@voltro/database 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as e, 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, Gt as m, H as h, Ht as g, I as ee, It as te, J as _, Jt as ne, K as re, Kt as v, L as ie, Lt as y, M as ae, Mt as oe, N as se, Nt as ce, O as le, Ot as ue, P as de, Pt as fe, Q as pe, R as me, Rt as b, S as he, St as ge, T as _e, Tt as ve, U as ye, Ut as be, V as xe, Vt as x, W as Se, Wt as Ce, X as we, Xt as S, Y as Te, Yt as C, Z as Ee, Zt as De, _ as Oe, _t as ke, a as Ae, at as je, b as Me, bt as Ne, c as Pe, ct as Fe, d as Ie, dt as Le, et as Re, f as ze, ft as Be, g as Ve, gt as He, h as Ue, ht as We, i as Ge, it as Ke, j as w, jt as qe, k as Je, kt as Ye, l as Xe, lt as Ze, m as Qe, mt as $e, n as et, nt as T, o as tt, ot as nt, p as E, pt as rt, q as it, qt as at, rt as ot, s as st, st as ct, t as lt, tt as ut, u as dt, ut as ft, v as pt, vt as mt, w as ht, wt as gt, x as _t, xt as vt, y as yt, yt as bt, z as xt, zt as D } from "./frameworkLiveTables-DNu6F6P8.js";
2
- import { timestampMs as St, timestampMsOrNull as Ct } from "./wire.js";
3
- import { Cause as wt, Chunk as Tt, Data as Et, Effect as O, Exit as Dt, Metric as k, MetricBoundaries as Ot, Option as A, Runtime as kt, Schedule as At, Schema as j, Stream as jt } from "effect";
4
- import { AsyncLocalStorage as Mt } from "node:async_hooks";
5
- import { createHash as Nt } from "node:crypto";
6
- import { TransactionConnection as Pt } from "@effect/sql/SqlClient";
7
- import { ansi as M } from "@voltro/logger";
8
- import { SqlClient as Ft } from "@effect/sql";
1
+ import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as ee, I as te, It as ne, J as re, Jt as ie, K as _, Kt as ae, L as v, Lt as oe, M as se, Mt as ce, N as le, Nt as ue, O as de, Ot as fe, P as pe, Pt as me, Q as he, Qt as y, R as ge, Rt as _e, S as ve, St as ye, T as be, Tt as xe, U as Se, Ut as b, V as Ce, Vt as x, W as we, Wt as Te, X as Ee, Xt as De, Y as Oe, Yt as ke, Z as Ae, Zt as S, _ as je, _t as Me, a as Ne, at as Pe, b as Fe, bt as Ie, c as Le, ct as Re, d as ze, dt as Be, et as Ve, f as He, ft as Ue, g as We, gt as Ge, h as Ke, ht as qe, i as Je, it as Ye, j as C, jt as Xe, k as Ze, kt as Qe, l as $e, lt as et, m as tt, mt as nt, n as rt, nt as w, o as it, ot as at, p as T, pt as ot, q as st, qt as ct, rt as lt, s as ut, st as dt, t as ft, tt as pt, u as mt, ut as ht, v as gt, vt as _t, w as vt, wt as yt, x as bt, xt, y as St, yt as Ct, z as wt, zt as Tt } from "./frameworkLiveTables-ChVR-C5F.js";
2
+ import { timestampMs as Et, timestampMsOrNull as Dt } from "./wire.js";
3
+ import { Cause as Ot, Chunk as kt, Data as At, Effect as E, Exit as jt, Metric as D, MetricBoundaries as Mt, Option as O, Runtime as Nt, Schedule as Pt, Schema as k, Stream as Ft } from "effect";
4
+ import { AsyncLocalStorage as It } from "node:async_hooks";
5
+ import { createHash as Lt } from "node:crypto";
6
+ import { TransactionConnection as Rt } from "@effect/sql/SqlClient";
7
+ import { ansi as A } from "@voltro/logger";
8
+ import { SqlClient as zt } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n) => {
10
+ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n) => {
11
11
  if (t != null && t !== "") try {
12
12
  let r = (await e.query({
13
13
  table: "actors",
@@ -23,20 +23,20 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: It(r.kind) ?? n,
27
- displayName: It(r.displayName),
28
- email: It(r.email)
26
+ type: Bt(r.kind) ?? n,
27
+ displayName: Bt(r.displayName),
28
+ email: Bt(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, Rt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", zt = (e) => {
33
+ }, Ht = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Ut = (e) => {
34
34
  let t = [];
35
35
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
36
36
  return t;
37
- }, Bt = (e, t, n) => {
38
- if (!Rt(n) || !t) return e;
39
- let r = zt(t);
37
+ }, Wt = (e, t, n) => {
38
+ if (!Ht(n) || !t) return e;
39
+ let r = Ut(t);
40
40
  if (r.length === 0) return e;
41
41
  let i = { ...e };
42
42
  for (let e of r) {
@@ -44,9 +44,9 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Vt = (e, t, n) => {
48
- if (!Rt(n) || !t) return e;
49
- let r = zt(t);
47
+ }, Gt = (e, t, n) => {
48
+ if (!Ht(n) || !t) return e;
49
+ let r = Ut(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,7 +58,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, Ht = "enc:v1:", Ut = class extends Error {
61
+ }, Kt = "enc:v1:", qt = class extends Error {
62
62
  _tag = "FieldDecryptionError";
63
63
  table;
64
64
  column;
@@ -66,7 +66,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
66
66
  constructor(e) {
67
67
  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;
68
68
  }
69
- }, Wt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Gt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Kt = (e, t) => e.encrypt(JSON.stringify(t)), qt = /* @__PURE__ */ new Set([
69
+ }, Jt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Yt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Xt = (e, t) => e.encrypt(JSON.stringify(t)), Zt = /* @__PURE__ */ new Set([
70
70
  "text",
71
71
  "id",
72
72
  "reference",
@@ -74,51 +74,51 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
74
74
  "uuid",
75
75
  "email",
76
76
  "url"
77
- ]), Jt = (e, t, n) => {
77
+ ]), Qt = (e, t, n) => {
78
78
  let r = e.decrypt(t), i;
79
79
  try {
80
80
  i = JSON.parse(r);
81
81
  } catch {
82
82
  return r;
83
83
  }
84
- return typeof i == "string" ? i : n === void 0 || qt.has(n) ? r : i;
85
- }, Yt = (e, t, n) => {
84
+ return typeof i == "string" ? i : n === void 0 || Zt.has(n) ? r : i;
85
+ }, $t = (e, t, n) => {
86
86
  let r = e.decrypt(t);
87
87
  try {
88
- return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || qt.has(n) ? !0 : void 0;
88
+ return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Zt.has(n) ? !0 : void 0;
89
89
  } catch {
90
90
  return !0;
91
91
  }
92
- }, Xt = (e, t) => e.fields[t]?.type, Zt = (e) => {
92
+ }, en = (e, t) => e.fields[t]?.type, tn = (e) => {
93
93
  let t = [];
94
94
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
95
95
  return t;
96
- }, Qt = (e, t, n) => {
96
+ }, nn = (e, t, n) => {
97
97
  if (!t) return e;
98
- let r = Zt(t);
98
+ let r = tn(t);
99
99
  if (r.length === 0) return e;
100
100
  let i = { ...e };
101
101
  for (let e of r) {
102
102
  let r = i[e];
103
- if (!(r == null || Gt(r))) {
103
+ if (!(r == null || Yt(r))) {
104
104
  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)`);
105
- i[e] = Kt(n, r);
105
+ i[e] = Xt(n, r);
106
106
  }
107
107
  }
108
108
  return i;
109
- }, $t = (e, t, n, r) => {
109
+ }, rn = (e, t, n, r) => {
110
110
  if (!t) return e;
111
- let i = Zt(t);
111
+ let i = tn(t);
112
112
  if (i.length === 0 || !n) return e;
113
113
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
114
114
  return e.map((e) => {
115
115
  let s;
116
116
  for (let c of i) {
117
117
  let i = e[c];
118
- if (Gt(i)) {
118
+ if (Yt(i)) {
119
119
  s ??= { ...e };
120
120
  try {
121
- s[c] = Jt(n, i, Xt(t, c));
121
+ s[c] = Qt(n, i, en(t, c));
122
122
  } catch (e) {
123
123
  let t = String(e?.message ?? e);
124
124
  if (a === "null") {
@@ -129,7 +129,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
129
129
  });
130
130
  continue;
131
131
  }
132
- throw new Ut({
132
+ throw new qt({
133
133
  table: o,
134
134
  column: c,
135
135
  reason: t
@@ -139,125 +139,125 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
139
139
  }
140
140
  return s ?? e;
141
141
  });
142
- }, en = (e) => {
142
+ }, an = (e) => {
143
143
  let t = e;
144
- for (let e = 0; e < 4 && kt.isFiberFailure(t); e++) t = wt.squash(t[kt.FiberFailureCauseId]);
144
+ for (let e = 0; e < 4 && Nt.isFiberFailure(t); e++) t = Ot.squash(t[Nt.FiberFailureCauseId]);
145
145
  return t;
146
- }, tn = (e, t = 0) => {
147
- if (t >= 4 || !kt.isFiberFailure(e)) return [e];
148
- let n = e[kt.FiberFailureCauseId], r = [...wt.failures(n), ...wt.defects(n)];
149
- if (r.length === 0) return [wt.squash(n)];
146
+ }, on = (e, t = 0) => {
147
+ if (t >= 4 || !Nt.isFiberFailure(e)) return [e];
148
+ let n = e[Nt.FiberFailureCauseId], r = [...Ot.failures(n), ...Ot.defects(n)];
149
+ if (r.length === 0) return [Ot.squash(n)];
150
150
  let i = [];
151
- for (let e of r.slice(0, 8)) i.push(...tn(e, t + 1));
151
+ for (let e of r.slice(0, 8)) i.push(...on(e, t + 1));
152
152
  return i;
153
- }, nn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, rn = (e) => {
154
- let t = {}, n = [], r = en(e);
153
+ }, sn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, cn = (e) => {
154
+ let t = {}, n = [], r = an(e);
155
155
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
156
156
  let e = r;
157
157
  t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
158
158
  let i = e.sqlMessage ?? e.detail;
159
159
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
160
160
  let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
161
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = en(e.cause);
161
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = an(e.cause);
162
162
  }
163
163
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
164
- }, an = (e) => {
165
- let t = tn(e).map(rn);
164
+ }, ln = (e) => {
165
+ let t = on(e).map(cn);
166
166
  if (t.length <= 1) return t[0] ?? {};
167
- let n = t.find(nn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
167
+ let n = t.find(sn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
168
168
  if (r.length === 0) return n;
169
169
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
170
170
  return {
171
171
  ...n,
172
172
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
173
173
  };
174
- }, on = /^[A-Za-z_][A-Za-z0-9_$]*$/, N = (e) => e !== void 0 && e.length <= 128 && on.test(e) ? e : void 0, sn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, P = (e, ...t) => {
174
+ }, un = /^[A-Za-z_][A-Za-z0-9_$]*$/, j = (e) => e !== void 0 && e.length <= 128 && un.test(e) ? e : void 0, dn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, M = (e, ...t) => {
175
175
  for (let n of t) {
176
176
  let t = n.exec(e);
177
177
  if (t?.[1] !== void 0) return t[1];
178
178
  }
179
- }, cn = (e, t) => {
179
+ }, fn = (e, t) => {
180
180
  let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
181
181
  if (n === "23503") {
182
- let t = N(e.dbConstraint);
182
+ let t = j(e.dbConstraint);
183
183
  return {
184
184
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
185
185
  ...t === void 0 ? {} : { constraint: t }
186
186
  };
187
187
  }
188
188
  if (n === "23505") {
189
- let t = N(e.dbConstraint);
189
+ let t = j(e.dbConstraint);
190
190
  return {
191
191
  kind: "unique",
192
192
  ...t === void 0 ? {} : { constraint: t }
193
193
  };
194
194
  }
195
195
  if (n === "23502") {
196
- let t = N(e.dbColumn);
196
+ let t = j(e.dbColumn);
197
197
  return {
198
198
  kind: "notNull",
199
199
  ...t === void 0 ? {} : { column: t }
200
200
  };
201
201
  }
202
202
  if (n === "23514") {
203
- let t = N(e.dbConstraint);
203
+ let t = j(e.dbConstraint);
204
204
  return {
205
205
  kind: "check",
206
206
  ...t === void 0 ? {} : { constraint: t }
207
207
  };
208
208
  }
209
209
  if (r === 1452 || r === 1451) {
210
- let e = N(P(o, /CONSTRAINT `([^`]+)`/));
210
+ let e = j(M(o, /CONSTRAINT `([^`]+)`/));
211
211
  return {
212
212
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
213
213
  ...e === void 0 ? {} : { constraint: e }
214
214
  };
215
215
  }
216
216
  if (r === 1062) {
217
- let e = N(sn(P(o, /for key '([^']+)'/)));
217
+ let e = j(dn(M(o, /for key '([^']+)'/)));
218
218
  return {
219
219
  kind: "unique",
220
220
  ...e === void 0 ? {} : { constraint: e }
221
221
  };
222
222
  }
223
223
  if (r === 1048 || r === 1364) {
224
- let e = N(P(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
224
+ let e = j(M(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
225
225
  return {
226
226
  kind: "notNull",
227
227
  ...e === void 0 ? {} : { column: e }
228
228
  };
229
229
  }
230
230
  if (r === 3819 || r === 4025) {
231
- let e = N(P(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
231
+ let e = j(M(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
232
232
  return {
233
233
  kind: "check",
234
234
  ...e === void 0 ? {} : { constraint: e }
235
235
  };
236
236
  }
237
237
  if (i === 547) {
238
- let e = P(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = P(o, /CHECK constraint "([^"]+)"/);
238
+ let e = M(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = M(o, /CHECK constraint "([^"]+)"/);
239
239
  if (t !== void 0 && e === void 0) {
240
- let e = N(t);
240
+ let e = j(t);
241
241
  return {
242
242
  kind: "check",
243
243
  ...e === void 0 ? {} : { constraint: e }
244
244
  };
245
245
  }
246
- let n = /REFERENCE constraint/.test(o), r = N(e);
246
+ let n = /REFERENCE constraint/.test(o), r = j(e);
247
247
  return {
248
248
  kind: n ? "foreignKeyInUse" : "foreignKey",
249
249
  ...r === void 0 ? {} : { constraint: r }
250
250
  };
251
251
  }
252
252
  if (i === 2627 || i === 2601) {
253
- let e = N(P(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
253
+ let e = j(M(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
254
254
  return {
255
255
  kind: "unique",
256
256
  ...e === void 0 ? {} : { constraint: e }
257
257
  };
258
258
  }
259
259
  if (i === 515) {
260
- let e = N(P(o, /Cannot insert the value NULL into column '([^']+)'/));
260
+ let e = j(M(o, /Cannot insert the value NULL into column '([^']+)'/));
261
261
  return {
262
262
  kind: "notNull",
263
263
  ...e === void 0 ? {} : { column: e }
@@ -265,34 +265,34 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
265
265
  }
266
266
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
267
267
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
268
- let e = N(sn(P(o, /UNIQUE constraint failed: ([^,\s]+)/)));
268
+ let e = j(dn(M(o, /UNIQUE constraint failed: ([^,\s]+)/)));
269
269
  return {
270
270
  kind: "unique",
271
271
  ...e === void 0 ? {} : { column: e }
272
272
  };
273
273
  }
274
274
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
275
- let e = N(sn(P(o, /NOT NULL constraint failed: ([^,\s]+)/)));
275
+ let e = j(dn(M(o, /NOT NULL constraint failed: ([^,\s]+)/)));
276
276
  return {
277
277
  kind: "notNull",
278
278
  ...e === void 0 ? {} : { column: e }
279
279
  };
280
280
  }
281
281
  if (n === "SQLITE_CONSTRAINT_CHECK") {
282
- let e = N(P(a, /CHECK constraint failed: (.+)$/));
282
+ let e = j(M(a, /CHECK constraint failed: (.+)$/));
283
283
  return {
284
284
  kind: "check",
285
285
  ...e === void 0 ? {} : { constraint: e }
286
286
  };
287
287
  }
288
- }, ln = (e) => {
289
- let t = cn(e)?.kind;
288
+ }, pn = (e) => {
289
+ let t = fn(e)?.kind;
290
290
  return t === "foreignKey" || t === "foreignKeyInUse";
291
- }, un = (e) => {
291
+ }, mn = (e) => {
292
292
  let t = e.dbCode, n = e.dbErrno;
293
293
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
294
- }, dn = (e) => {
295
- let t = an(e), n = [
294
+ }, hn = (e) => {
295
+ let t = ln(e), n = [
296
296
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
297
297
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
298
298
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
@@ -301,7 +301,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
301
301
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
302
302
  ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
303
303
  if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + s + o;
304
- }, fn = (e) => Object.entries(e).map(([e, t]) => `${e}:${pn(t)}`).join(" "), pn = (e) => {
304
+ }, gn = (e) => Object.entries(e).map(([e, t]) => `${e}:${_n(t)}`).join(" "), _n = (e) => {
305
305
  if (e === null) return "null";
306
306
  if (e === void 0) return "undefined";
307
307
  if (typeof e == "bigint") return "bigint";
@@ -311,62 +311,62 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
311
311
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
312
312
  let t = e.constructor?.name;
313
313
  return typeof t == "string" && t !== "" ? t : "Object";
314
- }, mn = (e) => {
314
+ }, vn = (e) => {
315
315
  let t = (() => {
316
316
  switch (e.type) {
317
317
  case "id":
318
318
  case "reference":
319
319
  case "text":
320
- case "enum": return j.String;
320
+ case "enum": return k.String;
321
321
  case "integer":
322
322
  case "real":
323
- case "decimal": return j.Number;
324
- case "boolean": return j.Boolean;
323
+ case "decimal": return k.Number;
324
+ case "boolean": return k.Boolean;
325
325
  case "timestamp":
326
- case "date": return St;
327
- case "bigint": return j.BigInt;
328
- case "bytes": return j.Uint8ArrayFromBase64;
329
- case "array": return j.Array(j.Unknown);
330
- case "interval": return j.String;
331
- default: return j.Unknown;
326
+ case "date": return Et;
327
+ case "bigint": return k.BigInt;
328
+ case "bytes": return k.Uint8ArrayFromBase64;
329
+ case "array": return k.Array(k.Unknown);
330
+ case "interval": return k.String;
331
+ default: return k.Unknown;
332
332
  }
333
333
  })();
334
- return e.nullable === !0 ? j.NullOr(t) : t;
335
- }, hn = (e, t) => {
334
+ return e.nullable === !0 ? k.NullOr(t) : t;
335
+ }, yn = (e, t) => {
336
336
  let n = new Set(t?.omit ?? []), r = {};
337
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = mn(i));
338
- return j.Struct(r);
339
- }, gn = (e) => typeof e == "function" ? e : () => e, _n = (e, t) => ({
337
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = vn(i));
338
+ return k.Struct(r);
339
+ }, bn = (e) => typeof e == "function" ? e : () => e, xn = (e, t) => ({
340
340
  kind: "one",
341
- target: gn(e),
341
+ target: bn(e),
342
342
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
343
343
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
344
- }), vn = (e, t) => ({
344
+ }), Sn = (e, t) => ({
345
345
  kind: "many",
346
- target: gn(e),
346
+ target: bn(e),
347
347
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
348
348
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
349
- }), yn = (e, t) => ({
349
+ }), Cn = (e, t) => ({
350
350
  kind: "manyToMany",
351
- target: gn(e),
352
- through: gn(t.through),
351
+ target: bn(e),
352
+ through: bn(t.through),
353
353
  sourceKey: t.sourceKey,
354
354
  targetKey: t.targetKey
355
- }), bn = {
356
- one: _n,
357
- many: vn,
358
- manyToMany: yn
359
- }, xn = (e, t) => {
355
+ }), wn = {
356
+ one: xn,
357
+ many: Sn,
358
+ manyToMany: Cn
359
+ }, Tn = (e, t) => {
360
360
  let n = typeof e == "function" ? e : () => e;
361
361
  return {
362
362
  source: n,
363
- relations: t(bn, n())
363
+ relations: t(wn, n())
364
364
  };
365
- }, Sn = (e) => {
365
+ }, En = (e) => {
366
366
  if (typeof e != "object" || !e) return !1;
367
367
  let t = e;
368
368
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
369
- }, Cn = (e) => {
369
+ }, Dn = (e) => {
370
370
  if (typeof e != "object" || !e) return !1;
371
371
  let t = e;
372
372
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -375,35 +375,35 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
375
375
  let t = e?.kind;
376
376
  return t === "one" || t === "many" || t === "manyToMany";
377
377
  });
378
- }, wn = _n, Tn = vn, En = yn, Dn = (e, t, n) => {
378
+ }, On = xn, kn = Sn, An = Cn, jn = (e, t, n) => {
379
379
  let r = [];
380
380
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
381
381
  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>' }.`);
382
382
  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.`);
383
383
  return r[0];
384
- }, On = (e) => Object.keys(e.fields), kn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), An = (e) => {
385
- let t = On(e);
384
+ }, Mn = (e) => Object.keys(e.fields), Nn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Pn = (e) => {
385
+ let t = Mn(e);
386
386
  return t.length === 0 ? "<none>" : t.join(", ");
387
- }, jn = (e, t, n) => {
387
+ }, Fn = (e, t, n) => {
388
388
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
389
389
  if (n.kind === "manyToMany") {
390
390
  let t = n.through();
391
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!kn(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}': ${An(t)}.`);
391
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Nn(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}': ${Pn(t)}.`);
392
392
  return;
393
393
  }
394
394
  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.`);
395
- if (n.sourceKey !== void 0 && !kn(e, n.sourceKey)) {
396
- let t = kn(i, n.sourceKey);
397
- 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}': ${An(e)}.`));
395
+ if (n.sourceKey !== void 0 && !Nn(e, n.sourceKey)) {
396
+ let t = Nn(i, n.sourceKey);
397
+ 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}': ${Pn(e)}.`));
398
398
  }
399
- if (n.foreignKey !== void 0 && !kn(i, n.foreignKey)) {
400
- let t = kn(e, n.foreignKey);
401
- 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}': ${An(i)}.`));
399
+ if (n.foreignKey !== void 0 && !Nn(i, n.foreignKey)) {
400
+ let t = Nn(e, n.foreignKey);
401
+ 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}': ${Pn(i)}.`));
402
402
  }
403
- }, Mn = Symbol.for("@voltro/database/relationsRegistry"), Nn = globalThis, F = Nn[Mn] ?? (Nn[Mn] = /* @__PURE__ */ new Map()), Pn = (e) => {
404
- let t = e.source(), n = F.get(t.tableName);
403
+ }, In = Symbol.for("@voltro/database/relationsRegistry"), Ln = globalThis, N = Ln[In] ?? (Ln[In] = /* @__PURE__ */ new Map()), Rn = (e) => {
404
+ let t = e.source(), n = N.get(t.tableName);
405
405
  if (n === void 0) {
406
- F.set(t.tableName, new Map(Object.entries(e.relations)));
406
+ N.set(t.tableName, new Map(Object.entries(e.relations)));
407
407
  return;
408
408
  }
409
409
  for (let [r, i] of Object.entries(e.relations)) {
@@ -413,33 +413,33 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
413
413
  n.set(r, i);
414
414
  }
415
415
  }
416
- }, Fn = (e) => {
416
+ }, zn = (e) => {
417
417
  let t = 0;
418
- for (let n of Object.values(e)) Cn(n) && (Pn(n), t += 1);
418
+ for (let n of Object.values(e)) Dn(n) && (Rn(n), t += 1);
419
419
  return t;
420
- }, In = (e) => {
421
- let t = F.get(e);
420
+ }, Bn = (e) => {
421
+ let t = N.get(e);
422
422
  if (t !== void 0) return Object.fromEntries(t);
423
- }, Ln = (e, t) => F.get(e)?.get(t), Rn = () => {
423
+ }, Vn = (e, t) => N.get(e)?.get(t), Hn = () => {
424
424
  let e = [];
425
- for (let [t, n] of F) for (let [r, i] of n) e.push({
425
+ for (let [t, n] of N) for (let [r, i] of n) e.push({
426
426
  source: t,
427
427
  name: r,
428
428
  relation: i
429
429
  });
430
430
  return e;
431
- }, zn = () => {
432
- for (let [e, t] of F) {
433
- let n = p(e);
434
- if (n !== void 0) for (let [e, r] of t) jn(n, e, r);
435
- }
436
- }, Bn = () => {
437
- F.clear();
438
- }, Vn = 4, Hn = (e) => Object.keys(e.fields), Un = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Wn = (e, t) => {
431
+ }, Un = () => {
432
+ for (let [e, t] of N) {
433
+ let n = m(e);
434
+ if (n !== void 0) for (let [e, r] of t) Fn(n, e, r);
435
+ }
436
+ }, Wn = () => {
437
+ N.clear();
438
+ }, Gn = 4, Kn = (e) => Object.keys(e.fields), qn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Jn = (e, t) => {
439
439
  let n = [];
440
440
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
441
441
  return n;
442
- }, Gn = (e, t) => {
442
+ }, Yn = (e, t) => {
443
443
  let n = [];
444
444
  for (let r of t) {
445
445
  if (r.source !== e) continue;
@@ -456,7 +456,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
456
456
  } catch {
457
457
  continue;
458
458
  }
459
- if (!Un(e, t.sourceKey)) continue;
459
+ if (!qn(e, t.sourceKey)) continue;
460
460
  n.push({
461
461
  table: e.tableName,
462
462
  foreignKey: t.sourceKey,
@@ -465,24 +465,24 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
465
465
  continue;
466
466
  }
467
467
  if (t.sourceKey !== void 0) continue;
468
- let a = Wn(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
469
- o === void 0 || !Un(i, o) || n.push({
468
+ let a = Jn(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
469
+ o === void 0 || !qn(i, o) || n.push({
470
470
  table: i.tableName,
471
471
  foreignKey: o,
472
472
  parentKey: "id"
473
473
  });
474
474
  }
475
475
  return n;
476
- }, Kn = (e, t) => {
476
+ }, Xn = (e, t) => {
477
477
  let n = [];
478
- for (let r of t) if (r.tableName !== e) for (let t of Wn(r, e)) n.push({
478
+ for (let r of t) if (r.tableName !== e) for (let t of Jn(r, e)) n.push({
479
479
  table: r.tableName,
480
480
  foreignKey: t,
481
481
  parentKey: "id"
482
482
  });
483
483
  return n;
484
- }, qn = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Jn = (e) => {
485
- let t = e.tables ?? h(), n = e.relations ?? Rn(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
484
+ }, Zn = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Qn = (e) => {
485
+ let t = e.tables ?? g(), n = e.relations ?? Hn(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
486
486
  if (!a.has(e.subjectTable)) return {
487
487
  subjectTable: e.subjectTable,
488
488
  paths: [],
@@ -497,11 +497,11 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
497
497
  hops: [],
498
498
  depth: 0,
499
499
  via: "relation"
500
- }, c = [s], l = /* @__PURE__ */ new Set([qn(s)]), u = /* @__PURE__ */ new Set(), d = [s];
500
+ }, c = [s], l = /* @__PURE__ */ new Set([Zn(s)]), u = /* @__PURE__ */ new Set(), d = [s];
501
501
  for (let e = 1; e <= r; e++) {
502
502
  let r = [];
503
503
  for (let a of d) {
504
- let s = Gn(a.table, n), d = Kn(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
504
+ let s = Yn(a.table, n), d = Xn(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
505
505
  for (let [t, n] of f) {
506
506
  if (i.has(t.table)) {
507
507
  o.push({
@@ -519,7 +519,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
519
519
  hops: [...a.hops, t],
520
520
  depth: e,
521
521
  via: n
522
- }, f = qn(d);
522
+ }, f = Zn(d);
523
523
  l.has(f) || (l.add(f), c.push(d), r.push(d));
524
524
  }
525
525
  }
@@ -529,7 +529,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
529
529
  }
530
530
  d = r;
531
531
  }
532
- for (let e of d) (Gn(e.table, n).length > 0 || Kn(e.table, t).length > 0) && o.push({
532
+ for (let e of d) (Yn(e.table, n).length > 0 || Xn(e.table, t).length > 0) && o.push({
533
533
  kind: "depth-truncated",
534
534
  table: e.table,
535
535
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
@@ -538,14 +538,14 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
538
538
  for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
539
539
  kind: "unreachable",
540
540
  table: n.tableName,
541
- detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${Hn(n).join(", ")}`
541
+ detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${Kn(n).join(", ")}`
542
542
  });
543
543
  return {
544
544
  subjectTable: e.subjectTable,
545
545
  paths: c,
546
546
  limitations: o
547
547
  };
548
- }, Yn = (e) => {
548
+ }, $n = (e) => {
549
549
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
550
550
  for (let n of e.paths) {
551
551
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -553,7 +553,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
553
553
  }
554
554
  let n = e.limitations.filter((e) => e.kind === "depth-truncated"), r = e.limitations.filter((e) => e.kind === "unreachable"), i = e.limitations.filter((e) => e.kind === "excluded");
555
555
  return t.push(""), t.push(" WHAT THIS CANNOT SEE — a DSAR is only as complete as this list is short:"), n.length > 0 && t.push(` depth-truncated (${n.length}): ${n.map((e) => e.table).join(", ")}`), i.length > 0 && t.push(` excluded (${i.length}): ${[...new Set(i.map((e) => e.table))].join(", ")}`), t.push(r.length === 0 ? " unreachable: none — every registered table is linked to the subject." : ` unreachable (${r.length}): ${r.map((e) => e.table).join(", ")}`), t.push(" Always outside this graph: object storage / uploaded files, external processors,"), t.push(" log and metric sinks, backups, and any subject id embedded in JSON or free text."), t.join("\n");
556
- }, Xn = (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, Zn = (e) => {
556
+ }, er = (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, tr = (e) => {
557
557
  if (e == null || typeof e != "string") return e;
558
558
  let t = e.trim();
559
559
  if (t.length === 0) return e;
@@ -564,7 +564,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
564
564
  } catch {
565
565
  return e;
566
566
  }
567
- }, Qn = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, $n = (e) => {
567
+ }, nr = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, rr = (e) => {
568
568
  if (e == null || e instanceof Date) return e;
569
569
  if (typeof e == "string") {
570
570
  let t = new Date(e);
@@ -575,21 +575,21 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
575
575
  return isNaN(t.getTime()) ? e : t;
576
576
  }
577
577
  return e;
578
- }, er = (e, t, n) => {
578
+ }, ir = (e, t, n) => {
579
579
  if (e == null) return e;
580
580
  switch (t) {
581
- case "boolean": return n === "postgres" ? e : Xn(e);
581
+ case "boolean": return n === "postgres" ? e : er(e);
582
582
  case "json":
583
- case "array": return n === "postgres" ? e : Zn(e);
583
+ case "array": return n === "postgres" ? e : tr(e);
584
584
  case "timestamp":
585
- case "date": return n === "sqlite" || n === "turso" ? $n(e) : e;
585
+ case "date": return n === "sqlite" || n === "turso" ? rr(e) : e;
586
586
  case "decimal":
587
- case "bigint": return Qn(e);
587
+ case "bigint": return nr(e);
588
588
  default: return e;
589
589
  }
590
- }, tr = (e, t, n) => {
590
+ }, ar = (e, t, n) => {
591
591
  if (e.length === 0) return e;
592
- let r = p(t);
592
+ let r = m(t);
593
593
  if (r === void 0) return e;
594
594
  let i = r.fields, a = [];
595
595
  for (let [e, t] of Object.entries(i)) a.push({
@@ -598,36 +598,36 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
598
598
  });
599
599
  return e.map((e) => {
600
600
  let t = { ...e };
601
- for (let { key: e, type: r } of a) e in t && (t[e] = er(t[e], r, n));
601
+ for (let { key: e, type: r } of a) e in t && (t[e] = ir(t[e], r, n));
602
602
  return t;
603
603
  });
604
- }, nr = (e, t) => {
604
+ }, or = (e, t) => {
605
605
  if (e == null) return e;
606
606
  switch (t) {
607
607
  case "json":
608
608
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
609
609
  default: return e;
610
610
  }
611
- }, rr = (e, t, n = ["json", "array"]) => {
612
- let r = p(t);
611
+ }, sr = (e, t, n = ["json", "array"]) => {
612
+ let r = m(t);
613
613
  if (r === void 0) return e;
614
614
  let i = r.fields, a = null;
615
615
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
616
- let n = nr(e[t], r.type);
616
+ let n = or(e[t], r.type);
617
617
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
618
618
  }
619
619
  return a ?? e;
620
- }, ir = class extends Error {
620
+ }, cr = class extends Error {
621
621
  _tag = "EagerCardinalityError";
622
622
  constructor(e) {
623
623
  super(e), this.name = "EagerCardinalityError";
624
624
  }
625
- }, ar = (e) => {
625
+ }, lr = (e) => {
626
626
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
627
627
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
628
- }, or = async (e, t, n, r) => {
628
+ }, ur = async (e, t, n, r) => {
629
629
  if (e.length === 0) return e;
630
- let i = In(n.tableName);
630
+ let i = Bn(n.tableName);
631
631
  if (i === void 0) throw Error(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
632
632
  let a = e.map((e) => ({ ...e }));
633
633
  for (let [e, o] of Object.entries(t)) {
@@ -636,36 +636,36 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
636
636
  let t = Object.keys(i).join(", ") || "<none>";
637
637
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
638
638
  }
639
- jn(n, e, t), await sr(a, e, t, o === !0 ? {} : o, n, r);
639
+ Fn(n, e, t), await dr(a, e, t, o === !0 ? {} : o, n, r);
640
640
  }
641
641
  return a;
642
- }, sr = async (e, t, n, r, i, a) => {
642
+ }, dr = async (e, t, n, r, i, a) => {
643
643
  switch (n.kind) {
644
644
  case "one":
645
- await cr(e, t, n, r, i, a);
645
+ await fr(e, t, n, r, i, a);
646
646
  return;
647
647
  case "many":
648
- await lr(e, t, n, r, i, a);
648
+ await pr(e, t, n, r, i, a);
649
649
  return;
650
650
  case "manyToMany":
651
- await dr(e, t, n, r, i, a);
651
+ await hr(e, t, n, r, i, a);
652
652
  return;
653
653
  }
654
- }, cr = async (e, t, n, r, i, a) => {
655
- let o = n.target(), s = n.sourceKey ?? fr(i, o.tableName);
654
+ }, fr = async (e, t, n, r, i, a) => {
655
+ let o = n.target(), s = n.sourceKey ?? gr(i, o.tableName);
656
656
  if (s !== void 0) {
657
- let n = pr(e, s), i = n.length === 0 ? [] : await mr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
657
+ let n = P(e, s), i = n.length === 0 ? [] : await _r(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
658
658
  for (let n of e) {
659
659
  let e = n[s];
660
660
  n[t] = e == null ? null : c.get(e) ?? null;
661
661
  }
662
- await hr(i, r.with, o, a);
662
+ await vr(i, r.with, o, a);
663
663
  return;
664
664
  }
665
- let c = n.foreignKey ?? Dn(o, i.tableName, t), l = n.sourceKey ?? "id", u = pr(e, l), d = u.length === 0 ? [] : await mr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
665
+ let c = n.foreignKey ?? jn(o, i.tableName, t), l = n.sourceKey ?? "id", u = P(e, l), d = u.length === 0 ? [] : await _r(o, c, u, r, a), f = /* @__PURE__ */ new Map();
666
666
  for (let e of d) {
667
667
  let n = e[c];
668
- if (f.has(n)) throw new ir(ar({
668
+ if (f.has(n)) throw new cr(lr({
669
669
  relationName: t,
670
670
  sourceTableName: i.tableName,
671
671
  targetTableName: o.tableName,
@@ -678,9 +678,9 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
678
678
  let e = n[l];
679
679
  n[t] = e == null ? null : f.get(e) ?? null;
680
680
  }
681
- await hr(d, r.with, o, a);
682
- }, lr = async (e, t, n, r, i, a) => {
683
- let o = n.target(), s = n.foreignKey ?? Dn(o, i.tableName, t), c = n.sourceKey ?? "id", l = pr(e, c), u = ur(r), d = l.length === 0 ? [] : await mr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
681
+ await vr(d, r.with, o, a);
682
+ }, pr = async (e, t, n, r, i, a) => {
683
+ let o = n.target(), s = n.foreignKey ?? jn(o, i.tableName, t), c = n.sourceKey ?? "id", l = P(e, c), u = mr(r), d = l.length === 0 ? [] : await _r(o, s, l, u, a), f = /* @__PURE__ */ new Map();
684
684
  for (let e of d) {
685
685
  let t = e[s], n = f.get(t);
686
686
  n ? n.push(e) : f.set(t, [e]);
@@ -696,12 +696,12 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
696
696
  let e = n[c];
697
697
  n[t] = f.get(e) ?? [];
698
698
  }
699
- await hr(d, r.with, o, a);
700
- }, ur = (e) => {
699
+ await vr(d, r.with, o, a);
700
+ }, mr = (e) => {
701
701
  let { limit: t, offset: n, ...r } = e;
702
702
  return r;
703
- }, dr = async (e, t, n, r, i, a) => {
704
- let o = n.target(), s = n.through(), c = pr(e, "id");
703
+ }, hr = async (e, t, n, r, i, a) => {
704
+ let o = n.target(), s = n.through(), c = P(e, "id");
705
705
  if (c.length === 0) {
706
706
  for (let n of e) n[t] = [];
707
707
  return;
@@ -722,8 +722,8 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
722
722
  for (let n of e) n[t] = [];
723
723
  return;
724
724
  }
725
- let f = await mr(o, "id", pr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
726
- await hr(f, r.with, o, a);
725
+ let f = await _r(o, "id", P(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
726
+ await vr(f, r.with, o, a);
727
727
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
728
728
  for (let e of d) {
729
729
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -735,16 +735,16 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
735
735
  o ? o.push(a) : h.set(t, [a]);
736
736
  }
737
737
  for (let n of e) n[t] = h.get(n.id) ?? [];
738
- }, fr = (e, t) => {
738
+ }, gr = (e, t) => {
739
739
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
740
- }, pr = (e, t) => {
740
+ }, P = (e, t) => {
741
741
  let n = /* @__PURE__ */ new Set();
742
742
  for (let r of e) {
743
743
  let e = r[t];
744
744
  e != null && n.add(e);
745
745
  }
746
746
  return [...n];
747
- }, mr = (e, t, n, r, i) => {
747
+ }, _r = (e, t, n, r, i) => {
748
748
  let a = {
749
749
  column: t,
750
750
  op: "in",
@@ -758,70 +758,70 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
758
758
  skip: r.offset,
759
759
  projection: void 0
760
760
  });
761
- }, hr = async (e, t, n, r) => {
762
- t !== void 0 && e.length !== 0 && (await or(e, t, n, r)).forEach((t, n) => {
761
+ }, vr = async (e, t, n, r) => {
762
+ t !== void 0 && e.length !== 0 && (await ur(e, t, n, r)).forEach((t, n) => {
763
763
  let r = e[n];
764
764
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
765
765
  });
766
- }, gr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, _r = class extends Error {
766
+ }, yr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, br = class extends Error {
767
767
  _tag = "TenantNamespaceUnresolved";
768
768
  constructor(e) {
769
769
  super(e), this.name = "TenantNamespaceUnresolved";
770
770
  }
771
- }, vr = class extends Error {
771
+ }, xr = class extends Error {
772
772
  _tag = "TenantNamespaceInvalid";
773
773
  constructor(e) {
774
774
  super(e), this.name = "TenantNamespaceInvalid";
775
775
  }
776
- }, yr = 63, br = "tenant_", xr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Sr = (e) => {
777
- if (e == null || e === "") throw new _r("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.");
778
- let t = xr(e);
779
- if (t.replace(/_/g, "") === "") throw new vr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
780
- let n = `${br}${t}`;
781
- if (n.length > yr) throw new vr(`namespace '${n}' for tenant '${e}' exceeds the ${yr}-byte identifier limit. Use a shorter tenant id.`);
776
+ }, Sr = 63, Cr = "tenant_", wr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Tr = (e) => {
777
+ if (e == null || e === "") throw new br("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.");
778
+ let t = wr(e);
779
+ if (t.replace(/_/g, "") === "") throw new xr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
780
+ let n = `${Cr}${t}`;
781
+ if (n.length > Sr) throw new xr(`namespace '${n}' for tenant '${e}' exceeds the ${Sr}-byte identifier limit. Use a shorter tenant id.`);
782
782
  return n;
783
- }, Cr = (e, t) => e === null ? t : `${e}.${t}`, wr = /* @__PURE__ */ new Set(["timestamp", "date"]), Tr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Er = (e, t) => {
784
- if (e === void 0 || t == null || !wr.has(e) || t instanceof Date) return t;
783
+ }, Er = (e, t) => e === null ? t : `${e}.${t}`, Dr = /* @__PURE__ */ new Set(["timestamp", "date"]), Or = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, kr = (e, t) => {
784
+ if (e === void 0 || t == null || !Dr.has(e) || t instanceof Date) return t;
785
785
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
786
- if (typeof t == "string" && Tr.test(t)) {
786
+ if (typeof t == "string" && Or.test(t)) {
787
787
  let e = new Date(t);
788
788
  return Number.isNaN(e.getTime()) ? t : e;
789
789
  }
790
790
  return t;
791
- }, Dr = (e, t) => e === void 0 || !wr.has(e) ? t : t.map((t) => Er(e, t)), Or = (e, t) => {
791
+ }, Ar = (e, t) => e === void 0 || !Dr.has(e) ? t : t.map((t) => kr(e, t)), jr = (e, t) => {
792
792
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
793
793
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
794
794
  return t`${i}`;
795
- }, kr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), I = (e, t, n = null, r) => {
795
+ }, F = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), I = (e, t, n = null, r) => {
796
796
  if ("not" in e) return t`NOT (${I(e.not, t, n, r)})`;
797
797
  if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => I(e, t, n, r)));
798
798
  if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => I(e, t, n, r)));
799
799
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
800
- let r = e, i = Br(r.subquery, t, n);
800
+ let r = e, i = Hr(r.subquery, t, n);
801
801
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
802
802
  }
803
803
  if (e.op === "exists" || e.op === "not-exists") {
804
- let r = e, i = Br(r.subquery, t, n);
804
+ let r = e, i = Hr(r.subquery, t, n);
805
805
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
806
806
  }
807
807
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
808
- mysql: () => t.unsafe(E(i.column, o, "mysql")),
809
- mssql: () => t.unsafe(E(i.column, o, "mssql")),
810
- sqlite: () => t.unsafe(E(i.column, o, "sqlite")),
811
- orElse: () => t.unsafe(E(i.column, o, "postgres"))
808
+ mysql: () => t.unsafe(T(i.column, o, "mysql")),
809
+ mssql: () => t.unsafe(T(i.column, o, "mssql")),
810
+ sqlite: () => t.unsafe(T(i.column, o, "sqlite")),
811
+ orElse: () => t.unsafe(T(i.column, o, "postgres"))
812
812
  }), l = () => t.onDialectOrElse({
813
- mysql: () => t.unsafe(E(i.column, o, "mysql", { numeric: !0 })),
814
- mssql: () => t.unsafe(E(i.column, o, "mssql", { numeric: !0 })),
815
- sqlite: () => t.unsafe(E(i.column, o, "sqlite", { numeric: !0 })),
816
- orElse: () => t.unsafe(E(i.column, o, "postgres", { numeric: !0 }))
817
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, m = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : p(r)?.fields?.[i.column]?.type, g = (e) => Er(h, e);
813
+ mysql: () => t.unsafe(T(i.column, o, "mysql", { numeric: !0 })),
814
+ mssql: () => t.unsafe(T(i.column, o, "mssql", { numeric: !0 })),
815
+ sqlite: () => t.unsafe(T(i.column, o, "sqlite", { numeric: !0 })),
816
+ orElse: () => t.unsafe(T(i.column, o, "postgres", { numeric: !0 }))
817
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : m(r)?.fields?.[i.column]?.type, g = (e) => kr(h, e);
818
818
  switch (i.op) {
819
819
  case "eq": return t`${u} = ${f(g(i.value))}`;
820
820
  case "neq": return t`${u} <> ${f(g(i.value))}`;
821
- case "gt": return t`${d} > ${m(i.value)}`;
822
- case "gte": return t`${d} >= ${m(i.value)}`;
823
- case "lt": return t`${d} < ${m(i.value)}`;
824
- case "lte": return t`${d} <= ${m(i.value)}`;
821
+ case "gt": return t`${d} > ${p(i.value)}`;
822
+ case "gte": return t`${d} >= ${p(i.value)}`;
823
+ case "lt": return t`${d} < ${p(i.value)}`;
824
+ case "lte": return t`${d} <= ${p(i.value)}`;
825
825
  case "in": {
826
826
  let e = i.value ?? [];
827
827
  return e.length === 0 ? t`FALSE` : t`${u} IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
@@ -831,7 +831,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
831
831
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
832
832
  }
833
833
  case "contains": {
834
- let e = `%${kr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
834
+ let e = `%${F(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
835
835
  return t.onDialectOrElse({
836
836
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
837
837
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -840,7 +840,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
840
840
  });
841
841
  }
842
842
  case "startsWith": {
843
- let e = `${kr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
843
+ let e = `${F(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
844
844
  return t.onDialectOrElse({
845
845
  mysql: () => t`${u} LIKE ${e}`,
846
846
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -888,13 +888,13 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
888
888
  });
889
889
  }
890
890
  }
891
- }, Ar = (e, t) => {
891
+ }, Mr = (e, t) => {
892
892
  let n = [];
893
893
  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}`);
894
- }, jr = (e, t) => t.csv(e.map((e) => {
894
+ }, Nr = (e, t) => t.csv(e.map((e) => {
895
895
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
896
896
  if (e.op.startsWith("window-")) {
897
- let r = Ar(e.window ?? {}, t);
897
+ let r = Mr(e.window ?? {}, t);
898
898
  switch (e.op) {
899
899
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
900
900
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -918,44 +918,44 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
918
918
  return t`${t(e.column)} AS ${t(e.alias)}`;
919
919
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
920
920
  }
921
- })), Mr = (e) => `[${e.join(",")}]`, Nr = (e, t) => {
921
+ })), Pr = (e) => `[${e.join(",")}]`, Fr = (e, t) => {
922
922
  if (e.queryVector === void 0) return null;
923
- let n = t(e.column), r = Mr(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
923
+ let n = t(e.column), r = Pr(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
924
924
  return t.onDialectOrElse({
925
925
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
926
926
  mssql: () => t`NULL`,
927
927
  sqlite: () => t`NULL`,
928
928
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
929
929
  });
930
- }, Pr = (e, t) => {
930
+ }, Ir = (e, t) => {
931
931
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
932
932
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
933
- }, Fr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Ir = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Lr = (e, t) => `${t}_${e.indexName}_fts`, Rr = (e, t, n) => {
934
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${kr(e.query)}%`;
933
+ }, Lr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Rr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, zr = (e, t) => `${t}_${e.indexName}_fts`, Br = (e, t, n) => {
934
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${F(e.query)}%`;
935
935
  return n.onDialectOrElse({
936
936
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
937
937
  sqlite: () => {
938
- let r = n(Lr(e, t));
938
+ let r = n(zr(e, t));
939
939
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
940
940
  },
941
941
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
942
- orElse: () => n`${Ir(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
942
+ orElse: () => n`${Rr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
943
943
  });
944
- }, zr = (e, t, n) => {
945
- let r = `%${kr(e.query)}%`;
944
+ }, Vr = (e, t, n) => {
945
+ let r = `%${F(e.query)}%`;
946
946
  return n.onDialectOrElse({
947
947
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
948
948
  sqlite: () => {
949
- let r = n(Lr(e, t));
949
+ let r = n(zr(e, t));
950
950
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
951
951
  },
952
952
  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}`),
953
- orElse: () => n`ts_rank(${Ir(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
953
+ orElse: () => n`ts_rank(${Rr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
954
954
  });
955
- }, Br = (e, t, n = null) => {
955
+ }, Hr = (e, t, n = null) => {
956
956
  if (e.setOp && e.setOp.queries.length >= 2) {
957
- 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`(${Br(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
958
- if (w(e).length > 0 && a.push(t` ORDER BY ${t.csv(w(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
957
+ 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`(${Hr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
958
+ if (C(e).length > 0 && a.push(t` ORDER BY ${t.csv(C(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
959
959
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
960
960
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
961
961
  }
@@ -965,7 +965,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
965
965
  }
966
966
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
967
967
  }
968
- let r = e.annClause === void 0 ? null : Nr(e.annClause, t);
968
+ let r = e.annClause === void 0 ? null : Fr(e.annClause, t);
969
969
  e.spatialClause !== void 0 && t.onDialectOrElse({
970
970
  mysql: () => {
971
971
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -978,57 +978,57 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
978
978
  },
979
979
  orElse: () => t``
980
980
  });
981
- let i = e.spatialClause?.projectAs === void 0 ? null : Pr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? jr(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 ? zr(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({
981
+ let i = e.spatialClause?.projectAs === void 0 ? null : Ir(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Nr(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 ? Vr(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({
982
982
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
983
983
  mysql: () => t`DISTINCT `,
984
984
  mssql: () => t`DISTINCT `,
985
985
  sqlite: () => t`DISTINCT `
986
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Cr(n, e.table))}` : t`${t(Cr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
986
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Er(n, e.table))}` : t`${t(Er(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
987
987
  let r = e.kind === "inner" ? "INNER" : "LEFT";
988
- return t` ${t.unsafe(r)} JOIN ${t(Cr(n, e.table))} AS ${t(e.alias)} ON ${I(e.on, t, n)}`;
989
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Rr(c, e.table, t), ee = [e.predicate ? I(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, _ = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ne = e.having ? t` HAVING ${I(e.having, t, n, e.table)}` : t``, re = e.skip !== void 0, v = [];
990
- r !== null && v.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && v.push(e.spatialClause.order === "desc" ? t`${Fr(e.spatialClause, t)} DESC` : t`${Fr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && v.push(t`${l} DESC`);
991
- for (let n of w(e)) v.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
992
- let ie = v.length > 0 ? t` ORDER BY ${t.csv(v)}` : re ? t.onDialectOrElse({
988
+ return t` ${t.unsafe(r)} JOIN ${t(Er(n, e.table))} AS ${t(e.alias)} ON ${I(e.on, t, n)}`;
989
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Br(c, e.table, t), ee = [e.predicate ? I(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, ne = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, re = e.having ? t` HAVING ${I(e.having, t, n, e.table)}` : t``, ie = e.skip !== void 0, _ = [];
990
+ r !== null && _.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && _.push(e.spatialClause.order === "desc" ? t`${Lr(e.spatialClause, t)} DESC` : t`${Lr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && _.push(t`${l} DESC`);
991
+ for (let n of C(e)) _.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
992
+ let ae = _.length > 0 ? t` ORDER BY ${t.csv(_)}` : ie ? t.onDialectOrElse({
993
993
  mssql: () => t` ORDER BY (SELECT NULL)`,
994
994
  orElse: () => t``
995
- }) : t``, y = (e) => {
995
+ }) : t``, v = (e) => {
996
996
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
997
997
  return t.unsafe(String(e));
998
- }, ae = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Br(e.descriptor, t, n)})`), oe = (e.ctes ?? []).some((e) => e.recursive === !0), se = ae.length > 0 ? t`WITH ${t.unsafe(oe ? "RECURSIVE " : "")}${t.csv(ae)} ` : t``;
998
+ }, oe = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Hr(e.descriptor, t, n)})`), se = (e.ctes ?? []).some((e) => e.recursive === !0), ce = oe.length > 0 ? t`WITH ${t.unsafe(se ? "RECURSIVE " : "")}${t.csv(oe)} ` : t``;
999
999
  return t.onDialectOrElse({
1000
1000
  mssql: () => {
1001
- let n = e.take !== void 0 && !re ? t`TOP ${y(e.take)} ` : t``, r = re ? t` OFFSET ${y(e.skip)} ROWS FETCH NEXT ${y(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1002
- return t`${se}SELECT ${n}${f}${d} FROM ${h}${te}${_}${ne}${ie}${r}`;
1001
+ let n = e.take !== void 0 && !ie ? t`TOP ${v(e.take)} ` : t``, r = ie ? t` OFFSET ${v(e.skip)} ROWS FETCH NEXT ${v(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1002
+ return t`${ce}SELECT ${n}${f}${d} FROM ${h}${te}${ne}${re}${ae}${r}`;
1003
1003
  },
1004
1004
  orElse: () => {
1005
- let n = e.take === void 0 ? t`` : t` LIMIT ${y(e.take)}`, r = re ? t` OFFSET ${y(e.skip)}` : t``;
1006
- return t`${se}SELECT ${f}${d} FROM ${h}${te}${_}${ne}${ie}${n}${r}`;
1005
+ let n = e.take === void 0 ? t`` : t` LIMIT ${v(e.take)}`, r = ie ? t` OFFSET ${v(e.skip)}` : t``;
1006
+ return t`${ce}SELECT ${f}${d} FROM ${h}${te}${ne}${re}${ae}${n}${r}`;
1007
1007
  }
1008
1008
  });
1009
- }, Vr = (e, t, n) => {
1009
+ }, Ur = (e, t, n) => {
1010
1010
  if (e.eager === void 0) return null;
1011
- let r = Wr(e.table, e.eager, e.sourceTable);
1011
+ let r = Kr(e.table, e.eager, e.sourceTable);
1012
1012
  if (r === null) return null;
1013
- let i = Zr(n, e, r, Xr(t, n));
1013
+ let i = $r(n, e, r, Qr(t, n));
1014
1014
  return i === null ? null : {
1015
1015
  fragment: i,
1016
- decode: ei(r, n)
1016
+ decode: ni(r, n)
1017
1017
  };
1018
- }, Hr = (e) => e.relation.kind === "one" && e.fkSide === "target", Ur = (e) => ({
1018
+ }, Wr = (e) => e.relation.kind === "one" && e.fkSide === "target", Gr = (e) => ({
1019
1019
  ...e,
1020
1020
  branch: {
1021
1021
  ...e.branch,
1022
1022
  limit: 2
1023
1023
  }
1024
- }), Wr = (e, t, n) => {
1025
- let r = n ?? _(e), i = In(e);
1024
+ }), Kr = (e, t, n) => {
1025
+ let r = n ?? re(e), i = Bn(e);
1026
1026
  if (i === void 0) return null;
1027
1027
  let a = [];
1028
1028
  for (let [e, n] of Object.entries(t)) {
1029
1029
  let t = i[e];
1030
1030
  if (t === void 0) return null;
1031
- let o = Gr(e, t, r, n === !0 ? {} : n);
1031
+ let o = qr(e, t, r, n === !0 ? {} : n);
1032
1032
  if (o === null) return null;
1033
1033
  a.push(o);
1034
1034
  }
@@ -1036,30 +1036,30 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1036
1036
  table: r,
1037
1037
  children: a
1038
1038
  };
1039
- }, Gr = (e, t, n, r) => {
1039
+ }, qr = (e, t, n, r) => {
1040
1040
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1041
1041
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1042
1042
  else if (t.kind === "one") {
1043
- let r = t.sourceKey ?? Yr(n, i.tableName);
1043
+ let r = t.sourceKey ?? Zr(n, i.tableName);
1044
1044
  if (r !== void 0) o = r, s = "source";
1045
1045
  else try {
1046
- o = t.foreignKey ?? Dn(i, n.tableName, e), s = "target";
1046
+ o = t.foreignKey ?? jn(i, n.tableName, e), s = "target";
1047
1047
  } catch {
1048
1048
  return null;
1049
1049
  }
1050
1050
  } else try {
1051
- o = t.foreignKey ?? Dn(i, n.tableName, e), s = "target";
1051
+ o = t.foreignKey ?? jn(i, n.tableName, e), s = "target";
1052
1052
  } catch {
1053
1053
  return null;
1054
1054
  }
1055
1055
  let c = r.with === void 0 ? [] : (() => {
1056
- let e = In(i.tableName);
1056
+ let e = Bn(i.tableName);
1057
1057
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
1058
1058
  let t = [];
1059
1059
  for (let [n, a] of Object.entries(r.with)) {
1060
1060
  let r = e?.[n];
1061
1061
  if (r === void 0) return null;
1062
- let o = Gr(n, r, i, a === !0 ? {} : a);
1062
+ let o = qr(n, r, i, a === !0 ? {} : a);
1063
1063
  if (o === null) return null;
1064
1064
  t.push(o);
1065
1065
  }
@@ -1075,9 +1075,9 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1075
1075
  fkSide: s,
1076
1076
  branch: r,
1077
1077
  children: c,
1078
- junction: Kr(t, r)
1078
+ junction: Jr(t, r)
1079
1079
  };
1080
- }, Kr = (e, t) => {
1080
+ }, Jr = (e, t) => {
1081
1081
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1082
1082
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1083
1083
  return {
@@ -1089,35 +1089,35 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1089
1089
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1090
1090
  })
1091
1091
  };
1092
- }, qr = (e) => `__j_${e}`, Jr = "__j", Yr = (e, t) => {
1092
+ }, Yr = (e) => `__j_${e}`, Xr = "__j", Zr = (e, t) => {
1093
1093
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1094
- }, Xr = (e, t) => {
1094
+ }, Qr = (e, t) => {
1095
1095
  let n = 0;
1096
1096
  return {
1097
1097
  sql: e,
1098
1098
  dialect: t,
1099
1099
  nextAlias: () => `__a${n++}`
1100
1100
  };
1101
- }, Zr = (e, t, n, r) => {
1101
+ }, $r = (e, t, n, r) => {
1102
1102
  switch (e) {
1103
- case "postgres": return ri(t, n, r);
1103
+ case "postgres": return ai(t, n, r);
1104
1104
  case "sqlite":
1105
- case "turso": return di(t, n, r);
1105
+ case "turso": return pi(t, n, r);
1106
1106
  case "mysql":
1107
- case "mariadb": return xi(t, n, r);
1108
- case "mssql": return Oi(t, n, r);
1107
+ case "mariadb": return Ci(t, n, r);
1108
+ case "mssql": return Ai(t, n, r);
1109
1109
  }
1110
- }, Qr = (e, t) => t === "mssql" && !$r.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), $r = /(?:Z|[+-]\d{2}:?\d{2})$/, ei = (e, t) => {
1111
- let n = ti(e.table, e.children, t);
1110
+ }, ei = (e, t) => t === "mssql" && !ti.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ti = /(?:Z|[+-]\d{2}:?\d{2})$/, ni = (e, t) => {
1111
+ let n = ri(e.table, e.children, t);
1112
1112
  return (e) => e.map((e) => {
1113
1113
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1114
1114
  return n(r);
1115
1115
  });
1116
- }, ti = (e, t, n) => {
1116
+ }, ri = (e, t, n) => {
1117
1117
  let r = [];
1118
1118
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1119
1119
  let i = t.map((e) => {
1120
- let t = ti(e.target, e.children, n), r = e.relation.kind === "one", i = Hr(e), a = i ? ar({
1120
+ let t = ri(e.target, e.children, n), r = e.relation.kind === "one", i = Wr(e), a = i ? lr({
1121
1121
  relationName: e.relationName,
1122
1122
  sourceTableName: e.source.tableName,
1123
1123
  targetTableName: e.target.tableName,
@@ -1130,14 +1130,14 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1130
1130
  isSingle: r,
1131
1131
  fromOverFetch: i,
1132
1132
  cardinalityMessage: a,
1133
- junction: ni(e.junction, n)
1133
+ junction: ii(e.junction, n)
1134
1134
  };
1135
1135
  });
1136
1136
  return (e) => {
1137
1137
  let t = { ...e };
1138
1138
  for (let e of r) {
1139
1139
  let r = t[e];
1140
- typeof r == "string" && (t[e] = Qr(r, n));
1140
+ typeof r == "string" && (t[e] = ei(r, n));
1141
1141
  }
1142
1142
  for (let e of i) {
1143
1143
  let n = t[e.name];
@@ -1147,7 +1147,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1147
1147
  }
1148
1148
  if (e.fromOverFetch) {
1149
1149
  let r = n;
1150
- if (r.length > 1) throw new ir(e.cardinalityMessage);
1150
+ if (r.length > 1) throw new cr(e.cardinalityMessage);
1151
1151
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
1152
1152
  continue;
1153
1153
  }
@@ -1159,202 +1159,202 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1159
1159
  }
1160
1160
  return t;
1161
1161
  };
1162
- }, ni = (e, t) => {
1162
+ }, ii = (e, t) => {
1163
1163
  if (e === void 0) return;
1164
1164
  let n = new Set(e.dateColumns), r = e.requested;
1165
1165
  return (e) => {
1166
1166
  let i = e._junction ?? {}, a = {};
1167
1167
  for (let e of r) {
1168
1168
  let r = i[e];
1169
- a[e] = n.has(e) && typeof r == "string" ? Qr(r, t) : r;
1169
+ a[e] = n.has(e) && typeof r == "string" ? ei(r, t) : r;
1170
1170
  }
1171
1171
  return {
1172
1172
  ...e,
1173
1173
  _junction: a
1174
1174
  };
1175
1175
  };
1176
- }, ri = (e, t, n) => {
1177
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ii(i, t.children, n);
1178
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``}${w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`}`;
1179
- }, ii = (e, t, n, r) => {
1180
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${B(Jr, i)}::text)`;
1176
+ }, ai = (e, t, n) => {
1177
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = oi(i, t.children, n);
1178
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``}${C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`}`;
1179
+ }, oi = (e, t, n, r) => {
1180
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${B(Xr, i)}::text)`;
1181
1181
  if (t.length === 0 && r === void 0) return a;
1182
1182
  let o = [];
1183
- r !== void 0 && o.push(i`${B("_junction", i)}, ${z(e, Jr, i)}`);
1183
+ r !== void 0 && o.push(i`${B("_junction", i)}, ${z(e, Xr, i)}`);
1184
1184
  for (let r of t) {
1185
- let t = ai(r, e, n);
1185
+ let t = si(r, e, n);
1186
1186
  if (t === null) return null;
1187
1187
  o.push(i`${B(r.relationName, i)}, ${t}`);
1188
1188
  }
1189
1189
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1190
- }, ai = (e, t, n) => {
1190
+ }, si = (e, t, n) => {
1191
1191
  switch (e.relation.kind) {
1192
- case "one": return Hr(e) ? si(Ur(e), t, n) : oi(e, t, n);
1193
- case "many": return si(e, t, n);
1194
- case "manyToMany": return ci(e, t, n);
1192
+ case "one": return Wr(e) ? li(Gr(e), t, n) : ci(e, t, n);
1193
+ case "many": return li(e, t, n);
1194
+ case "manyToMany": return ui(e, t, n);
1195
1195
  }
1196
- }, oi = (e, t, n) => {
1197
- let r = n.sql, i = n.nextAlias(), a = ii(i, e.children, n);
1196
+ }, ci = (e, t, n) => {
1197
+ let r = n.sql, i = n.nextAlias(), a = oi(i, e.children, n);
1198
1198
  if (a === null) return null;
1199
1199
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, c = L(i, e.branch.orderBy, r);
1200
1200
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1201
- }, si = (e, t, n) => {
1202
- let r = n.sql, i = n.nextAlias(), a = ii(i, e.children, n);
1201
+ }, li = (e, t, n) => {
1202
+ let r = n.sql, i = n.nextAlias(), a = oi(i, e.children, n);
1203
1203
  if (a === null) return null;
1204
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, c = ui(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1204
+ let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, c = fi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1205
1205
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1206
- }, ci = (e, t, n) => {
1207
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ii(o, e.children, n, e.junction);
1206
+ }, ui = (e, t, n) => {
1207
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = oi(o, e.children, n, e.junction);
1208
1208
  if (c === null) return null;
1209
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, u = Ii(e, s, r), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${li(e.junction, s, r)} AS ${r(Jr)}`;
1209
+ let l = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, u = Ri(e, s, r), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${di(e.junction, s, r)} AS ${r(Xr)}`;
1210
1210
  return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1211
- }, li = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t, e, n)}`))})`, L = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${z(e, t.column, n)} DESC` : n`${z(e, t.column, n)} ASC`))}`, ui = (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`))}`, di = (e, t, n) => {
1212
- let r = n.sql, i = n.nextAlias(), a = fi(i, t.table, t.children, n);
1211
+ }, di = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t, e, n)}`))})`, L = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${z(e, t.column, n)} DESC` : n`${z(e, t.column, n)} ASC`))}`, fi = (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`))}`, pi = (e, t, n) => {
1212
+ let r = n.sql, i = n.nextAlias(), a = mi(i, t.table, t.children, n);
1213
1213
  if (a === null) return null;
1214
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1214
+ let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1215
1215
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1216
- }, fi = (e, t, n, r, i) => {
1216
+ }, mi = (e, t, n, r, i) => {
1217
1217
  let a = r.sql, o = [];
1218
1218
  for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1219
1219
  if (i !== void 0) {
1220
- let e = pi(i.projection, i.source, a);
1220
+ let e = hi(i.projection, i.source, a);
1221
1221
  o.push(a`${B("_junction", a)}, json_object(${e})`);
1222
1222
  }
1223
1223
  for (let t of n) {
1224
- let n = _i(t, e, r);
1224
+ let n = yi(t, e, r);
1225
1225
  if (n === null) return null;
1226
1226
  o.push(a`${B(t.relationName, a)}, ${n}`);
1227
1227
  }
1228
1228
  return a`json_object(${a.csv(o)})`;
1229
- }, pi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t.alias, t.physical(e), n)}`)), mi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${z(t, e, n)} AS ${n(qr(e))}`))}`, hi = (e) => ({
1229
+ }, hi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t.alias, t.physical(e), n)}`)), gi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${z(t, e, n)} AS ${n(Yr(e))}`))}`, _i = (e) => ({
1230
1230
  alias: e,
1231
- physical: qr
1232
- }), gi = (e) => ({
1231
+ physical: Yr
1232
+ }), vi = (e) => ({
1233
1233
  alias: e,
1234
1234
  physical: (e) => e
1235
- }), _i = (e, t, n) => {
1235
+ }), yi = (e, t, n) => {
1236
1236
  switch (e.relation.kind) {
1237
- case "one": return Hr(e) ? yi(Ur(e), t, n) : vi(e, t, n);
1238
- case "many": return yi(e, t, n);
1239
- case "manyToMany": return bi(e, t, n);
1237
+ case "one": return Wr(e) ? xi(Gr(e), t, n) : bi(e, t, n);
1238
+ case "many": return xi(e, t, n);
1239
+ case "manyToMany": return Si(e, t, n);
1240
1240
  }
1241
- }, vi = (e, t, n) => {
1242
- let r = n.sql, i = n.nextAlias(), a = fi(i, e.target, e.children, n);
1241
+ }, bi = (e, t, n) => {
1242
+ let r = n.sql, i = n.nextAlias(), a = mi(i, e.target, e.children, n);
1243
1243
  if (a === null) return null;
1244
1244
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1245
1245
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1246
- }, yi = (e, t, n) => {
1247
- let r = n.sql, i = n.nextAlias(), a = fi(i, e.target, e.children, n);
1246
+ }, xi = (e, t, n) => {
1247
+ let r = n.sql, i = n.nextAlias(), a = mi(i, e.target, e.children, n);
1248
1248
  if (a === null) return null;
1249
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = ui(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1249
+ let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = fi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1250
1250
  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('[]'))`;
1251
- }, bi = (e, t, n) => {
1252
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = fi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1251
+ }, Si = (e, t, n) => {
1252
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = mi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1253
1253
  projection: e.junction,
1254
- source: hi(o)
1254
+ source: _i(o)
1255
1255
  });
1256
1256
  if (c === null) return null;
1257
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Ii(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : mi(e.junction, s, r);
1257
+ let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Ri(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : gi(e.junction, s, r);
1258
1258
  return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1259
- }, xi = (e, t, n) => {
1259
+ }, Ci = (e, t, n) => {
1260
1260
  let r = n.sql, i = n.nextAlias(), a = R(i, t.table, t.children, n);
1261
1261
  if (a === null) return null;
1262
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1262
+ let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1263
1263
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1264
1264
  }, R = (e, t, n, r, i) => {
1265
1265
  let a = r.sql, o = [];
1266
1266
  for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1267
1267
  if (i !== void 0) {
1268
- let e = pi(i.projection, i.source, a);
1268
+ let e = hi(i.projection, i.source, a);
1269
1269
  o.push(a`${B("_junction", a)}, JSON_OBJECT(${e})`);
1270
1270
  }
1271
1271
  for (let t of n) {
1272
- let n = Si(t, e, r);
1272
+ let n = wi(t, e, r);
1273
1273
  if (n === null) return null;
1274
1274
  o.push(a`${B(t.relationName, a)}, ${n}`);
1275
1275
  }
1276
1276
  return a`JSON_OBJECT(${a.csv(o)})`;
1277
- }, Si = (e, t, n) => {
1277
+ }, wi = (e, t, n) => {
1278
1278
  switch (e.relation.kind) {
1279
1279
  case "one":
1280
- if (Hr(e)) {
1281
- let r = Ur(e);
1282
- return n.dialect === "mariadb" ? Ei(r, t, n) : wi(r, t, n);
1280
+ if (Wr(e)) {
1281
+ let r = Gr(e);
1282
+ return n.dialect === "mariadb" ? Oi(r, t, n) : Ei(r, t, n);
1283
1283
  }
1284
- return Ci(e, t, n);
1285
- case "many": return n.dialect === "mariadb" ? Ei(e, t, n) : wi(e, t, n);
1286
- case "manyToMany": return n.dialect === "mariadb" ? Di(e, t, n) : Ti(e, t, n);
1284
+ return Ti(e, t, n);
1285
+ case "many": return n.dialect === "mariadb" ? Oi(e, t, n) : Ei(e, t, n);
1286
+ case "manyToMany": return n.dialect === "mariadb" ? ki(e, t, n) : Di(e, t, n);
1287
1287
  }
1288
- }, Ci = (e, t, n) => {
1288
+ }, Ti = (e, t, n) => {
1289
1289
  let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1290
1290
  if (a === null) return null;
1291
1291
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1292
1292
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1293
- }, wi = (e, t, n) => {
1293
+ }, Ei = (e, t, n) => {
1294
1294
  let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1295
1295
  if (a === null) return null;
1296
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = ui(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1296
+ let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = fi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1297
1297
  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())`;
1298
- }, Ti = (e, t, n) => {
1298
+ }, Di = (e, t, n) => {
1299
1299
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = R(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1300
1300
  projection: e.junction,
1301
- source: hi(o)
1301
+ source: _i(o)
1302
1302
  });
1303
1303
  if (c === null) return null;
1304
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Ii(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : mi(e.junction, s, r);
1304
+ let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Ri(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : gi(e.junction, s, r);
1305
1305
  return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1306
- }, Ei = (e, t, n) => {
1306
+ }, Oi = (e, t, n) => {
1307
1307
  let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1308
1308
  if (a === null) return null;
1309
1309
  let o = r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1310
1310
  if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1311
1311
  let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)} AND ${z(i, "rn", r)} <= ${V(d + u, r)}` : u === void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)}` : r` AND ${z(i, "rn", r)} <= ${V(u, r)}`;
1312
1312
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${z(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1313
- }, Di = (e, t, n) => {
1313
+ }, ki = (e, t, n) => {
1314
1314
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1315
1315
  projection: e.junction,
1316
1316
  source: t
1317
- }, l = r`${z(s, i.sourceKey, r)} = ${z(t, "id", r)}`, u = r`${z(o, "id", r)} = ${z(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, f = Ii(e, s, r, !0), p = e.branch.orderBy ?? [];
1317
+ }, l = r`${z(s, i.sourceKey, r)} = ${z(t, "id", r)}`, u = r`${z(o, "id", r)} = ${z(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, f = Ri(e, s, r, !0), p = e.branch.orderBy ?? [];
1318
1318
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1319
- let t = R(o, e.target, e.children, n, c(gi(s)));
1319
+ let t = R(o, e.target, e.children, n, c(vi(s)));
1320
1320
  return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1321
1321
  }
1322
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r` ORDER BY ${z(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)} AND ${z(o, "rn", r)} <= ${V(g + h, r)}` : h === void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)}` : r` AND ${z(o, "rn", r)} <= ${V(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${H(U(e.branch.onJunction), s, r)}`, _ = R(o, e.target, e.children, n, c(hi(o)));
1323
- if (_ === null) return null;
1324
- let ne = e.junction === void 0 ? r`` : mi(e.junction, s, r);
1325
- return r`COALESCE((SELECT JSON_ARRAYAGG(${_} ORDER BY ${z(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${z(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${z(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${z(o, `__src_${i.sourceKey}`, r)} = ${z(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1326
- }, Oi = (e, t, n) => {
1327
- let r = n.sql, i = n.nextAlias(), a = ki(i, t.table, t.children, n);
1322
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r` ORDER BY ${z(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)} AND ${z(o, "rn", r)} <= ${V(g + h, r)}` : h === void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)}` : r` AND ${z(o, "rn", r)} <= ${V(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${H(U(e.branch.onJunction), s, r)}`, ne = R(o, e.target, e.children, n, c(_i(o)));
1323
+ if (ne === null) return null;
1324
+ let re = e.junction === void 0 ? r`` : gi(e.junction, s, r);
1325
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${ne} ORDER BY ${z(o, "rn", r)}) FROM (SELECT ${r(o)}.*${re}, ${z(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${z(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${z(o, `__src_${i.sourceKey}`, r)} = ${z(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1326
+ }, Ai = (e, t, n) => {
1327
+ let r = n.sql, i = n.nextAlias(), a = ji(i, t.table, t.children, n);
1328
1328
  if (a === null) return null;
1329
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1329
+ let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1330
1330
  if (e.skip !== void 0) {
1331
- let t = w(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1331
+ let t = C(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1332
1332
  l = e.take === void 0 ? r`${t} OFFSET ${V(e.skip, r)} ROWS` : r`${t} OFFSET ${V(e.skip, r)} ROWS FETCH NEXT ${V(e.take, r)} ROWS ONLY`;
1333
1333
  } else e.take !== void 0 && (c = r`TOP ${V(e.take, r)} `);
1334
1334
  let u = e.skip === void 0 ? s : r``;
1335
1335
  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}`;
1336
- }, ki = (e, t, n, r, i) => {
1336
+ }, ji = (e, t, n, r, i) => {
1337
1337
  let a = r.sql, o = [];
1338
1338
  for (let n of Object.keys(t.fields)) o.push(a`${z(e, n, a)} AS ${a(n)}`);
1339
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${z(i.source.alias, i.source.physical(e), a)} AS ${Ai(`_junction.${e}`, a)}`);
1339
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${z(i.source.alias, i.source.physical(e), a)} AS ${Mi(`_junction.${e}`, a)}`);
1340
1340
  for (let t of n) {
1341
- let n = ji(t, e, r);
1341
+ let n = Ni(t, e, r);
1342
1342
  if (n === null) return null;
1343
1343
  o.push(n);
1344
1344
  }
1345
1345
  return a.csv(o);
1346
- }, Ai = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), ji = (e, t, n) => {
1346
+ }, Mi = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Ni = (e, t, n) => {
1347
1347
  switch (e.relation.kind) {
1348
- case "one": return Hr(e) ? Pi(Ur(e), t, n) : Mi(e, t, n);
1349
- case "many": return Pi(e, t, n);
1350
- case "manyToMany": return Fi(e, t, n);
1348
+ case "one": return Wr(e) ? Ii(Gr(e), t, n) : Pi(e, t, n);
1349
+ case "many": return Ii(e, t, n);
1350
+ case "manyToMany": return Li(e, t, n);
1351
1351
  }
1352
- }, Mi = (e, t, n) => {
1353
- let r = n.sql, i = n.nextAlias(), a = ki(i, e.target, e.children, n);
1352
+ }, Pi = (e, t, n) => {
1353
+ let r = n.sql, i = n.nextAlias(), a = ji(i, e.target, e.children, n);
1354
1354
  if (a === null) return null;
1355
1355
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1356
1356
  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)}`;
1357
- }, Ni = (e, t, n) => {
1357
+ }, Fi = (e, t, n) => {
1358
1358
  if (e.offset !== void 0) {
1359
1359
  let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${V(e.offset, n)} ROWS` : n`${r} OFFSET ${V(e.offset, n)} ROWS FETCH NEXT ${V(e.limit, n)} ROWS ONLY`;
1360
1360
  return {
@@ -1368,29 +1368,29 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1368
1368
  pagination: n``,
1369
1369
  finalOrder: t
1370
1370
  };
1371
- }, Pi = (e, t, n) => {
1372
- let r = n.sql, i = n.nextAlias(), a = ki(i, e.target, e.children, n);
1371
+ }, Ii = (e, t, n) => {
1372
+ let r = n.sql, i = n.nextAlias(), a = ji(i, e.target, e.children, n);
1373
1373
  if (a === null) return null;
1374
- let o = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, s = L(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Ni(e.branch, s, r);
1374
+ let o = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, s = L(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Fi(e.branch, s, r);
1375
1375
  return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1376
- }, Fi = (e, t, n) => {
1377
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ki(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1376
+ }, Li = (e, t, n) => {
1377
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ji(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1378
1378
  projection: e.junction,
1379
- source: gi(s)
1379
+ source: vi(s)
1380
1380
  });
1381
1381
  if (c === null) return null;
1382
- let l = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, o, r)}`, u = Ii(e, s, r), d = L(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Ni(e.branch, d, r);
1382
+ let l = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, o, r)}`, u = Ri(e, s, r), d = L(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Fi(e.branch, d, r);
1383
1383
  return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1384
1384
  }, z = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, B = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), V = (e, t) => {
1385
1385
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1386
1386
  return t.unsafe(String(e));
1387
- }, H = (e, t, n) => I(Li(e, t), n), Ii = (e, t, n, r = !1) => {
1387
+ }, H = (e, t, n) => I(zi(e, t), n), Ri = (e, t, n, r = !1) => {
1388
1388
  let i = e.branch.onJunction;
1389
1389
  return i === void 0 ? n`` : n` AND ${H(r ? U(i) : i, t, n)}`;
1390
- }, Li = (e, t) => {
1391
- if ("not" in e) return { not: Li(e.not, t) };
1392
- if ("and" in e) return { and: e.and.map((e) => Li(e, t)) };
1393
- if ("or" in e) return { or: e.or.map((e) => Li(e, t)) };
1390
+ }, zi = (e, t) => {
1391
+ if ("not" in e) return { not: zi(e.not, t) };
1392
+ if ("and" in e) return { and: e.and.map((e) => zi(e, t)) };
1393
+ if ("or" in e) return { or: e.or.map((e) => zi(e, t)) };
1394
1394
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1395
1395
  let n = e;
1396
1396
  return {
@@ -1412,91 +1412,91 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1412
1412
  let t = e;
1413
1413
  return {
1414
1414
  ...t,
1415
- value: Ri(t.value)
1415
+ value: Bi(t.value)
1416
1416
  };
1417
- }, Ri = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Ri(e)) : e, zi = Symbol.for("@voltro/database/coreTablesRegistry"), Bi = globalThis, Vi = Bi[zi] ?? (Bi[zi] = {}), Hi = (e) => {
1418
- e.actors !== void 0 && (Vi.actors = e.actors), e.tenants !== void 0 && (Vi.tenants = e.tenants);
1419
- }, Ui = (e, t) => () => {
1417
+ }, Bi = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Bi(e)) : e, Vi = Symbol.for("@voltro/database/coreTablesRegistry"), Hi = globalThis, Ui = Hi[Vi] ?? (Hi[Vi] = {}), Wi = (e) => {
1418
+ e.actors !== void 0 && (Ui.actors = e.actors), e.tenants !== void 0 && (Ui.tenants = e.tenants);
1419
+ }, Gi = (e, t) => () => {
1420
1420
  let n = e();
1421
1421
  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`);
1422
1422
  return n();
1423
- }, Wi = () => Ui(() => Vi.actors, "actors"), Gi = () => Ui(() => Vi.tenants, "tenants"), Ki = T("actors", {
1424
- id: b(),
1425
- kind: C().oneOf([
1423
+ }, Ki = () => Gi(() => Ui.actors, "actors"), qi = () => Gi(() => Ui.tenants, "tenants"), Ji = w("actors", {
1424
+ id: a(),
1425
+ kind: S().oneOf([
1426
1426
  "user",
1427
1427
  "serviceAccount",
1428
1428
  "apiKey",
1429
1429
  "system"
1430
1430
  ]),
1431
- displayName: C().nullable(),
1432
- createdAt: S().default("now")
1433
- }), qi = (e, t) => ({
1431
+ displayName: S().nullable(),
1432
+ createdAt: y().default("now")
1433
+ }), Yi = (e, t) => ({
1434
1434
  column: e,
1435
1435
  op: "eq",
1436
1436
  value: t
1437
- }), Ji = (e, t) => ({
1437
+ }), Xi = (e, t) => ({
1438
1438
  column: e,
1439
1439
  op: "neq",
1440
1440
  value: t
1441
- }), Yi = (e, t) => ({
1441
+ }), Zi = (e, t) => ({
1442
1442
  column: e,
1443
1443
  op: "gt",
1444
1444
  value: t
1445
- }), Xi = (e, t) => ({
1445
+ }), Qi = (e, t) => ({
1446
1446
  column: e,
1447
1447
  op: "gte",
1448
1448
  value: t
1449
- }), Zi = (e, t) => ({
1449
+ }), $i = (e, t) => ({
1450
1450
  column: e,
1451
1451
  op: "lt",
1452
1452
  value: t
1453
- }), Qi = (e, t) => ({
1453
+ }), ea = (e, t) => ({
1454
1454
  column: e,
1455
1455
  op: "lte",
1456
1456
  value: t
1457
- }), $i = (e, t) => ({
1457
+ }), ta = (e, t) => ({
1458
1458
  column: e,
1459
1459
  op: "in",
1460
1460
  value: t
1461
- }), ea = (e, t) => ({
1461
+ }), na = (e, t) => ({
1462
1462
  column: e,
1463
1463
  op: "notIn",
1464
1464
  value: t
1465
- }), ta = (e, t) => ({
1465
+ }), ra = (e, t) => ({
1466
1466
  column: e,
1467
1467
  op: "contains",
1468
1468
  value: t
1469
- }), na = (e, t) => ({
1469
+ }), ia = (e, t) => ({
1470
1470
  column: e,
1471
1471
  op: "startsWith",
1472
1472
  value: t
1473
- }), ra = (e, t) => ({
1473
+ }), aa = (e, t) => ({
1474
1474
  column: e,
1475
1475
  op: "arrayContains",
1476
1476
  value: t
1477
- }), ia = (e, t) => ({
1477
+ }), oa = (e, t) => ({
1478
1478
  column: e,
1479
1479
  op: "arrayOverlaps",
1480
1480
  value: t
1481
- }), aa = (e, t) => ({
1481
+ }), sa = (e, t) => ({
1482
1482
  column: e,
1483
1483
  op: "arrayHas",
1484
1484
  value: t
1485
- }), oa = {
1485
+ }), ca = {
1486
1486
  column: "id",
1487
1487
  op: "in",
1488
1488
  value: []
1489
- }, sa = (e) => ({
1489
+ }, la = (e) => ({
1490
1490
  column: e,
1491
1491
  op: "isNull"
1492
- }), ca = (e) => ({
1492
+ }), ua = (e) => ({
1493
1493
  column: e,
1494
1494
  op: "isNotNull"
1495
- }), la = (e, t) => ({
1495
+ }), da = (e, t) => ({
1496
1496
  column: e,
1497
1497
  op: "spatial",
1498
1498
  value: t
1499
- }), ua = (...e) => ({ and: e }), da = (...e) => ({ or: e }), fa = (e) => ({ not: e }), pa = (e, ...t) => {
1499
+ }), fa = (...e) => ({ and: e }), pa = (...e) => ({ or: e }), ma = (e) => ({ not: e }), ha = (e, ...t) => {
1500
1500
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1501
1501
  let n = (n, r) => ({
1502
1502
  column: e,
@@ -1518,33 +1518,33 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1518
1518
  isNull: () => n("isNull"),
1519
1519
  isNotNull: () => n("isNotNull")
1520
1520
  };
1521
- }, ma = (e) => "descriptor" in e ? e.descriptor : e, ha = (e, t) => ({
1521
+ }, ga = (e) => "descriptor" in e ? e.descriptor : e, _a = (e, t) => ({
1522
1522
  column: e,
1523
1523
  op: "subquery-in",
1524
- subquery: ma(t)
1525
- }), ga = (e, t) => ({
1524
+ subquery: ga(t)
1525
+ }), va = (e, t) => ({
1526
1526
  column: e,
1527
1527
  op: "subquery-not-in",
1528
- subquery: ma(t)
1529
- }), _a = (e) => ({
1528
+ subquery: ga(t)
1529
+ }), ya = (e) => ({
1530
1530
  op: "exists",
1531
- subquery: ma(e)
1532
- }), va = (e) => ({
1531
+ subquery: ga(e)
1532
+ }), ba = (e) => ({
1533
1533
  op: "not-exists",
1534
- subquery: ma(e)
1535
- }), ya = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), ba = (e, t) => {
1534
+ subquery: ga(e)
1535
+ }), xa = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Sa = (e, t) => {
1536
1536
  if (e == null || t == null) return null;
1537
1537
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1538
1538
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1539
- }, xa = (e, t, n = null) => {
1539
+ }, Ca = (e, t, n = null) => {
1540
1540
  if (!t) return !1;
1541
- if ("not" in e) return !xa(e.not, t, n);
1541
+ if ("not" in e) return !Ca(e.not, t, n);
1542
1542
  if ("and" in e) {
1543
- for (let r of e.and) if (!xa(r, t, n)) return !1;
1543
+ for (let r of e.and) if (!Ca(r, t, n)) return !1;
1544
1544
  return !0;
1545
1545
  }
1546
1546
  if ("or" in e) {
1547
- for (let r of e.or) if (xa(r, t, n)) return !0;
1547
+ for (let r of e.or) if (Ca(r, t, n)) return !0;
1548
1548
  return !1;
1549
1549
  }
1550
1550
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1561,14 +1561,14 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1561
1561
  }
1562
1562
  let r = e, i = t[r.column];
1563
1563
  switch (r.op) {
1564
- case "eq": return ya(i, r.value);
1565
- case "neq": return !ya(i, r.value);
1566
- case "gt": return (ba(i, r.value) ?? -1) > 0;
1567
- case "gte": return (ba(i, r.value) ?? -1) >= 0;
1568
- case "lt": return (ba(i, r.value) ?? 1) < 0;
1569
- case "lte": return (ba(i, r.value) ?? 1) <= 0;
1570
- case "in": return Array.isArray(r.value) && r.value.some((e) => ya(i, e));
1571
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => ya(i, e));
1564
+ case "eq": return xa(i, r.value);
1565
+ case "neq": return !xa(i, r.value);
1566
+ case "gt": return (Sa(i, r.value) ?? -1) > 0;
1567
+ case "gte": return (Sa(i, r.value) ?? -1) >= 0;
1568
+ case "lt": return (Sa(i, r.value) ?? 1) < 0;
1569
+ case "lte": return (Sa(i, r.value) ?? 1) <= 0;
1570
+ case "in": return Array.isArray(r.value) && r.value.some((e) => xa(i, e));
1571
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => xa(i, e));
1572
1572
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1573
1573
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1574
1574
  case "arrayContains": {
@@ -1584,17 +1584,17 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1584
1584
  case "isNotNull": return i != null;
1585
1585
  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.");
1586
1586
  }
1587
- }, Sa = function* (e) {
1587
+ }, wa = function* (e) {
1588
1588
  if ("not" in e) {
1589
- yield* Sa(e.not);
1589
+ yield* wa(e.not);
1590
1590
  return;
1591
1591
  }
1592
1592
  if ("and" in e) {
1593
- for (let t of e.and) yield* Sa(t);
1593
+ for (let t of e.and) yield* wa(t);
1594
1594
  return;
1595
1595
  }
1596
1596
  if ("or" in e) {
1597
- for (let t of e.or) yield* Sa(t);
1597
+ for (let t of e.or) yield* wa(t);
1598
1598
  return;
1599
1599
  }
1600
1600
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1604,46 +1604,46 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1604
1604
  kind: "exists",
1605
1605
  descriptor: e.subquery
1606
1606
  });
1607
- }, Ca = function* (e, t = !0) {
1607
+ }, Ta = function* (e, t = !0) {
1608
1608
  if ("not" in e) {
1609
- yield* Ca(e.not, !1);
1609
+ yield* Ta(e.not, !1);
1610
1610
  return;
1611
1611
  }
1612
1612
  if ("and" in e) {
1613
- for (let n of e.and) yield* Ca(n, t);
1613
+ for (let n of e.and) yield* Ta(n, t);
1614
1614
  return;
1615
1615
  }
1616
1616
  if ("or" in e) {
1617
- for (let t of e.or) yield* Ca(t, !1);
1617
+ for (let t of e.or) yield* Ta(t, !1);
1618
1618
  return;
1619
1619
  }
1620
1620
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1621
1621
  ...e,
1622
1622
  conjunctive: t
1623
1623
  });
1624
- }, wa = (e, t) => ({
1624
+ }, Ea = (e, t) => ({
1625
1625
  ...t,
1626
1626
  ...e,
1627
1627
  origin: e.origin ?? "injected"
1628
- }), Ta = (e, t, n = {}) => ({
1628
+ }), Da = (e, t, n = {}) => ({
1629
1629
  table: e,
1630
1630
  op: "insert",
1631
1631
  old: null,
1632
1632
  new: t,
1633
1633
  ...n
1634
- }), Ea = (e, t, n, r = {}) => ({
1634
+ }), Oa = (e, t, n, r = {}) => ({
1635
1635
  table: e,
1636
1636
  op: "update",
1637
1637
  old: t,
1638
1638
  new: n,
1639
1639
  ...r
1640
- }), Da = (e, t, n = {}) => ({
1640
+ }), ka = (e, t, n = {}) => ({
1641
1641
  table: e,
1642
1642
  op: "delete",
1643
1643
  old: t,
1644
1644
  new: null,
1645
1645
  ...n
1646
- }), Oa = (e, t, n = {}) => {
1646
+ }), Aa = (e, t, n = {}) => {
1647
1647
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1648
1648
  return {
1649
1649
  table: e,
@@ -1658,26 +1658,26 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1658
1658
  },
1659
1659
  ...a
1660
1660
  };
1661
- }, ka = new Mt(), Aa = (e, t) => ka.run(e, t), ja = () => ka.getStore(), Ma = (e) => {
1662
- let t = e ?? ka.getStore();
1661
+ }, ja = new It(), Ma = (e, t) => ja.run(e, t), Na = () => ja.getStore(), Pa = (e) => {
1662
+ let t = e ?? ja.getStore();
1663
1663
  return t === void 0 ? {} : {
1664
1664
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1665
1665
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1666
1666
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1667
1667
  ...t.via === void 0 ? {} : { via: t.via }
1668
1668
  };
1669
- }, Na = (e) => {
1670
- let t = ka.getStore();
1671
- return t === void 0 ? e(void 0) : ka.run(t, () => e(t));
1672
- }, Pa = 3e4, Fa = 1e4, W = /* @__PURE__ */ new Map(), G = 0, Ia = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, La = (e) => {
1669
+ }, Fa = (e) => {
1670
+ let t = ja.getStore();
1671
+ return t === void 0 ? e(void 0) : ja.run(t, () => e(t));
1672
+ }, Ia = 3e4, La = 1e4, W = /* @__PURE__ */ new Map(), G = 0, Ra = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, za = (e) => {
1673
1673
  for (let [t, n] of W) {
1674
- let r = n.filter((t) => e - t.at < Pa);
1674
+ let r = n.filter((t) => e - t.at < Ia);
1675
1675
  G -= n.length - r.length, r.length === 0 ? W.delete(t) : r.length !== n.length && W.set(t, r);
1676
1676
  }
1677
- }, Ra = (e, t) => {
1677
+ }, Ba = (e, t) => {
1678
1678
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1679
1679
  let n = Date.now();
1680
- if (G >= Fa && La(n), G >= Fa) return;
1680
+ if (G >= La && za(n), G >= La) return;
1681
1681
  let r = W.get(e);
1682
1682
  r === void 0 ? W.set(e, [{
1683
1683
  attribution: t,
@@ -1686,38 +1686,38 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1686
1686
  attribution: t,
1687
1687
  at: n
1688
1688
  }), G += 1;
1689
- }, za = (e) => {
1689
+ }, Va = (e) => {
1690
1690
  let t = W.get(e);
1691
1691
  if (t === void 0 || t.length === 0) return;
1692
1692
  let n = t.shift();
1693
- if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= Pa)) return n.attribution;
1694
- }, Ba = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), Va = /* @__PURE__ */ new Map(), Ha = /* @__PURE__ */ new Map(), Ua = 250, Wa = (e) => {
1695
- let t = Va.get(e);
1693
+ if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= Ia)) return n.attribution;
1694
+ }, Ha = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), Ua = /* @__PURE__ */ new Map(), Wa = /* @__PURE__ */ new Map(), Ga = 250, Ka = (e) => {
1695
+ let t = Ua.get(e);
1696
1696
  if (t === void 0) return;
1697
- Va.delete(e);
1698
- let n = Ha.get(e);
1699
- n !== void 0 && (clearTimeout(n), Ha.delete(e));
1697
+ Ua.delete(e);
1698
+ let n = Wa.get(e);
1699
+ n !== void 0 && (clearTimeout(n), Wa.delete(e));
1700
1700
  for (let e of t) e();
1701
- }, Ga = (e) => {
1701
+ }, qa = (e) => {
1702
1702
  K.set(e, (K.get(e) ?? 0) + 1);
1703
- }, Ka = (e) => {
1703
+ }, Ja = (e) => {
1704
1704
  let t = (K.get(e) ?? 0) - 1;
1705
1705
  if (t > 0) {
1706
1706
  K.set(e, t);
1707
1707
  return;
1708
1708
  }
1709
- K.delete(e), Wa(e);
1710
- }, qa = (e, t, n, r) => {
1711
- let i = n == null ? void 0 : Ia(e, t, n), a = () => r(i === void 0 ? void 0 : za(i));
1709
+ K.delete(e), Ka(e);
1710
+ }, Ya = (e, t, n, r) => {
1711
+ let i = n == null ? void 0 : Ra(e, t, n), a = () => r(i === void 0 ? void 0 : Va(i));
1712
1712
  if (i === void 0) {
1713
1713
  a();
1714
1714
  return;
1715
1715
  }
1716
- if (Ba(i)) {
1716
+ if (Ha(i)) {
1717
1717
  a();
1718
1718
  return;
1719
1719
  }
1720
- let o = Va.get(e);
1720
+ let o = Ua.get(e);
1721
1721
  if (o === void 0 && (K.get(e) ?? 0) === 0) {
1722
1722
  a();
1723
1723
  return;
@@ -1726,91 +1726,91 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1726
1726
  o.push(a);
1727
1727
  return;
1728
1728
  }
1729
- Va.set(e, [a]);
1730
- let s = setTimeout(() => Wa(e), Ua);
1731
- typeof s == "object" && typeof s.unref == "function" && s.unref(), Ha.set(e, s);
1732
- }, Ja = () => {
1729
+ Ua.set(e, [a]);
1730
+ let s = setTimeout(() => Ka(e), Ga);
1731
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Wa.set(e, s);
1732
+ }, Xa = () => {
1733
1733
  W.clear(), G = 0, K.clear();
1734
- for (let e of Ha.values()) clearTimeout(e);
1735
- Ha.clear(), Va.clear();
1736
- }, Ya = () => G, Xa = 64, Za = "\0", Qa = 32, $a = (e, ...t) => `${e}_${Nt("sha256").update(t.map(String).join(Za)).digest("hex").slice(0, Qa)}`, eo = (e) => e.length + 1 + Qa, q = /* @__PURE__ */ new Map(), to = (e, t) => {
1734
+ for (let e of Wa.values()) clearTimeout(e);
1735
+ Wa.clear(), Ua.clear();
1736
+ }, Za = () => G, Qa = 64, $a = "\0", eo = 32, to = (e, ...t) => `${e}_${Lt("sha256").update(t.map(String).join($a)).digest("hex").slice(0, eo)}`, no = (e) => e.length + 1 + eo, q = /* @__PURE__ */ new Map(), ro = (e, t) => {
1737
1737
  q.set(e, {
1738
1738
  recorder: t.recorder,
1739
1739
  tables: new Set(t.tables),
1740
1740
  ownTables: new Set(t.ownTables)
1741
1741
  });
1742
- }, no = (e) => {
1742
+ }, io = (e) => {
1743
1743
  q.delete(e);
1744
- }, ro = () => q.clear(), io = new Mt(), ao = (e) => io.run({ n: 1 }, e), oo = (e) => O.suspend(() => {
1745
- let t = io.getStore();
1746
- if (t !== void 0) return t.n += 1, O.ensuring(e, O.sync(() => {
1744
+ }, ao = () => q.clear(), oo = new It(), so = (e) => oo.run({ n: 1 }, e), co = (e) => E.suspend(() => {
1745
+ let t = oo.getStore();
1746
+ if (t !== void 0) return t.n += 1, E.ensuring(e, E.sync(() => {
1747
1747
  --t.n;
1748
1748
  }));
1749
1749
  let n = { n: 1 };
1750
- return io.enterWith(n), O.ensuring(e, O.sync(() => {
1750
+ return oo.enterWith(n), E.ensuring(e, E.sync(() => {
1751
1751
  --n.n;
1752
1752
  }));
1753
- }), so = () => (io.getStore()?.n ?? 0) > 0, co = (e) => {
1754
- if (q.size === 0 || (io.getStore()?.n ?? 0) > 0) return !1;
1753
+ }), lo = () => (oo.getStore()?.n ?? 0) > 0, uo = (e) => {
1754
+ if (q.size === 0 || (oo.getStore()?.n ?? 0) > 0) return !1;
1755
1755
  for (let t of q.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1756
1756
  return !1;
1757
- }, lo = async (e, t) => {
1757
+ }, fo = async (e, t) => {
1758
1758
  if (q.size !== 0) {
1759
1759
  for (let [n, r] of q.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1760
1760
  await r.recorder(e, t);
1761
1761
  } catch (e) {
1762
- let r = dn(e);
1762
+ let r = hn(e);
1763
1763
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1764
1764
  }
1765
1765
  }
1766
- }, uo = Ot.exponential({
1766
+ }, po = Mt.exponential({
1767
1767
  start: 5e-4,
1768
1768
  factor: 2,
1769
1769
  count: 16
1770
- }), fo = k.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), po = k.histogram("voltro_db_query_duration_seconds", uo, "Database operation duration in seconds, by dialect and operation kind."), mo = k.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), ho = k.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), go = k.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), J = [], _o = /* @__PURE__ */ new Map(), vo = /* @__PURE__ */ new Map(), yo = /* @__PURE__ */ new Map(), bo = (e, t) => {
1771
- let n = `${e}\u0000${t}`, r = _o.get(n);
1770
+ }), mo = D.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), ho = D.histogram("voltro_db_query_duration_seconds", po, "Database operation duration in seconds, by dialect and operation kind."), go = D.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), _o = D.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), vo = D.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), yo = [], bo = /* @__PURE__ */ new Map(), xo = /* @__PURE__ */ new Map(), So = /* @__PURE__ */ new Map(), Co = (e, t) => {
1771
+ let n = `${e}\u0000${t}`, r = bo.get(n);
1772
1772
  if (r !== void 0) return r;
1773
- let i = (n) => k.tagged(k.tagged(n, "dialect", e), "op", t), a = {
1774
- count: i(fo),
1775
- duration: i(po),
1776
- errors: i(mo)
1773
+ let i = (n) => D.tagged(D.tagged(n, "dialect", e), "op", t), a = {
1774
+ count: i(mo),
1775
+ duration: i(ho),
1776
+ errors: i(go)
1777
1777
  };
1778
- return _o.set(n, a), a;
1779
- }, xo = () => {
1780
- _o.clear(), vo.clear(), yo.clear();
1781
- }, So = () => _o.size + vo.size + yo.size, Co = /* @__PURE__ */ new Map(), wo = (e, t) => {
1782
- let n = Math.max(0, (Co.get(e) ?? 0) + t);
1783
- n === 0 ? Co.delete(e) : Co.set(e, n);
1784
- let r = vo.get(e);
1785
- r === void 0 && (r = k.tagged(ho, "dialect", e), vo.set(e, r)), r.unsafeUpdate(n, J);
1786
- }, To = (e) => Co.get(e) ?? 0, Eo = (e) => {
1787
- let t = bo(String(e.dialect), e.op);
1788
- t.count.unsafeUpdate(1, J), t.duration.unsafeUpdate(e.durationMs / 1e3, J), e.status === "error" && t.errors.unsafeUpdate(1, J);
1789
- }, Do = async (e, t, n) => {
1778
+ return bo.set(n, a), a;
1779
+ }, wo = () => {
1780
+ bo.clear(), xo.clear(), So.clear();
1781
+ }, To = () => bo.size + xo.size + So.size, Eo = /* @__PURE__ */ new Map(), Do = (e, t) => {
1782
+ let n = Math.max(0, (Eo.get(e) ?? 0) + t);
1783
+ n === 0 ? Eo.delete(e) : Eo.set(e, n);
1784
+ let r = xo.get(e);
1785
+ r === void 0 && (r = D.tagged(_o, "dialect", e), xo.set(e, r)), r.unsafeUpdate(n, yo);
1786
+ }, Oo = (e) => Eo.get(e) ?? 0, ko = (e) => {
1787
+ let t = Co(String(e.dialect), e.op);
1788
+ t.count.unsafeUpdate(1, yo), t.duration.unsafeUpdate(e.durationMs / 1e3, yo), e.status === "error" && t.errors.unsafeUpdate(1, yo);
1789
+ }, Ao = async (e, t, n) => {
1790
1790
  let r = performance.now(), i = String(e);
1791
- wo(i, 1);
1791
+ Do(i, 1);
1792
1792
  let a = "ok";
1793
1793
  try {
1794
1794
  return await n();
1795
1795
  } catch (e) {
1796
1796
  throw a = "error", e;
1797
1797
  } finally {
1798
- wo(i, -1), Eo({
1798
+ Do(i, -1), ko({
1799
1799
  dialect: e,
1800
1800
  op: t,
1801
1801
  durationMs: performance.now() - r,
1802
1802
  status: a
1803
1803
  });
1804
1804
  }
1805
- }, Oo = 3e5, ko = (e) => {
1805
+ }, jo = 3e5, Mo = (e) => {
1806
1806
  if (e == null || e === "") return;
1807
1807
  let t = Number(e);
1808
1808
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1809
- }, Ao = (e, t = process.env) => ko(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? ko(e) ?? 3e5, jo = (e, t = {}) => {
1810
- let n = Ao(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1809
+ }, No = (e, t = process.env) => Mo(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Mo(e) ?? 3e5, Po = (e, t = {}) => {
1810
+ let n = No(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1811
1811
  return (t) => {
1812
- let a = `${t.dialect} ${t.reason}`, o = yo.get(a);
1813
- o === void 0 && (o = k.tagged(k.tagged(go, "dialect", String(t.dialect)), "reason", t.reason), yo.set(a, o)), o.unsafeUpdate(1, J);
1812
+ let a = `${t.dialect} ${t.reason}`, o = So.get(a);
1813
+ o === void 0 && (o = D.tagged(D.tagged(vo, "dialect", String(t.dialect)), "reason", t.reason), So.set(a, o)), o.unsafeUpdate(1, yo);
1814
1814
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1815
1815
  table: t.table,
1816
1816
  dialect: String(t.dialect),
@@ -1824,24 +1824,24 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1824
1824
  }
1825
1825
  i.set(s, r()), e.warn(t.reason === "execute-failed" ? "eager-load JSON-agg statement FAILED and was re-run on the multi-query walker — this query pays both paths on every call. Counted as voltro_db_eager_fallback_total{reason=\"execute-failed\"}." : "eager-load could not be compiled to a single JSON-agg roundtrip and is running on the multi-query walker — one round trip per relation level, on every call. Counted as voltro_db_eager_fallback_total{reason=\"not-compilable\"}.", u);
1826
1826
  };
1827
- }, Mo = (e) => {
1828
- if (Dt.isSuccess(e)) return e.value;
1829
- throw wt.squash(e.cause);
1830
- }, No = "10 millis", Po = 3, Fo = async (e) => {
1831
- let t = 0, n = O.suspend(() => {
1827
+ }, Fo = (e) => {
1828
+ if (jt.isSuccess(e)) return e.value;
1829
+ throw Ot.squash(e.cause);
1830
+ }, Io = "10 millis", Lo = 3, Ro = async (e) => {
1831
+ let t = 0, n = E.suspend(() => {
1832
1832
  let n = ++t;
1833
- return e.withTransaction(O.flatMap(O.serviceOption(Pt), (t) => {
1834
- if (A.isNone(t)) return O.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1835
- let r = t.value, i = O.tryPromise({
1833
+ return e.withTransaction(E.flatMap(E.serviceOption(Rt), (t) => {
1834
+ if (O.isNone(t)) return E.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1835
+ let r = t.value, i = E.tryPromise({
1836
1836
  try: () => e.body(r, n),
1837
1837
  catch: (e) => e
1838
1838
  });
1839
- return e.prepare === void 0 ? i : O.flatMap(e.prepare(r), () => i);
1840
- })).pipe(O.catchAllDefect((t) => e.isRetryable(t) ? O.fail(t) : O.die(t)));
1841
- }), r = At.exponential(No).pipe(At.compose(At.recurs(Po)), At.whileInput(e.isRetryable)), i = n.pipe(O.retry(r), O.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1842
- return Do(e.dialect, "transaction", async () => Mo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1843
- }, Io = async (e) => {
1844
- let t = ja(), n = t === void 0 ? (e) => e() : (e) => Aa(t, e), r = await Fo({
1839
+ return e.prepare === void 0 ? i : E.flatMap(e.prepare(r), () => i);
1840
+ })).pipe(E.catchAllDefect((t) => e.isRetryable(t) ? E.fail(t) : E.die(t)));
1841
+ }), r = Pt.exponential(Io).pipe(Pt.compose(Pt.recurs(Lo)), Pt.whileInput(e.isRetryable)), i = n.pipe(E.retry(r), E.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1842
+ return Ao(e.dialect, "transaction", async () => Fo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1843
+ }, zo = async (e) => {
1844
+ let t = Na(), n = t === void 0 ? (e) => e() : (e) => Ma(t, e), r = await Ro({
1845
1845
  ...e,
1846
1846
  body: (r) => {
1847
1847
  let i = e.makeView(r, t);
@@ -1852,14 +1852,14 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1852
1852
  }
1853
1853
  });
1854
1854
  return r.view.commitEvents(), r.result;
1855
- }, Lo = class extends j.TaggedError()("VersionConflict", {
1856
- table: j.String,
1857
- id: j.String,
1858
- expected: j.Number,
1859
- actual: j.NullOr(j.Number)
1860
- }) {}, Ro = (e) => {
1855
+ }, Bo = class extends k.TaggedError()("VersionConflict", {
1856
+ table: k.String,
1857
+ id: k.String,
1858
+ expected: k.Number,
1859
+ actual: k.NullOr(k.Number)
1860
+ }) {}, Vo = (e) => {
1861
1861
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1862
- }, zo = (e) => {
1862
+ }, Ho = (e) => {
1863
1863
  let { versionColumn: t, patch: n } = e;
1864
1864
  if (t === void 0) return {
1865
1865
  nextVersion: void 0,
@@ -1872,28 +1872,28 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1872
1872
  expected: i,
1873
1873
  patch: a
1874
1874
  };
1875
- }, Bo = (e) => {
1876
- if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Lo({
1875
+ }, Uo = (e) => {
1876
+ if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Bo({
1877
1877
  table: e.table,
1878
1878
  id: e.id,
1879
1879
  expected: e.expected,
1880
1880
  actual: e.current
1881
1881
  });
1882
- }, Vo = 1, Ho = "voltro/expires", Uo = () => Ke({
1883
- id: Ho,
1884
- fields: { expiresAt: S().nullable() },
1882
+ }, Wo = 1, Go = "voltro/expires", Ko = () => Ye({
1883
+ id: Go,
1884
+ fields: { expiresAt: y().nullable() },
1885
1885
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1886
- }), Wo = "voltro/localFirst", Go = () => Ke({
1887
- id: Wo,
1886
+ }), qo = "voltro/localFirst", Jo = () => Ye({
1887
+ id: qo,
1888
1888
  fields: {}
1889
- }), Ko = (e) => e.appliedMixins.some((e) => e.id === Wo), qo = (e) => {
1889
+ }), Yo = (e) => e.appliedMixins.some((e) => e.id === qo), Xo = (e) => {
1890
1890
  let t = [];
1891
- for (let n of Object.values(e)) Ko(n) && t.push(n.tableName);
1891
+ for (let n of Object.values(e)) Yo(n) && t.push(n.tableName);
1892
1892
  return t;
1893
- }, Jo = class extends Et.TaggedError("TableStreamError") {}, Yo = 1e3, Xo = (e, t, n, r) => {
1894
- let i = A.match(r, {
1893
+ }, Zo = class extends At.TaggedError("TableStreamError") {}, Qo = 1e3, $o = (e, t, n, r) => {
1894
+ let i = O.match(r, {
1895
1895
  onNone: () => e.where,
1896
- onSome: (n) => e.where ? ua(e.where, Yi(t, n)) : Yi(t, n)
1896
+ onSome: (n) => e.where ? fa(e.where, Zi(t, n)) : Zi(t, n)
1897
1897
  });
1898
1898
  return {
1899
1899
  table: e.table,
@@ -1908,19 +1908,19 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1908
1908
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1909
1909
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1910
1910
  };
1911
- }, Zo = (e, t) => {
1912
- let n = t.pk ?? "id", r = t.chunkSize ?? Yo;
1913
- return jt.paginateChunkEffect(A.none(), (i) => {
1914
- let a = O.tryPromise({
1915
- try: () => e.query(Xo(t, n, r, i)),
1916
- catch: (e) => new Jo({
1911
+ }, es = (e, t) => {
1912
+ let n = t.pk ?? "id", r = t.chunkSize ?? Qo;
1913
+ return Ft.paginateChunkEffect(O.none(), (i) => {
1914
+ let a = E.tryPromise({
1915
+ try: () => e.query($o(t, n, r, i)),
1916
+ catch: (e) => new Zo({
1917
1917
  table: t.table,
1918
1918
  cause: e
1919
1919
  })
1920
1920
  });
1921
- return (t.retry ? a.pipe(O.retry(t.retry)) : a).pipe(O.map((e) => [Tt.fromIterable(e), e.length === r && e.length > 0 ? A.some(A.some(e[e.length - 1][n])) : A.none()]));
1921
+ return (t.retry ? a.pipe(E.retry(t.retry)) : a).pipe(E.map((e) => [kt.fromIterable(e), e.length === r && e.length > 0 ? O.some(O.some(e[e.length - 1][n])) : O.none()]));
1922
1922
  });
1923
- }, Qo = (e) => {
1923
+ }, ts = (e) => {
1924
1924
  let t = e.alpha ?? .5;
1925
1925
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1926
1926
  return (n) => {
@@ -1934,7 +1934,7 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1934
1934
  queryText: e.vector.query,
1935
1935
  distance: e.vector.distance ?? "cosine",
1936
1936
  alpha: t
1937
- }, i = ee(n.table, e.fts.indexName, n.fullTextIndexes);
1937
+ }, i = te(n.table, e.fts.indexName, n.fullTextIndexes);
1938
1938
  return {
1939
1939
  ...n,
1940
1940
  annClause: r,
@@ -1947,19 +1947,19 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1947
1947
  }
1948
1948
  };
1949
1949
  };
1950
- }, $o = async (e, t) => {
1950
+ }, ns = async (e, t) => {
1951
1951
  let n = e.as ?? "embedding", r = t.row[e.from];
1952
1952
  if (typeof r != "string" || r.length === 0) return {};
1953
1953
  let i = await t.embed(r);
1954
1954
  return { [n]: i };
1955
- }, es = (e) => {
1955
+ }, rs = (e) => {
1956
1956
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1957
- let t = e.as ?? "embedding", n = (t) => $o(e, t);
1958
- return Ke({
1957
+ let n = e.as ?? "embedding", r = (t) => ns(e, t);
1958
+ return Ye({
1959
1959
  id: "voltro/vectorEmbedding",
1960
- fields: { [t]: De(e.dimensions) },
1960
+ fields: { [n]: t(e.dimensions) },
1961
1961
  ...e.index === !1 ? {} : { indexes: [{
1962
- fields: [t],
1962
+ fields: [n],
1963
1963
  kind: "hnsw",
1964
1964
  kindOptions: { hnsw: {
1965
1965
  ...e.index?.m === void 0 ? {} : { m: e.index.m },
@@ -1968,23 +1968,23 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
1968
1968
  } }
1969
1969
  }] },
1970
1970
  behaviors: {
1971
- beforeInsert: n,
1972
- beforeUpdate: n
1971
+ beforeInsert: r,
1972
+ beforeUpdate: r
1973
1973
  }
1974
1974
  });
1975
- }, ts = 63, ns = "br_pr", Y = class extends Error {
1975
+ }, is = 63, as = "br_pr", J = class extends Error {
1976
1976
  _tag = "BranchNameInvalid";
1977
1977
  constructor(e) {
1978
1978
  super(e), this.name = "BranchNameInvalid";
1979
1979
  }
1980
- }, rs = (e, t) => {
1981
- if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1982
- let n = xr(e);
1983
- if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1984
- let r = `${ns}${t}_${n}`;
1985
- if (r.length > ts) throw new Y(`branch namespace '${r}' exceeds the ${ts}-byte identifier limit — use a shorter app slug`);
1980
+ }, os = (e, t) => {
1981
+ if (!Number.isInteger(t) || t < 0) throw new J(`prNumber must be a non-negative integer, got ${String(t)}`);
1982
+ let n = wr(e);
1983
+ if (n.replace(/_/g, "") === "") throw new J(`app slug '${e}' has no usable identifier characters`);
1984
+ let r = `${as}${t}_${n}`;
1985
+ if (r.length > is) throw new J(`branch namespace '${r}' exceeds the ${is}-byte identifier limit — use a shorter app slug`);
1986
1986
  return r;
1987
- }, is = (e) => e.startsWith(ns), as = {
1987
+ }, ss = (e) => e.startsWith(as), cs = {
1988
1988
  requested: {
1989
1989
  provision: "provisioning",
1990
1990
  destroy: "destroying"
@@ -2003,19 +2003,19 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
2003
2003
  fail: "failed"
2004
2004
  },
2005
2005
  destroyed: {}
2006
- }, os = class extends Error {
2006
+ }, ls = class extends Error {
2007
2007
  from;
2008
2008
  event;
2009
2009
  _tag = "BranchTransitionInvalid";
2010
2010
  constructor(e, t) {
2011
2011
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2012
2012
  }
2013
- }, ss = (e, t) => {
2014
- let n = as[e][t];
2015
- if (n === void 0) throw new os(e, t);
2013
+ }, us = (e, t) => {
2014
+ let n = cs[e][t];
2015
+ if (n === void 0) throw new ls(e, t);
2016
2016
  return n;
2017
- }, cs = (e, t, n, r, i = [], a = []) => {
2018
- if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2017
+ }, ds = (e, t, n, r, i = [], a = []) => {
2018
+ if (n === "copy" && (r === void 0 || r === "")) throw new J("seed 'copy' requires a parentNamespace to snapshot from");
2019
2019
  let o = [{
2020
2020
  kind: "create-namespace",
2021
2021
  detail: e
@@ -2044,13 +2044,13 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
2044
2044
  kind: "seed",
2045
2045
  detail: `run boot seeds into ${e}`
2046
2046
  }), o;
2047
- }, ls = (e) => {
2048
- if (!is(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2047
+ }, fs = (e) => {
2048
+ if (!ss(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
2049
2049
  return [{
2050
2050
  kind: "drop-namespace",
2051
2051
  detail: e
2052
2052
  }];
2053
- }, us = (e) => {
2053
+ }, ps = (e) => {
2054
2054
  if (e === void 0 || e === "") return !1;
2055
2055
  try {
2056
2056
  let t = new URL(e).hostname.toLowerCase();
@@ -2058,27 +2058,27 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
2058
2058
  } catch {
2059
2059
  return /\bneon\.(tech|build)\b/i.test(e);
2060
2060
  }
2061
- }, ds = (e) => e.prefer === void 0 ? e.seed === "copy" && us(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, fs = (e, t = {}) => [{
2061
+ }, ms = (e) => e.prefer === void 0 ? e.seed === "copy" && ps(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, hs = (e, t = {}) => [{
2062
2062
  kind: "neon-branch-create",
2063
2063
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2064
- }], ps = (e) => {
2065
- if (!is(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2064
+ }], gs = (e) => {
2065
+ if (!ss(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
2066
2066
  return [{
2067
2067
  kind: "neon-branch-delete",
2068
2068
  detail: e
2069
2069
  }];
2070
- }, ms = (e) => e.mechanism === "neon-cow" ? fs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : cs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), hs = (e, t) => e === "neon-cow" ? ps(t) : ls(t), gs = (e, t, n) => {
2070
+ }, _s = (e) => e.mechanism === "neon-cow" ? hs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : ds(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), vs = (e, t) => e === "neon-cow" ? gs(t) : fs(t), ys = (e, t, n) => {
2071
2071
  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);
2072
2072
  return {
2073
2073
  evict: i,
2074
2074
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2075
2075
  };
2076
- }, _s = async (e, t) => {
2077
- let n = rs(e.appSlug, e.prNumber), r = ds({
2076
+ }, bs = async (e, t) => {
2077
+ let n = os(e.appSlug, e.prNumber), r = ms({
2078
2078
  seed: e.seed,
2079
2079
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2080
2080
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2081
- }), i = ms({
2081
+ }), i = _s({
2082
2082
  mechanism: r,
2083
2083
  branchId: n,
2084
2084
  tableNames: e.tableNames,
@@ -2107,16 +2107,16 @@ var It = (e) => typeof e == "string" && e !== "" ? e : null, Lt = async (e, t, n
2107
2107
  mechanism: r,
2108
2108
  steps: i
2109
2109
  };
2110
- }, vs = async (e, t, n) => {
2111
- let r = hs(t, e);
2110
+ }, xs = async (e, t, n) => {
2111
+ let r = vs(t, e);
2112
2112
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2113
- }, ys = (e, t, n) => gs(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, bs = {
2113
+ }, Ss = (e, t, n) => ys(e, t, n), Y = (e) => `"${e.replace(/"/g, "\"\"")}"`, Cs = {
2114
2114
  cascade: "CASCADE",
2115
2115
  restrict: "RESTRICT",
2116
2116
  setNull: "SET NULL",
2117
2117
  noAction: "NO ACTION"
2118
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, xs = (e, t) => {
2119
- let n = t.columns.map(Z).join(", ");
2118
+ }, X = (e) => `'${e.replace(/'/g, "''")}'`, ws = (e, t) => {
2119
+ let n = t.columns.map(X).join(", ");
2120
2120
  return `DO $voltro_branch$
2121
2121
  DECLARE derived name;
2122
2122
  BEGIN
@@ -2125,11 +2125,11 @@ BEGIN
2125
2125
  JOIN pg_class i ON i.oid = x.indexrelid
2126
2126
  JOIN pg_class c ON c.oid = x.indrelid
2127
2127
  JOIN pg_namespace nsp ON nsp.oid = c.relnamespace
2128
- WHERE nsp.nspname = ${Z(e)}
2129
- AND c.relname = ${Z(t.table)}
2128
+ WHERE nsp.nspname = ${X(e)}
2129
+ AND c.relname = ${X(t.table)}
2130
2130
  AND NOT x.indisprimary
2131
2131
  AND x.indisunique = ${t.unique ? "true" : "false"}
2132
- AND i.relname <> ${Z(t.name)}
2132
+ AND i.relname <> ${X(t.name)}
2133
2133
  AND (
2134
2134
  SELECT array_agg(att.attname::text ORDER BY k.ord)
2135
2135
  FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
@@ -2138,39 +2138,39 @@ BEGIN
2138
2138
  LIMIT 1;
2139
2139
  IF derived IS NOT NULL THEN
2140
2140
  EXECUTE format('ALTER INDEX %I.%I RENAME TO %I',
2141
- ${Z(e)}, derived, ${Z(t.name)});
2141
+ ${X(e)}, derived, ${X(t.name)});
2142
2142
  END IF;
2143
2143
  END
2144
2144
  $voltro_branch$`;
2145
- }, Ss = (e, t) => {
2146
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${bs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${bs[t.onUpdate]}`;
2147
- return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2148
- }, Cs = (e) => {
2145
+ }, Ts = (e, t) => {
2146
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Cs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Cs[t.onUpdate]}`;
2147
+ return `ALTER TABLE ${Y(e)}.${Y(t.table)} ADD FOREIGN KEY (${Y(t.column)}) REFERENCES ${Y(e)}.${Y(t.targetTable)} (${Y(t.targetColumn)})${n}${r}`;
2148
+ }, Es = (e) => {
2149
2149
  let t = () => {
2150
2150
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2151
2151
  };
2152
2152
  return {
2153
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2154
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2155
- copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2156
- addForeignKey: (t, n) => e.run(Ss(t, n)),
2157
- restoreIndexName: (t, n) => e.run(xs(t, n)),
2158
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2153
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${Y(t)}`),
2154
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${Y(t)}.${Y(n)} (LIKE ${Y(n)} INCLUDING ALL)`),
2155
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${Y(n)}.${Y(r)} SELECT * FROM ${Y(t)}.${Y(r)}`),
2156
+ addForeignKey: (t, n) => e.run(Ts(t, n)),
2157
+ restoreIndexName: (t, n) => e.run(ws(t, n)),
2158
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${Y(t)} CASCADE`),
2159
2159
  neonBranchCreate: t,
2160
2160
  neonBranchDelete: t
2161
2161
  };
2162
- }, ws = class extends Error {
2162
+ }, Ds = class extends Error {
2163
2163
  _tag = "TenantResidencyUnresolved";
2164
2164
  constructor(e) {
2165
2165
  super(e), this.name = "TenantResidencyUnresolved";
2166
2166
  }
2167
- }, Ts = class extends Error {
2167
+ }, Os = class extends Error {
2168
2168
  region;
2169
2169
  _tag = "TenantRegionUnavailable";
2170
2170
  constructor(e, t) {
2171
2171
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2172
2172
  }
2173
- }, Es, Ds = (e) => {
2173
+ }, ks, As = (e) => {
2174
2174
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2175
2175
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2176
2176
  let t = /* @__PURE__ */ new Map();
@@ -2179,98 +2179,98 @@ $voltro_branch$`;
2179
2179
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2180
2180
  t.set(n.tenantId, n.region);
2181
2181
  }
2182
- return Es = e, e;
2183
- }, Os = () => Es, ks = () => {
2184
- Es = void 0;
2185
- }, As = (e, t) => {
2186
- if (e == null || e === "") throw new ws("residency is on but the request has no resolvable tenant — refusing to bind a store");
2182
+ return ks = e, e;
2183
+ }, js = () => ks, Ms = () => {
2184
+ ks = void 0;
2185
+ }, Ns = (e, t) => {
2186
+ if (e == null || e === "") throw new Ds("residency is on but the request has no resolvable tenant — refusing to bind a store");
2187
2187
  let n = t.homes.find((t) => t.tenantId === e);
2188
- if (n === void 0) throw new ws(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2188
+ if (n === void 0) throw new Ds(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2189
2189
  return n;
2190
- }, js = (e, t) => t.servableRegions.includes(e), Ms = (e, t) => {
2191
- let n = As(e.tenantId, t), r = Sr(n.tenantId);
2190
+ }, Ps = (e, t) => t.servableRegions.includes(e), Fs = (e, t) => {
2191
+ let n = Ns(e.tenantId, t), r = Tr(n.tenantId);
2192
2192
  return {
2193
2193
  region: n.region,
2194
2194
  namespace: r,
2195
2195
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2196
2196
  };
2197
- }, Ns = (e, t, n) => {
2198
- let r = Ms(e, t);
2199
- if (!js(r.region, t)) throw new Ts(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2197
+ }, Is = (e, t, n) => {
2198
+ let r = Fs(e, t);
2199
+ if (!Ps(r.region, t)) throw new Os(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2200
2200
  let i = n.get(r.region);
2201
- if (i === void 0) throw new Ts(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2201
+ if (i === void 0) throw new Os(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2202
2202
  return {
2203
2203
  store: i,
2204
2204
  placement: r
2205
2205
  };
2206
- }, Ps = async (e, t, n, r) => {
2207
- let { store: i, placement: a } = Ns(e, t, n);
2206
+ }, Ls = async (e, t, n, r) => {
2207
+ let { store: i, placement: a } = Is(e, t, n);
2208
2208
  return await r(i, a), a;
2209
- }, Fs = (e) => {
2209
+ }, Rs = (e) => {
2210
2210
  if (typeof e == "string") return e;
2211
2211
  if ("jsonPath" in e) {
2212
2212
  let { column: t, path: n, numeric: r } = e.jsonPath;
2213
2213
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2214
2214
  }
2215
2215
  return `(${e.expr})`;
2216
- }, Q = (e) => e.map(Fs), Is = (e, t) => {
2216
+ }, Z = (e) => e.map(Rs), zs = (e, t) => {
2217
2217
  if (e.length !== t.length) return !1;
2218
- for (let n = 0; n < e.length; n++) if (Fs(e[n]) !== Fs(t[n])) return !1;
2218
+ for (let n = 0; n < e.length; n++) if (Rs(e[n]) !== Rs(t[n])) return !1;
2219
2219
  return !0;
2220
- }, Ls = (e, t) => {
2220
+ }, Bs = (e, t) => {
2221
2221
  if (e.length >= t.length) return !1;
2222
- for (let n = 0; n < e.length; n++) if (Fs(e[n]) !== Fs(t[n])) return !1;
2222
+ for (let n = 0; n < e.length; n++) if (Rs(e[n]) !== Rs(t[n])) return !1;
2223
2223
  return !0;
2224
- }, Rs = (e) => {
2224
+ }, Vs = (e) => {
2225
2225
  let t = [], n = e.appliedIndexes, r = e.tableName;
2226
2226
  for (let e = 0; e < n.length; e++) {
2227
2227
  let i = n[e];
2228
2228
  for (let a = e + 1; a < n.length; a++) {
2229
2229
  let e = n[a];
2230
- if (Is(i.fields, e.fields)) {
2230
+ if (zs(i.fields, e.fields)) {
2231
2231
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2232
2232
  t.push({
2233
2233
  kind: "duplicate-fields",
2234
2234
  table: r,
2235
2235
  redundant: n,
2236
2236
  coveredBy: a,
2237
- 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).`
2237
+ 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).`
2238
2238
  });
2239
2239
  continue;
2240
2240
  }
2241
- Ls(i.fields, e.fields) ? t.push({
2241
+ Bs(i.fields, e.fields) ? t.push({
2242
2242
  kind: "redundant-prefix",
2243
2243
  table: r,
2244
2244
  redundant: i,
2245
2245
  coveredBy: e,
2246
- 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).`
2247
- }) : Ls(e.fields, i.fields) && t.push({
2246
+ 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).`
2247
+ }) : Bs(e.fields, i.fields) && t.push({
2248
2248
  kind: "redundant-prefix",
2249
2249
  table: r,
2250
2250
  redundant: e,
2251
2251
  coveredBy: i,
2252
- 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).`
2252
+ 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).`
2253
2253
  });
2254
2254
  }
2255
2255
  }
2256
2256
  return t;
2257
- }, zs = (e) => {
2257
+ }, Hs = (e) => {
2258
2258
  let t = [];
2259
- for (let n of e) t.push(...Rs(n));
2259
+ for (let n of e) t.push(...Vs(n));
2260
2260
  return t;
2261
- }, Bs = "\x1B[", Vs = `${Bs}38;2;245;158;11m`, Hs = `${Bs}38;2;16;185;129m`, Us = (e, t) => `${e}${t}${M.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Us(t, n) : n, Ws = (e, t = {}) => {
2262
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, M.dim, e.padEnd(11)), a = (e) => $(n, (e) => M.bold(M.brand(e)), e), o = (e) => $(n, M.brightRed24, e), s = (e) => $(n, Hs, e), c = (e) => $(n, Vs, e), l = (e) => $(n, M.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, M.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2261
+ }, Us = "\x1B[", Ws = `${Us}38;2;245;158;11m`, Gs = `${Us}38;2;16;185;129m`, Ks = (e, t) => `${e}${t}${A.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : Ks(t, n) : n, qs = (e, t = {}) => {
2262
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, A.dim, e.padEnd(11)), a = (e) => Q(n, (e) => A.bold(A.brand(e)), e), o = (e) => Q(n, A.brightRed24, e), s = (e) => Q(n, Gs, e), c = (e) => Q(n, Ws, e), l = (e) => Q(n, A.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, A.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
2263
2263
  let n = e.slice(0, t), r = e.slice(t), i = [];
2264
2264
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2265
2265
  }, m = [];
2266
- 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, M.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");
2267
- }, Gs = (e, { apply: t, undo: n }) => ({
2266
+ 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, 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");
2267
+ }, Js = (e, { apply: t, undo: n }) => ({
2268
2268
  name: e,
2269
2269
  apply: t,
2270
2270
  undo: n
2271
- }), Ks = (e) => {
2271
+ }), Ys = (e) => {
2272
2272
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2273
- let t = e.steps({ step: Gs });
2273
+ let t = e.steps({ step: Js });
2274
2274
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2275
2275
  return {
2276
2276
  __migration: !0,
@@ -2278,91 +2278,91 @@ $voltro_branch$`;
2278
2278
  name: e.name,
2279
2279
  steps: t
2280
2280
  };
2281
- }, qs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Js = T("_voltro_migrations", {
2282
- id: b({ prefix: "mig" }),
2283
- name: C(),
2284
- hash: C(),
2285
- status: C(),
2286
- appliedAt: S().nullable(),
2287
- durationMs: D().nullable(),
2288
- errorMessage: C().nullable(),
2289
- errorStack: C().nullable(),
2290
- workflowRunId: C().nullable(),
2291
- createdAt: S().default("now"),
2292
- updatedAt: S().default("now").onUpdate("now")
2293
- }).index(["status"]), Ys = T("_voltro_seeds", {
2294
- id: b({ prefix: "seed" }),
2295
- name: C(),
2296
- lifecycle: C(),
2297
- fingerprint: C(),
2298
- cronSchedule: C().nullable(),
2299
- watchedTables: x().nullable(),
2300
- nextRunAt: S().nullable(),
2301
- lastRunStatus: C().nullable(),
2302
- lastRunAt: S().nullable(),
2303
- lastRunDurationMs: D().nullable(),
2304
- lastRunRowsTouched: D().nullable(),
2305
- lastError: C().nullable(),
2306
- workflowRunId: C().nullable(),
2307
- createdAt: S().default("now"),
2308
- updatedAt: S().default("now").onUpdate("now")
2309
- }).index(["lifecycle"]).index(["nextRunAt"]), Xs = T("_voltro_migration_plans", {
2310
- id: b({ prefix: "plan" }),
2311
- fingerprint: C(),
2312
- liveFingerprint: C().nullable(),
2313
- operations: x(),
2314
- rollbackPlan: x().nullable(),
2315
- appliedBy: C(),
2316
- environment: C(),
2317
- source: C(),
2318
- onlineStrategy: C().nullable(),
2319
- durationMs: D(),
2320
- notes: C().nullable(),
2321
- squashedAt: S().nullable(),
2322
- appliedAt: S().default("now"),
2323
- createdAt: S().default("now"),
2324
- updatedAt: S().default("now").onUpdate("now")
2325
- }).index(["fingerprint"]).index(["environment"]), Zs = T("_voltro_idempotency", {
2326
- id: b({ prefix: "idem" }),
2327
- scope: C(),
2328
- key: C(),
2329
- status: C(),
2330
- response: x().nullable(),
2331
- createdAt: S().default("now")
2332
- }).unique(["scope", "key"]).index(["createdAt"]), Qs = T("_voltro_kv", {
2333
- id: b({ prefix: "kv" }),
2334
- key: C().unique(),
2335
- value: C().nullable(),
2336
- expiresAt: S().nullable(),
2337
- createdAt: S().default("now"),
2338
- updatedAt: S().default("now").onUpdate("now")
2339
- }).index(["expiresAt"]), $s = T("_voltro_api_keys", {
2340
- id: b({ prefix: "apikey" }),
2341
- tenantId: C().nullable(),
2342
- name: C(),
2343
- hashedKey: C().maxLength(64).unique(),
2344
- keyPrefix: C(),
2345
- scopes: x().nullable(),
2346
- lastUsedAt: S().nullable(),
2347
- requestCount: D().default(0),
2348
- expiresAt: S().nullable(),
2349
- revokedAt: S().nullable(),
2350
- createdBy: C().nullable(),
2351
- onBehalfOf: C().nullable(),
2352
- metadata: x().nullable(),
2353
- createdAt: S().default("now")
2354
- }).index("byApiKeyTenant", ["tenantId"]), ec = [
2355
- Js,
2356
- Ys,
2357
- Xs
2358
- ], tc = "_voltro_replace_in_progress", nc = T(tc, {
2359
- id: b({ prefix: "repl" }),
2360
- startedAt: S().default("now"),
2361
- kind: C().default("replace"),
2362
- tables: C().nullable(),
2363
- capture: C().nullable(),
2364
- via: C()
2365
- }), rc = (e) => {
2281
+ }, Xs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Zs = w("_voltro_migrations", {
2282
+ id: a({ prefix: "mig" }),
2283
+ name: S(),
2284
+ hash: S(),
2285
+ status: S(),
2286
+ appliedAt: y().nullable(),
2287
+ durationMs: x().nullable(),
2288
+ errorMessage: S().nullable(),
2289
+ errorStack: S().nullable(),
2290
+ workflowRunId: S().nullable(),
2291
+ createdAt: y().default("now"),
2292
+ updatedAt: y().default("now").onUpdate("now")
2293
+ }).index(["status"]), Qs = w("_voltro_seeds", {
2294
+ id: a({ prefix: "seed" }),
2295
+ name: S(),
2296
+ lifecycle: S(),
2297
+ fingerprint: S(),
2298
+ cronSchedule: S().nullable(),
2299
+ watchedTables: b().nullable(),
2300
+ nextRunAt: y().nullable(),
2301
+ lastRunStatus: S().nullable(),
2302
+ lastRunAt: y().nullable(),
2303
+ lastRunDurationMs: x().nullable(),
2304
+ lastRunRowsTouched: x().nullable(),
2305
+ lastError: S().nullable(),
2306
+ workflowRunId: S().nullable(),
2307
+ createdAt: y().default("now"),
2308
+ updatedAt: y().default("now").onUpdate("now")
2309
+ }).index(["lifecycle"]).index(["nextRunAt"]), $s = w("_voltro_migration_plans", {
2310
+ id: a({ prefix: "plan" }),
2311
+ fingerprint: S(),
2312
+ liveFingerprint: S().nullable(),
2313
+ operations: b(),
2314
+ rollbackPlan: b().nullable(),
2315
+ appliedBy: S(),
2316
+ environment: S(),
2317
+ source: S(),
2318
+ onlineStrategy: S().nullable(),
2319
+ durationMs: x(),
2320
+ notes: S().nullable(),
2321
+ squashedAt: y().nullable(),
2322
+ appliedAt: y().default("now"),
2323
+ createdAt: y().default("now"),
2324
+ updatedAt: y().default("now").onUpdate("now")
2325
+ }).index(["fingerprint"]).index(["environment"]), ec = w("_voltro_idempotency", {
2326
+ id: a({ prefix: "idem" }),
2327
+ scope: S(),
2328
+ key: S(),
2329
+ status: S(),
2330
+ response: b().nullable(),
2331
+ createdAt: y().default("now")
2332
+ }).unique(["scope", "key"]).index(["createdAt"]), tc = w("_voltro_kv", {
2333
+ id: a({ prefix: "kv" }),
2334
+ key: S().unique(),
2335
+ value: S().nullable(),
2336
+ expiresAt: y().nullable(),
2337
+ createdAt: y().default("now"),
2338
+ updatedAt: y().default("now").onUpdate("now")
2339
+ }).index(["expiresAt"]), nc = w("_voltro_api_keys", {
2340
+ id: a({ prefix: "apikey" }),
2341
+ tenantId: S().nullable(),
2342
+ name: S(),
2343
+ hashedKey: S().maxLength(64).unique(),
2344
+ keyPrefix: S(),
2345
+ scopes: b().nullable(),
2346
+ lastUsedAt: y().nullable(),
2347
+ requestCount: x().default(0),
2348
+ expiresAt: y().nullable(),
2349
+ revokedAt: y().nullable(),
2350
+ createdBy: S().nullable(),
2351
+ onBehalfOf: S().nullable(),
2352
+ metadata: b().nullable(),
2353
+ createdAt: y().default("now")
2354
+ }).index("byApiKeyTenant", ["tenantId"]), rc = [
2355
+ Zs,
2356
+ Qs,
2357
+ $s
2358
+ ], ic = "_voltro_replace_in_progress", ac = w(ic, {
2359
+ id: a({ prefix: "repl" }),
2360
+ startedAt: y().default("now"),
2361
+ kind: S().default("replace"),
2362
+ tables: S().nullable(),
2363
+ capture: S().nullable(),
2364
+ via: S()
2365
+ }), oc = (e) => {
2366
2366
  if (e.length !== 0) return `refusing to start: a destructive data operation did not finish.
2367
2367
  ${e.map((e) => {
2368
2368
  let t = Number.isFinite(e.startedAt.getTime()) ? `${Math.max(0, Math.round((Date.now() - e.startedAt.getTime()) / 6e4))} minute(s) ago` : "at an unknown time";
@@ -2376,22 +2376,22 @@ ${e.map((e) => {
2376
2376
 
2377
2377
  When the data is back, or you have decided the current state is correct, clear the marker:
2378
2378
  voltro data clear-replace-marker --yes`;
2379
- }, ic = "id", ac = (e, t) => {
2380
- let n = p(e);
2379
+ }, $ = "id", sc = (e, t) => {
2380
+ let n = m(e);
2381
2381
  if (n === void 0) return t;
2382
- let r = n.fields[ic]?.idScheme;
2383
- if (r === void 0 || t[ic] != null) return t;
2382
+ let r = n.fields[$]?.idScheme;
2383
+ if (r === void 0 || t[$] != null) return t;
2384
2384
  if (r.kind === "numeric") {
2385
- if (!(ic in t)) return t;
2385
+ if (!($ in t)) return t;
2386
2386
  let e = { ...t };
2387
- return delete e[ic], e;
2387
+ return delete e[$], e;
2388
2388
  }
2389
- let i = Fe(r, e);
2389
+ let i = Re(r, e);
2390
2390
  return i === null ? t : {
2391
2391
  ...t,
2392
- [ic]: i
2392
+ [$]: i
2393
2393
  };
2394
- }, oc = (e, t) => t.map((t) => ac(e, t)), sc = {
2394
+ }, cc = (e, t) => t.map((t) => sc(e, t)), lc = {
2395
2395
  postgres: { maxBindParameters: 65535 },
2396
2396
  mysql: { maxBindParameters: 65535 },
2397
2397
  mariadb: { maxBindParameters: 65535 },
@@ -2401,49 +2401,56 @@ ${e.map((e) => {
2401
2401
  },
2402
2402
  sqlite: { maxBindParameters: 32766 },
2403
2403
  turso: { maxBindParameters: 32766 }
2404
- }, cc = (e) => sc[e], lc = (e) => {
2404
+ }, uc = (e) => lc[e], dc = (e) => {
2405
2405
  let t = /* @__PURE__ */ new Set();
2406
2406
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2407
2407
  return t.size;
2408
- }, uc = (e, t) => {
2408
+ }, fc = (e, t) => {
2409
2409
  if (t === void 0 || e.length === 0) return [e];
2410
- let n = Math.max(1, lc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2410
+ let n = Math.max(1, dc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2411
2411
  if (e.length <= a) return [e];
2412
2412
  let o = [];
2413
2413
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2414
2414
  return o;
2415
- }, dc = (e, t) => {
2415
+ }, pc = (e, t) => {
2416
2416
  let n = [], r = t;
2417
2417
  for (let [t, i] of Object.entries(e.fields)) {
2418
2418
  let e = i;
2419
2419
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2420
2420
  }
2421
2421
  return n;
2422
- }, fc = (e, t) => {
2423
- let n = t;
2424
- return e.filter((e) => n[e] === void 0 || n[e] === null);
2425
- }, pc = (e, t, n) => e.insert(t.tableName, n), mc = (e, t, n, r) => e.upsert(t.tableName, n, {
2422
+ }, mc = (e, t, n) => {
2423
+ let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
2424
+ for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
2425
+ column: e,
2426
+ reason: "absent"
2427
+ }) : r[e] === null && a.push({
2428
+ column: e,
2429
+ reason: "null"
2430
+ }));
2431
+ return a;
2432
+ }, hc = (e, t, n) => e.insert(t.tableName, n), gc = (e, t, n, r) => e.upsert(t.tableName, n, {
2426
2433
  conflictColumns: r.conflictColumns,
2427
2434
  ...r.update === void 0 ? {} : { update: r.update }
2428
- }), hc = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), gc = 512, _c = (e) => {
2435
+ }), _c = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), vc = 512, yc = (e) => {
2429
2436
  e.setMaxListeners(512);
2430
- }, vc = (e, t, n) => ({
2437
+ }, bc = (e, t, n) => ({
2431
2438
  _tag: "PrimaryKeyConflictError",
2432
2439
  table: e,
2433
2440
  key: t,
2434
2441
  cause: n
2435
- }), yc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", bc = {
2442
+ }), xc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Sc = {
2436
2443
  postgres: 5432,
2437
2444
  mysql: 3306,
2438
2445
  mariadb: 3306,
2439
2446
  mssql: 1433
2440
- }, xc = /* @__PURE__ */ new Set([
2447
+ }, Cc = /* @__PURE__ */ new Set([
2441
2448
  "localhost",
2442
2449
  "127.0.0.1",
2443
2450
  "::1",
2444
2451
  "[::1]",
2445
2452
  "0.0.0.0"
2446
- ]), Sc = (e) => {
2453
+ ]), wc = (e) => {
2447
2454
  let t = e.host, n = e.port, r = e.database;
2448
2455
  if (e.url !== void 0 && e.url !== "") try {
2449
2456
  let i = new URL(e.url);
@@ -2452,29 +2459,29 @@ ${e.map((e) => {
2452
2459
  return;
2453
2460
  }
2454
2461
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2455
- let i = n ?? bc[(e.dialect ?? "").toLowerCase()];
2462
+ let i = n ?? Sc[(e.dialect ?? "").toLowerCase()];
2456
2463
  if (i === void 0 || !Number.isFinite(i)) return;
2457
2464
  let a = t.toLowerCase();
2458
2465
  return {
2459
- host: xc.has(a) ? "localhost" : a,
2466
+ host: Cc.has(a) ? "localhost" : a,
2460
2467
  port: i,
2461
2468
  database: r.toLowerCase()
2462
2469
  };
2463
- }, Cc = (e) => {
2464
- let t = Sc(e);
2465
- if (t !== void 0) return Nt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2466
- }, wc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Tc = {
2470
+ }, Tc = (e) => {
2471
+ let t = wc(e);
2472
+ if (t !== void 0) return Lt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2473
+ }, Ec = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Dc = {
2467
2474
  app: 3,
2468
2475
  plugin: 2,
2469
2476
  framework: 1
2470
- }, Ec = /* @__PURE__ */ new Map(), Dc = [], Oc = () => [...Dc], kc = (e) => {
2477
+ }, Oc = /* @__PURE__ */ new Map(), kc = [], Ac = () => [...kc], jc = (e) => {
2471
2478
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2472
2479
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2473
- let t = e.source ?? "app", n = Ec.get(e.table);
2480
+ let t = e.source ?? "app", n = Oc.get(e.table);
2474
2481
  if (n !== void 0) {
2475
2482
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2476
- if (Tc[t] < Tc[r]) {
2477
- i && Dc.push({
2483
+ if (Dc[t] < Dc[r]) {
2484
+ i && kc.push({
2478
2485
  table: e.table,
2479
2486
  kept: {
2480
2487
  source: r,
@@ -2487,7 +2494,7 @@ ${e.map((e) => {
2487
2494
  });
2488
2495
  return;
2489
2496
  }
2490
- i && r !== t && Dc.push({
2497
+ i && r !== t && kc.push({
2491
2498
  table: e.table,
2492
2499
  kept: {
2493
2500
  source: t,
@@ -2499,51 +2506,51 @@ ${e.map((e) => {
2499
2506
  }
2500
2507
  });
2501
2508
  }
2502
- Ec.set(e.table, {
2509
+ Oc.set(e.table, {
2503
2510
  ...e,
2504
2511
  source: t
2505
2512
  });
2506
- }, Ac = () => [...Ec.values()], jc = () => {
2507
- Ec.clear(), Dc.length = 0;
2508
- }, Mc = async (e, t, n, r = 2e4) => {
2513
+ }, Mc = () => [...Oc.values()], Nc = () => {
2514
+ Oc.clear(), kc.length = 0;
2515
+ }, Pc = async (e, t, n, r = 2e4) => {
2509
2516
  let i = new Date(t - e.ttlMs), a = 0;
2510
2517
  for (;;) {
2511
2518
  let t = await n(e.table, e.timeColumn, i, r, e.where);
2512
2519
  if (a += t, t < r) break;
2513
2520
  }
2514
2521
  return a;
2515
- }, Nc = (e, t) => {
2522
+ }, Fc = (e, t) => {
2516
2523
  let n = Number(e ?? String(t));
2517
2524
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2518
- }, Pc = "_voltro_cdc_offsets", Fc = T(Pc, {
2519
- id: b({ prefix: "cdcoff" }),
2520
- replicaId: C(),
2521
- streamName: C(),
2522
- binlogFile: C(),
2523
- binlogPosition: C(),
2524
- updatedAt: S()
2525
- }).index(["replicaId"]), Ic = T(Pc, {
2526
- id: b({ prefix: "cdcoff" }),
2527
- replicaId: C(),
2528
- streamName: C(),
2529
- ctVersion: C(),
2530
- updatedAt: S()
2531
- }).index(["replicaId"]), Lc = "_voltro_data_transfers", Rc = T(Lc, {
2532
- id: b({ prefix: "dimp" }),
2533
- startedAt: S().default("now"),
2534
- finishedAt: S().nullable(),
2535
- direction: C().default("import"),
2536
- mode: C(),
2537
- via: C(),
2538
- bundle: C().nullable(),
2539
- sourceFingerprint: C().nullable(),
2540
- tablesWritten: D().default(0),
2541
- rowsWritten: D().default(0),
2542
- failure: C().nullable(),
2543
- staged: ue().nullable()
2544
- }).renamedFrom("_voltro_data_imports").nonReactive(), zc = (e) => {
2525
+ }, Ic = "_voltro_cdc_offsets", Lc = w(Ic, {
2526
+ id: a({ prefix: "cdcoff" }),
2527
+ replicaId: S(),
2528
+ streamName: S(),
2529
+ binlogFile: S(),
2530
+ binlogPosition: S(),
2531
+ updatedAt: y()
2532
+ }).index(["replicaId"]), Rc = w(Ic, {
2533
+ id: a({ prefix: "cdcoff" }),
2534
+ replicaId: S(),
2535
+ streamName: S(),
2536
+ ctVersion: S(),
2537
+ updatedAt: y()
2538
+ }).index(["replicaId"]), zc = "_voltro_data_transfers", Bc = w(zc, {
2539
+ id: a({ prefix: "dimp" }),
2540
+ startedAt: y().default("now"),
2541
+ finishedAt: y().nullable(),
2542
+ direction: S().default("import"),
2543
+ mode: S(),
2544
+ via: S(),
2545
+ bundle: S().nullable(),
2546
+ sourceFingerprint: S().nullable(),
2547
+ tablesWritten: x().default(0),
2548
+ rowsWritten: x().default(0),
2549
+ failure: S().nullable(),
2550
+ staged: fe().nullable()
2551
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Vc = (e) => {
2545
2552
  let t = Number.isFinite(e.startedAt.getTime()) ? e.startedAt.toISOString() : "an unknown time", n = e.direction === "import" ? e.mode : `${e.direction} ${e.mode}`, r = e.failure === null ? e.finishedAt === null ? `${n} — started and never reported finishing` : e.direction === "backup" || e.direction === "restore" ? `${n} — finished${e.rowsWritten > 0 ? ` (${e.rowsWritten} blob(s))` : ""}` : `${n} — ${e.rowsWritten} row(s) across ${e.tablesWritten} table(s)` : `FAILED ${n} — ${e.failure}`, i = e.staged === null ? "" : e.staged ? " · staged (target untouched until the swap)" : " · NOT staged (target emptied first)";
2546
2553
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2547
- }, Bc = "postgres";
2554
+ }, Hc = "postgres";
2548
2555
  //#endregion
2549
- export { Re as AUTO_FILLED_COLUMNS, sc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, os as BranchTransitionInvalid, Pc as CDC_OFFSETS_TABLE, gc as CHANGE_LISTENER_CEILING, ve as ColumnBuilder, Lc as DATA_TRANSFERS_TABLE, we as DEFAULT_ACQUIRE_TIMEOUT_MS, Oo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Vn as DEFAULT_SUBJECT_GRAPH_DEPTH, Ht as ENCRYPTED_PREFIX, Bc as ENGINE, ir as EagerCardinalityError, Ge as FILE_MIGRATION_PATTERN, lt as FRAMEWORK_LIVE_TABLES, Ut as FieldDecryptionError, Xa as ID_COLUMN_MAX_LENGTH, Vo as INITIAL_VERSION, oa as MATCHES_NO_ROWS, Be as MAX_IDENTIFIER_LENGTH, tc as REPLACE_IN_PROGRESS_TABLE, Ft as SqlClient, Jo as TableStreamError, vr as TenantNamespaceInvalid, _r as TenantNamespaceUnresolved, Ts as TenantRegionUnavailable, ws as TenantResidencyUnresolved, Ho as VOLTRO_EXPIRES_MIXIN_ID, Wo as VOLTRO_LOCAL_FIRST_MIXIN_ID, Lo as VersionConflict, rt as WARN_IDENTIFIER_LENGTH, $s as _voltroApiKeysTable, Fc as _voltroCdcOffsetsTable, Rc as _voltroDataTransfersTable, Zs as _voltroIdempotencyTable, Qs as _voltroKvTable, Xs as _voltroMigrationPlansTable, Js as _voltroMigrationsTable, Ic as _voltroMssqlCdcOffsetsTable, nc as _voltroReplaceInProgressTable, Ys as _voltroSeedsTable, Ki as actorsTable, ys as admitBranch, bt as allEnumRenames, Rn as allRegisteredRelations, h as allRegisteredTables, ua as and, u as array, ra as arrayContains, aa as arrayHas, ia as arrayOverlaps, or as attachEagerLoads, Ma as attributionFields, Ia as attributionKey, zs as auditAllTableIndexes, Rs as auditTableIndexes, pt as avg, yt as avgOver, Ga as beginLocalWrite, c as bigint, Ns as bindResidentStore, ue as boolean, rs as branchNamespaceName, cc as bulkInsertLimitsFor, Ye as bytes, Da as changeDelete, Ta as changeInsert, Oa as changeSoftDelete, Ea as changeUpdate, uc as chunkRowsForInsert, za as claimPendingAttribution, cn as classifyConstraintViolation, Ne as clearEnumRenames, Ja as clearPendingAttribution, Bn as clearRelationsRegistry, ks as clearResidencyConfig, jc as clearRetentions, ye as clearTableRegistry, ro as clearWriteRecorders, U as coercePredicateForSqlite, Er as coercePredicateValue, Dr as coercePredicateValues, Ri as coerceValueForSqlite, Sa as collectSubqueries, Me as column, mn as columnSchema, lc as columnsPerRow, Vr as compileEagerJson, I as compilePredicate, Or as compileRawFragment, Br as compileSelect, $o as computeEmbedding, Cc as connectionIdentity, ta as contains, _t as count, he as countDistinct, n as crdtManagedColumns, qe as crdtText, ja as currentWriteAttribution, a as databaseHandle, oe as date, ce as dbEnum, So as dbMetricTagCacheSizeForTests, To as dbOperationsInFlight, fe as decimal, vt as declareEnumRename, Jt as decodeFieldValue, tr as decodeRowsFromSchema, $t as decryptFieldsOnRead, Ks as defineMigration, Ke as defineMixin, st as defineSeed, ht as denseRank, Jn as deriveSubjectGraph, ct as deriveTypeIdPrefix, $a as derivedRowId, eo as derivedRowIdLength, dn as describeDriverError, fn as describeRowBindings, zc as describeTransferRun, Vt as deserializeArraysOnRead, $e as drainIdentifierWarnings, f as dropped, Kt as encodeFieldValue, rr as encodeRowForSchema, Qt as encryptFieldsForWrite, Zt as encryptedColumnsOf, Ka as endLocalWrite, gs as enforceBranchLimits, Se as ensureTableRegistered, qi as eq, kr as escapeLike, xa as evaluatePredicate, _e as except, _a as exists, Uo as expires, wa as externalChangeEvent, an as extractDbCause, Pe as fireSchemaChangeSeeds, Xe as fireTenantCreateSeeds, Ws as formatIndexAuditIssue, Yn as formatSubjectGraph, ec as frameworkTables, Fe as generateId, ft as generateSnowflake, te as geography, y as geometry, ge as getEnumRenames, Ln as getRelation, In as getRelations, Os as getResidencyConfig, p as getTable, Yi as gt, Xi as gte, gr as hasEagerLoads, Qo as hybridSearch, b as id, $i as inSet, ha as inSubquery, Dn as inferForeignKey, pc as insertRow, D as integer, rc as interruptedReplaceRefusal, l as intersect, i as interval, is as isBranchNamespace, Sn as isEmptyRelationsSpec, Gt as isEncrypted, Wt as isFieldDecryptionError, Ae as isFileMigration, ln as isForeignKeyViolation, et as isFrameworkOwnedLiveTable, Ko as isLocalFirst, qs as isMigrationDefinition, Ee as isMysqlFamily, us as isNeonConnection, ca as isNotNull, sa as isNull, yc as isPrimaryKeyConflictError, un as isQueryTimeout, Yt as isRawEncoding, js as isRegionServable, Cn as isRelationsSpec, dt as isSeedDefinition, pe as isSqliteFamily, re as isTableReactive, Qe as isView, x as json, pa as jsonField, ut as jsonIndex, s as lag, le as lead, Oc as listRetentionConflicts, Ac as listRetentions, Go as localFirst, qo as localFirstTables, Zi as lt, Qi as lte, jo as makeEagerFallbackReporter, Cs as makeNamespaceBranchExecutor, Tn as many, En as manyToMany, g as materializeFields, Je as max, tt as migration, t as min, fc as missingConflictColumns, dc as missingRequiredColumns, je as mixin, Ji as neq, ss as nextBranchState, Sc as normaliseTarget, fa as not, va as notExists, ea as notInSet, ga as notInSubquery, be as numeric, Do as observeDbOp, wn as one, ar as oneCardinalityMessage, da as or, w as orderClausesOf, ae as paginateBy, se as paginateById, Ya as pendingAttributionCount, ms as planBranch, cs as planBranchProvision, ls as planBranchTeardown, hs as planBranchTeardownFor, fs as planNeonBranchProvision, ps as planNeonBranchTeardown, zo as planVersionedUpdate, o as pluginRef, gt as pluginRefSpecOf, vc as primaryKeyConflictError, _s as provisionBranch, Ps as provisionResidentTenant, Cr as qualifyTable, de as queryFor, Ue as queryForView, e as quoteIdent, _c as raiseChangeListenerCeiling, d as rank, Ce as raw, m as readableByColumns, v as real, Eo as recordDbOp, co as recordsTable, at as reference, Hi as registerCoreTables, Fn as registerDiscoveredRelations, Ra as registerPendingAttribution, Pn as registerRelations, kc as registerRetention, it as registerTable, to as registerWriteRecorder, xn as relations, Wi as requireActors, _ as requireTable, Gi as requireTenants, xo as resetDbMetricTagCacheForTests, Le as resetSnowflake, Ms as residentPlacement, Lt as resolveActorSnapshot, ds as resolveBranchMechanism, Ao as resolveEagerFallbackWarnIntervalMs, qa as resolveEchoAttribution, ee as resolveFullTextIndex, Ze as resolveIdScheme, nt as resolveMixinGraph, As as resolveTenantHome, Sr as resolveTenantNamespace, Nc as retentionTtlMsFromEnv, ie as rowNumber, hn as rowSchema, Fo as runRetryingTransaction, Io as runStoreTransaction, Aa as runWithWriteAttribution, lo as runWriteRecorders, wc as sameDatabase, xr as sanitizeIdentifierFragment, Bt as serializeArraysForWrite, ne as serverOnlyColumns, Ds as setResidencyConfig, Ie as setSchemaChangeSeedHook, ze as setTenantCreateSeedHook, Mo as settleTransactionExit, Bo as settleVersionedUpdate, la as spatialPredicate, ac as stampGeneratedId, oc as stampGeneratedIds, na as startsWith, Zo as streamTable, me as sum, xt as sumOver, ao as suspendWriteRecorders, oo as suspendWriteRecordersEffect, Mc as sweepRetention, T as table, vs as teardownBranch, C as text, S as timestamp, St as timestampMs, Ct as timestampMsOrNull, r as union, xe as unionAll, Te as unregisterTable, no as unregisterWriteRecorder, hc as updateManyRow, mc as upsertRow, We as validateColumnName, He as validateIndexName, zn as validateRegisteredRelations, jn as validateRelationConfig, ke as validateTableName, mt as validateTypeIdPrefix, De as vector, ot as vectorDistanceToOpclass, es as vectorEmbedding, Ro as versionColumnOf, Ve as view, Oe as viewSql, Ca as walkLeaves, Na as withCapturedAttribution, so as writeRecordersSuspended };
2556
+ export { Ve as AUTO_FILLED_COLUMNS, lc as BULK_INSERT_LIMITS, J as BranchNameInvalid, ls as BranchTransitionInvalid, Ic as CDC_OFFSETS_TABLE, vc as CHANGE_LISTENER_CEILING, xe as ColumnBuilder, zc as DATA_TRANSFERS_TABLE, Ee as DEFAULT_ACQUIRE_TIMEOUT_MS, jo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Gn as DEFAULT_SUBJECT_GRAPH_DEPTH, Kt as ENCRYPTED_PREFIX, Hc as ENGINE, cr as EagerCardinalityError, Je as FILE_MIGRATION_PATTERN, ft as FRAMEWORK_LIVE_TABLES, qt as FieldDecryptionError, Qa as ID_COLUMN_MAX_LENGTH, Wo as INITIAL_VERSION, ca as MATCHES_NO_ROWS, Ue as MAX_IDENTIFIER_LENGTH, ic as REPLACE_IN_PROGRESS_TABLE, zt as SqlClient, Zo as TableStreamError, xr as TenantNamespaceInvalid, br as TenantNamespaceUnresolved, Os as TenantRegionUnavailable, Ds as TenantResidencyUnresolved, Go as VOLTRO_EXPIRES_MIXIN_ID, qo as VOLTRO_LOCAL_FIRST_MIXIN_ID, Bo as VersionConflict, ot as WARN_IDENTIFIER_LENGTH, nc as _voltroApiKeysTable, Lc as _voltroCdcOffsetsTable, Bc as _voltroDataTransfersTable, ec as _voltroIdempotencyTable, tc as _voltroKvTable, $s as _voltroMigrationPlansTable, Zs as _voltroMigrationsTable, Rc as _voltroMssqlCdcOffsetsTable, ac as _voltroReplaceInProgressTable, Qs as _voltroSeedsTable, Ji as actorsTable, Ss as admitBranch, Ct as allEnumRenames, Hn as allRegisteredRelations, g as allRegisteredTables, fa as and, d as array, aa as arrayContains, sa as arrayHas, oa as arrayOverlaps, ur as attachEagerLoads, Pa as attributionFields, Ra as attributionKey, Hs as auditAllTableIndexes, Vs as auditTableIndexes, gt as avg, St as avgOver, qa as beginLocalWrite, l as bigint, Is as bindResidentStore, fe as boolean, os as branchNamespaceName, uc as bulkInsertLimitsFor, Qe as bytes, ka as changeDelete, Da as changeInsert, Aa as changeSoftDelete, Oa as changeUpdate, fc as chunkRowsForInsert, Va as claimPendingAttribution, fn as classifyConstraintViolation, Ie as clearEnumRenames, Xa as clearPendingAttribution, Wn as clearRelationsRegistry, Ms as clearResidencyConfig, Nc as clearRetentions, Se as clearTableRegistry, ao as clearWriteRecorders, U as coercePredicateForSqlite, kr as coercePredicateValue, Ar as coercePredicateValues, Bi as coerceValueForSqlite, wa as collectSubqueries, Fe as column, vn as columnSchema, dc as columnsPerRow, Ur as compileEagerJson, I as compilePredicate, jr as compileRawFragment, Hr as compileSelect, ns as computeEmbedding, Tc as connectionIdentity, ra as contains, bt as count, ve as countDistinct, r as crdtDoc, Xe as crdtManagedColumns, ce as crdtManagedColumnsOf, ue as crdtText, Na as currentWriteAttribution, o as databaseHandle, me as date, p as dbEnum, To as dbMetricTagCacheSizeForTests, Oo as dbOperationsInFlight, ne as decimal, xt as declareEnumRename, Qt as decodeFieldValue, ar as decodeRowsFromSchema, rn as decryptFieldsOnRead, Ys as defineMigration, Ye as defineMixin, ut as defineSeed, vt as denseRank, Qn as deriveSubjectGraph, dt as deriveTypeIdPrefix, to as derivedRowId, no as derivedRowIdLength, hn as describeDriverError, gn as describeRowBindings, Vc as describeTransferRun, Gt as deserializeArraysOnRead, nt as drainIdentifierWarnings, oe as dropped, Xt as encodeFieldValue, sr as encodeRowForSchema, nn as encryptFieldsForWrite, tn as encryptedColumnsOf, Ja as endLocalWrite, ys as enforceBranchLimits, we as ensureTableRegistered, Yi as eq, F as escapeLike, Ca as evaluatePredicate, be as except, ya as exists, Ko as expires, Ea as externalChangeEvent, ln as extractDbCause, Le as fireSchemaChangeSeeds, $e as fireTenantCreateSeeds, qs as formatIndexAuditIssue, $n as formatSubjectGraph, rc as frameworkTables, Re as generateId, ht as generateSnowflake, _e as geography, Tt as geometry, ye as getEnumRenames, Vn as getRelation, Bn as getRelations, js as getResidencyConfig, m as getTable, Zi as gt, Qi as gte, yr as hasEagerLoads, ts as hybridSearch, a as id, ta as inSet, _a as inSubquery, jn as inferForeignKey, hc as insertRow, x as integer, oc as interruptedReplaceRefusal, u as intersect, ee as interval, ss as isBranchNamespace, En as isEmptyRelationsSpec, Yt as isEncrypted, Jt as isFieldDecryptionError, Ne as isFileMigration, pn as isForeignKeyViolation, rt as isFrameworkOwnedLiveTable, Yo as isLocalFirst, Xs as isMigrationDefinition, Ae as isMysqlFamily, ps as isNeonConnection, ua as isNotNull, la as isNull, xc as isPrimaryKeyConflictError, mn as isQueryTimeout, $t as isRawEncoding, Ps as isRegionServable, Dn as isRelationsSpec, mt as isSeedDefinition, he as isSqliteFamily, _ as isTableReactive, tt as isView, b as json, ha as jsonField, pt as jsonIndex, c as lag, de as lead, Ac as listRetentionConflicts, Mc as listRetentions, Jo as localFirst, Xo as localFirstTables, $i as lt, ea as lte, Po as makeEagerFallbackReporter, Es as makeNamespaceBranchExecutor, kn as many, An as manyToMany, Te as materializeFields, Ze as max, it as migration, n as min, mc as missingConflictColumns, pc as missingRequiredColumns, Pe as mixin, Xi as neq, us as nextBranchState, wc as normaliseTarget, ma as not, ba as notExists, na as notInSet, va as notInSubquery, h as numeric, Ao as observeDbOp, On as one, lr as oneCardinalityMessage, pa as or, C as orderClausesOf, se as paginateBy, le as paginateById, Za as pendingAttributionCount, _s as planBranch, ds as planBranchProvision, fs as planBranchTeardown, vs as planBranchTeardownFor, hs as planNeonBranchProvision, gs as planNeonBranchTeardown, Ho as planVersionedUpdate, s as pluginRef, yt as pluginRefSpecOf, bc as primaryKeyConflictError, bs as provisionBranch, Ls as provisionResidentTenant, Er as qualifyTable, pe as queryFor, Ke as queryForView, e as quoteIdent, yc as raiseChangeListenerCeiling, f as rank, ae as raw, ct as readableByColumns, ie as real, ko as recordDbOp, uo as recordsTable, ke as reference, Wi as registerCoreTables, zn as registerDiscoveredRelations, Ba as registerPendingAttribution, Rn as registerRelations, jc as registerRetention, st as registerTable, ro as registerWriteRecorder, Tn as relations, Ki as requireActors, re as requireTable, qi as requireTenants, wo as resetDbMetricTagCacheForTests, Be as resetSnowflake, Fs as residentPlacement, Vt as resolveActorSnapshot, ms as resolveBranchMechanism, No as resolveEagerFallbackWarnIntervalMs, Ya as resolveEchoAttribution, te as resolveFullTextIndex, et as resolveIdScheme, at as resolveMixinGraph, Ns as resolveTenantHome, Tr as resolveTenantNamespace, Fc as retentionTtlMsFromEnv, v as rowNumber, yn as rowSchema, Ro as runRetryingTransaction, zo as runStoreTransaction, Ma as runWithWriteAttribution, fo as runWriteRecorders, Ec as sameDatabase, wr as sanitizeIdentifierFragment, Wt as serializeArraysForWrite, De as serverOnlyColumns, As as setResidencyConfig, ze as setSchemaChangeSeedHook, He as setTenantCreateSeedHook, Fo as settleTransactionExit, Uo as settleVersionedUpdate, da as spatialPredicate, sc as stampGeneratedId, cc as stampGeneratedIds, ia as startsWith, es as streamTable, ge as sum, wt as sumOver, so as suspendWriteRecorders, co as suspendWriteRecordersEffect, Pc as sweepRetention, w as table, xs as teardownBranch, S as text, y as timestamp, Et as timestampMs, Dt as timestampMsOrNull, i as union, Ce as unionAll, Oe as unregisterTable, io as unregisterWriteRecorder, _c as updateManyRow, gc as upsertRow, qe as validateColumnName, Ge as validateIndexName, Un as validateRegisteredRelations, Fn as validateRelationConfig, Me as validateTableName, _t as validateTypeIdPrefix, t as vector, lt as vectorDistanceToOpclass, rs as vectorEmbedding, Vo as versionColumnOf, We as view, je as viewSql, Ta as walkLeaves, Fa as withCapturedAttribution, lo as writeRecordersSuspended };