@voltro/database 0.75.0 → 0.77.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.
@@ -20,11 +20,11 @@ var o = (e) => {
20
20
  });
21
21
  }
22
22
  return t;
23
- }, ee = (e) => {
23
+ }, l = (e) => {
24
24
  let t = [];
25
25
  for (let [n, r] of Object.entries(e.fields)) r.crdtManaged === !0 && t.push(n);
26
26
  return t;
27
- }, l = class e {
27
+ }, u = class e {
28
28
  definition;
29
29
  constructor(e) {
30
30
  this.definition = e;
@@ -185,14 +185,14 @@ var o = (e) => {
185
185
  __definition() {
186
186
  return this.definition;
187
187
  }
188
- }, u = (e) => new l({
188
+ }, d = (e) => new u({
189
189
  type: e,
190
190
  nullable: !1,
191
191
  unique: !1,
192
192
  hasDefault: !1
193
193
  });
194
- function d(e) {
195
- return new l({
194
+ function f(e) {
195
+ return new u({
196
196
  type: "id",
197
197
  nullable: !1,
198
198
  unique: !0,
@@ -200,10 +200,10 @@ function d(e) {
200
200
  idSchemeInput: e
201
201
  });
202
202
  }
203
- var f = () => u("text"), p = () => u("integer"), te = () => u("real"), ne = (e, t = 0) => {
203
+ var p = () => d("text"), m = () => d("integer"), h = () => d("real"), g = (e, t = 0) => {
204
204
  if (!Number.isInteger(e) || e <= 0) throw Error(`decimal(${String(e)}, ${String(t)}): precision must be a positive integer (the total number of significant digits, e.g. decimal(12, 2)).`);
205
205
  if (!Number.isInteger(t) || t < 0 || t > e) throw Error(`decimal(${String(e)}, ${String(t)}): scale must be an integer between 0 and precision (${e}).`);
206
- return new l({
206
+ return new u({
207
207
  type: "decimal",
208
208
  nullable: !1,
209
209
  unique: !1,
@@ -211,12 +211,12 @@ var f = () => u("text"), p = () => u("integer"), te = () => u("real"), ne = (e,
211
211
  precision: e,
212
212
  scale: t
213
213
  });
214
- }, re = ne, ie = () => u("bigint"), ae = (e, t) => {
214
+ }, ee = g, te = () => d("bigint"), ne = (e, t) => {
215
215
  if (t.length === 0) throw Error(`dbEnum('${e}', []): enum must have at least one value`);
216
216
  return {
217
217
  name: e,
218
218
  values: t,
219
- column: () => new l({
219
+ column: () => new u({
220
220
  type: "enum",
221
221
  nullable: !1,
222
222
  unique: !1,
@@ -225,26 +225,26 @@ var f = () => u("text"), p = () => u("integer"), te = () => u("real"), ne = (e,
225
225
  enumValues: t
226
226
  })
227
227
  };
228
- }, oe = () => u("boolean"), m = () => u("timestamp"), se = () => u("date"), h = () => u("json"), ce = () => u("bytes"), le = () => new l({
228
+ }, _ = () => d("boolean"), v = () => d("timestamp"), re = () => d("date"), y = () => d("json"), b = () => d("bytes"), x = () => new u({
229
229
  type: "bytes",
230
230
  nullable: !0,
231
231
  unique: !1,
232
232
  hasDefault: !1,
233
233
  crdtManaged: !0
234
- }), ue = () => new l({
234
+ }), ie = () => new u({
235
235
  type: "bytes",
236
236
  nullable: !0,
237
237
  unique: !1,
238
238
  hasDefault: !1,
239
239
  crdtManaged: !0
240
- }), g = () => {
240
+ }), S = () => {
241
241
  throw Error("selfReference(): the target is resolved by table() — a column built with selfReference() must be declared inside a table({ … }) literal, not read before the table exists");
242
242
  };
243
- function de(e) {
244
- return fe(g, e);
243
+ function ae(e) {
244
+ return oe(S, e);
245
245
  }
246
- function fe(e, t) {
247
- return new l({
246
+ function oe(e, t) {
247
+ return new u({
248
248
  type: "reference",
249
249
  nullable: !1,
250
250
  unique: !1,
@@ -259,15 +259,15 @@ function fe(e, t) {
259
259
  ...t?.orphanPolicy ? { orphanPolicy: t.orphanPolicy } : {}
260
260
  });
261
261
  }
262
- var pe = () => new l({
262
+ var se = () => new u({
263
263
  type: "text",
264
264
  nullable: !0,
265
265
  unique: !1,
266
266
  hasDefault: !1,
267
267
  dropped: !0
268
- }), me = (e, t) => {
268
+ }), ce = (e, t) => {
269
269
  if (!Number.isInteger(e) || e <= 0) throw Error(`vector(${String(e)}): dimension must be a positive integer (the embedding length, e.g. vector(1536)).`);
270
- return new l({
270
+ return new u({
271
271
  type: "vector",
272
272
  nullable: !1,
273
273
  unique: !1,
@@ -275,13 +275,13 @@ var pe = () => new l({
275
275
  vectorDim: e,
276
276
  vectorPrecision: t?.precision ?? "float32"
277
277
  });
278
- }, he = (e) => new l({
278
+ }, le = (e) => new u({
279
279
  type: "array",
280
280
  nullable: !1,
281
281
  unique: !1,
282
282
  hasDefault: !1,
283
283
  arrayElement: e.__definition().type
284
- }), ge = () => u("interval"), _e = (e, t = 4326) => new l({
284
+ }), ue = () => d("interval"), de = (e, t = 4326) => new u({
285
285
  type: "text",
286
286
  nullable: !1,
287
287
  unique: !1,
@@ -291,7 +291,7 @@ var pe = () => new l({
291
291
  geomKind: e,
292
292
  srid: t
293
293
  }
294
- }), ve = (e, t = 4326) => new l({
294
+ }), fe = (e, t = 4326) => new u({
295
295
  type: "text",
296
296
  nullable: !1,
297
297
  unique: !1,
@@ -301,163 +301,182 @@ var pe = () => new l({
301
301
  geomKind: e,
302
302
  srid: t
303
303
  }
304
- }), ye = (e) => new l({
304
+ }), pe = (e) => new u({
305
305
  type: "raw",
306
306
  nullable: !1,
307
307
  unique: !1,
308
308
  hasDefault: !1,
309
309
  rawDdl: e
310
- }), _ = (e) => {
310
+ }), C = (e) => {
311
311
  let t = {};
312
312
  for (let [n, r] of Object.entries(e)) t[n] = r.__definition();
313
313
  return t;
314
- }, be = /* @__PURE__ */ new WeakMap(), xe = (e) => typeof e == "object" && e ? be.get(e) : void 0, Se = (e, t = {}) => {
315
- let n = f();
316
- return be.set(n, {
314
+ }, me = /* @__PURE__ */ new WeakMap(), he = (e) => typeof e == "object" && e ? me.get(e) : void 0, ge = (e, t = {}) => {
315
+ let n = p();
316
+ return me.set(n, {
317
317
  target: e,
318
318
  orphanPolicy: t.orphanPolicy ?? "keep",
319
319
  onSoftDelete: t.onSoftDelete ?? !1
320
320
  }), n;
321
- }, v = /* @__PURE__ */ new Map(), Ce = (e, t) => {
321
+ }, w = /* @__PURE__ */ new Map(), _e = (e, t) => {
322
322
  if (t.from === t.to) throw Error(`declareEnumRename('${e}'): \`from\` and \`to\` are both '${t.from}' — a rename must change the value.`);
323
- let n = v.get(e) ?? [];
323
+ let n = w.get(e) ?? [];
324
324
  for (let r of n) {
325
325
  if (r.from === t.from && r.to === t.to) return;
326
326
  if (r.from === t.from && r.to !== t.to) throw Error(`declareEnumRename('${e}'): value '${t.from}' is already declared as renamed to '${r.to}', cannot also rename it to '${t.to}'.`);
327
327
  }
328
- n.push(t), v.set(e, n);
329
- }, we = (e) => v.get(e) ?? [], Te = () => v, Ee = () => {
330
- v.clear();
331
- }, De = (t) => {
328
+ n.push(t), w.set(e, n);
329
+ }, ve = (e) => w.get(e) ?? [], ye = () => w, be = () => {
330
+ w.clear();
331
+ }, xe = (t) => {
332
332
  let r = t;
333
333
  for (let t = 0; t < 4 && n.isFiberFailure(r); t++) r = e.squash(r[n.FiberFailureCauseId]);
334
334
  return r;
335
- }, y = (t, r = 0) => {
335
+ }, T = (t, r = 0) => {
336
336
  if (r >= 4 || !n.isFiberFailure(t)) return [t];
337
337
  let i = t[n.FiberFailureCauseId], a = [...e.failures(i), ...e.defects(i)];
338
338
  if (a.length === 0) return [e.squash(i)];
339
339
  let o = [];
340
- for (let e of a.slice(0, 8)) o.push(...y(e, r + 1));
340
+ for (let e of a.slice(0, 8)) o.push(...T(e, r + 1));
341
341
  return o;
342
- }, Oe = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, ke = (e) => {
343
- let t = {}, n = [], r = De(e);
342
+ }, Se = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, Ce = (e) => {
343
+ let t = {}, n = [], r = xe(e);
344
344
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
345
345
  let e = r;
346
346
  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);
347
347
  let i = e.sqlMessage ?? e.detail;
348
348
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
349
349
  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;
350
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = De(e.cause);
350
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = xe(e.cause);
351
351
  }
352
352
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
353
- }, b = (e) => {
354
- let t = y(e).map(ke);
353
+ }, we = (e) => {
354
+ let t = T(e).map(Ce);
355
355
  if (t.length <= 1) return t[0] ?? {};
356
- let n = t.find(Oe) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
356
+ let n = t.find(Se) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
357
357
  if (r.length === 0) return n;
358
358
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
359
359
  return {
360
360
  ...n,
361
361
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
362
362
  };
363
- }, Ae = (e, t) => {
364
- let n = b(e), r = w(n, t);
365
- if (r !== void 0) {
366
- let e = r.constraint ?? r.column;
367
- return e === void 0 ? r.kind : `${r.kind}: ${e}`;
368
- }
369
- let i = n.dbCode ?? n.dbSqlState ?? n.dbErrno ?? n.dbNumber, a = Ne(e);
370
- return i !== void 0 && je.test(String(i)) ? `${a} (${String(i)})` : a;
371
- }, je = /^[A-Za-z0-9_]{1,32}$/, Me = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, Ne = (e) => {
363
+ }, Te = (e, t) => {
364
+ let n = De(e);
365
+ if (n !== void 0) return n;
366
+ let r = we(e), i = Ne(r, t);
367
+ if (i !== void 0) {
368
+ let e = i.constraint ?? i.column;
369
+ return e === void 0 ? i.kind : `${i.kind}: ${e}`;
370
+ }
371
+ let a = r.dbCode ?? r.dbSqlState ?? r.dbErrno ?? r.dbNumber, o = Ae(e);
372
+ return a !== void 0 && Oe.test(String(a)) ? `${o} (${String(a)})` : o;
373
+ }, Ee = Symbol.for("@voltro/database/authoredMessage"), E = (e, t) => {
374
+ let n = t === void 0 ? Error(e) : Error(e, t);
375
+ return Object.defineProperty(n, Ee, {
376
+ value: !0,
377
+ enumerable: !1
378
+ }), n;
379
+ }, De = (e) => {
380
+ for (let t of T(e)) {
381
+ let e = t;
382
+ for (let t = 0; typeof e == "object" && e && t < 8; t += 1) {
383
+ if (e[Ee] === !0) {
384
+ let t = e.message;
385
+ if (typeof t == "string" && t.length > 0) return t;
386
+ }
387
+ e = e.cause;
388
+ }
389
+ }
390
+ }, Oe = /^[A-Za-z0-9_]{1,32}$/, ke = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, Ae = (e) => {
372
391
  let t = e?._tag, n = e?.name, r = (typeof t == "string" ? t : typeof n == "string" ? n : "").split(/[^A-Za-z0-9_]+/).filter(Boolean).pop();
373
- return r !== void 0 && Me.test(r) ? r : "unknown";
374
- }, Pe = /^[A-Za-z_][A-Za-z0-9_$]*$/, x = (e) => e !== void 0 && e.length <= 128 && Pe.test(e) ? e : void 0, S = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, C = (e, ...t) => {
392
+ return r !== void 0 && ke.test(r) ? r : "unknown";
393
+ }, je = /^[A-Za-z_][A-Za-z0-9_$]*$/, D = (e) => e !== void 0 && e.length <= 128 && je.test(e) ? e : void 0, Me = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, O = (e, ...t) => {
375
394
  for (let n of t) {
376
395
  let t = n.exec(e);
377
396
  if (t?.[1] !== void 0) return t[1];
378
397
  }
379
- }, w = (e, t) => {
398
+ }, Ne = (e, t) => {
380
399
  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}`;
381
400
  if (n === "23503") {
382
- let t = x(e.dbConstraint);
401
+ let t = D(e.dbConstraint);
383
402
  return {
384
403
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
385
404
  ...t === void 0 ? {} : { constraint: t }
386
405
  };
387
406
  }
388
407
  if (n === "23505") {
389
- let t = x(e.dbConstraint);
408
+ let t = D(e.dbConstraint);
390
409
  return {
391
410
  kind: "unique",
392
411
  ...t === void 0 ? {} : { constraint: t }
393
412
  };
394
413
  }
395
414
  if (n === "23502") {
396
- let t = x(e.dbColumn);
415
+ let t = D(e.dbColumn);
397
416
  return {
398
417
  kind: "notNull",
399
418
  ...t === void 0 ? {} : { column: t }
400
419
  };
401
420
  }
402
421
  if (n === "23514") {
403
- let t = x(e.dbConstraint);
422
+ let t = D(e.dbConstraint);
404
423
  return {
405
424
  kind: "check",
406
425
  ...t === void 0 ? {} : { constraint: t }
407
426
  };
408
427
  }
409
428
  if (r === 1452 || r === 1451) {
410
- let e = x(C(o, /CONSTRAINT `([^`]+)`/));
429
+ let e = D(O(o, /CONSTRAINT `([^`]+)`/));
411
430
  return {
412
431
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
413
432
  ...e === void 0 ? {} : { constraint: e }
414
433
  };
415
434
  }
416
435
  if (r === 1062) {
417
- let e = x(S(C(o, /for key '([^']+)'/)));
436
+ let e = D(Me(O(o, /for key '([^']+)'/)));
418
437
  return {
419
438
  kind: "unique",
420
439
  ...e === void 0 ? {} : { constraint: e }
421
440
  };
422
441
  }
423
442
  if (r === 1048 || r === 1364) {
424
- let e = x(C(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
443
+ let e = D(O(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
425
444
  return {
426
445
  kind: "notNull",
427
446
  ...e === void 0 ? {} : { column: e }
428
447
  };
429
448
  }
430
449
  if (r === 3819 || r === 4025) {
431
- let e = x(C(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
450
+ let e = D(O(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
432
451
  return {
433
452
  kind: "check",
434
453
  ...e === void 0 ? {} : { constraint: e }
435
454
  };
436
455
  }
437
456
  if (i === 547) {
438
- let e = C(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = C(o, /CHECK constraint "([^"]+)"/);
457
+ let e = O(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = O(o, /CHECK constraint "([^"]+)"/);
439
458
  if (t !== void 0 && e === void 0) {
440
- let e = x(t);
459
+ let e = D(t);
441
460
  return {
442
461
  kind: "check",
443
462
  ...e === void 0 ? {} : { constraint: e }
444
463
  };
445
464
  }
446
- let n = /REFERENCE constraint/.test(o), r = x(e);
465
+ let n = /REFERENCE constraint/.test(o), r = D(e);
447
466
  return {
448
467
  kind: n ? "foreignKeyInUse" : "foreignKey",
449
468
  ...r === void 0 ? {} : { constraint: r }
450
469
  };
451
470
  }
452
471
  if (i === 2627 || i === 2601) {
453
- let e = x(C(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
472
+ let e = D(O(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
454
473
  return {
455
474
  kind: "unique",
456
475
  ...e === void 0 ? {} : { constraint: e }
457
476
  };
458
477
  }
459
478
  if (i === 515) {
460
- let e = x(C(o, /Cannot insert the value NULL into column '([^']+)'/));
479
+ let e = D(O(o, /Cannot insert the value NULL into column '([^']+)'/));
461
480
  return {
462
481
  kind: "notNull",
463
482
  ...e === void 0 ? {} : { column: e }
@@ -465,34 +484,34 @@ var pe = () => new l({
465
484
  }
466
485
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
467
486
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
468
- let e = x(S(C(o, /UNIQUE constraint failed: ([^,\s]+)/)));
487
+ let e = D(Me(O(o, /UNIQUE constraint failed: ([^,\s]+)/)));
469
488
  return {
470
489
  kind: "unique",
471
490
  ...e === void 0 ? {} : { column: e }
472
491
  };
473
492
  }
474
493
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
475
- let e = x(S(C(o, /NOT NULL constraint failed: ([^,\s]+)/)));
494
+ let e = D(Me(O(o, /NOT NULL constraint failed: ([^,\s]+)/)));
476
495
  return {
477
496
  kind: "notNull",
478
497
  ...e === void 0 ? {} : { column: e }
479
498
  };
480
499
  }
481
500
  if (n === "SQLITE_CONSTRAINT_CHECK") {
482
- let e = x(C(a, /CHECK constraint failed: (.+)$/));
501
+ let e = D(O(a, /CHECK constraint failed: (.+)$/));
483
502
  return {
484
503
  kind: "check",
485
504
  ...e === void 0 ? {} : { constraint: e }
486
505
  };
487
506
  }
488
- }, Fe = (e) => {
489
- let t = w(e)?.kind;
507
+ }, Pe = (e) => {
508
+ let t = Ne(e)?.kind;
490
509
  return t === "foreignKey" || t === "foreignKeyInUse";
491
- }, Ie = (e) => {
510
+ }, Fe = (e) => {
492
511
  let t = e.dbCode, n = e.dbErrno;
493
512
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
494
- }, Le = (e) => {
495
- let t = b(e), n = [
513
+ }, Ie = (e) => {
514
+ let t = we(e), n = [
496
515
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
497
516
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
498
517
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
@@ -501,7 +520,7 @@ var pe = () => new l({
501
520
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
502
521
  ].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)}…`}` : "";
503
522
  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;
504
- }, Re = (e) => Object.entries(e).map(([e, t]) => `${e}:${ze(t)}`).join(" "), ze = (e) => {
523
+ }, Le = (e) => Object.entries(e).map(([e, t]) => `${e}:${Re(t)}`).join(" "), Re = (e) => {
505
524
  if (e === null) return "null";
506
525
  if (e === void 0) return "undefined";
507
526
  if (typeof e == "bigint") return "bigint";
@@ -511,24 +530,24 @@ var pe = () => new l({
511
530
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
512
531
  let t = e.constructor?.name;
513
532
  return typeof t == "string" && t !== "" ? t : "Object";
514
- }, Be = 63, Ve = 60, T = [], E = (e) => {
515
- T.includes(e) || T.push(e);
516
- }, He = () => {
517
- let e = T.slice();
518
- return T.length = 0, e;
519
- }, Ue = /^[a-zA-Z_][a-zA-Z0-9_]*$/, D = (e, t) => {
533
+ }, ze = 63, Be = 60, k = [], A = (e) => {
534
+ k.includes(e) || k.push(e);
535
+ }, Ve = () => {
536
+ let e = k.slice();
537
+ return k.length = 0, e;
538
+ }, He = /^[a-zA-Z_][a-zA-Z0-9_]*$/, Ue = (e, t) => {
520
539
  if (t.length === 0) throw Error(`${e} cannot be empty.`);
521
- if (!Ue.test(t)) throw Error(`${e} '${t}' contains characters outside [A-Za-z0-9_] or starts with a digit. Dialect-portable identifiers must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);
522
- }, O = (e) => {
523
- if (D("table name", e), e.length > 63) throw Error(`table name '${e}' is ${e.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Shorten the name; long table names also cascade into auto-named indexes and FK constraints that would themselves exceed the limit.`);
524
- e.length > 60 && E(`table name '${e}' is ${e.length} chars — ${63 - e.length} from the Postgres 63-byte limit. Auto-named indexes on this table will run out of room fast.`);
525
- }, k = (e, t) => {
526
- if (D("column name", t), t.length > 63) throw Error(`column '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Rename it.`);
527
- t.length > 60 && E(`column '${t}' on table '${e}' is ${t.length} chars — close to the 63-byte limit.`);
528
- }, A = (e, t, n, r) => {
529
- if (D("index name", t), t.length > 63) throw Error(n ? `auto-named index '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Supply an explicit short name: .index('<shortName>', ${JSON.stringify([...r])}).` : `index name '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Shorten it.`);
530
- t.length > 60 && E(`index '${t}' on table '${e}' is ${t.length} chars — ${63 - t.length} from the 63-byte limit. ${n ? `Consider .index('<shortName>', ${JSON.stringify([...r])}) before it grows.` : ""}`);
531
- }, j = (e, t) => {
540
+ if (!He.test(t)) throw Error(`${e} '${t}' contains characters outside [A-Za-z0-9_] or starts with a digit. Dialect-portable identifiers must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);
541
+ }, j = (e) => {
542
+ if (Ue("table name", e), e.length > 63) throw Error(`table name '${e}' is ${e.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Shorten the name; long table names also cascade into auto-named indexes and FK constraints that would themselves exceed the limit.`);
543
+ e.length > 60 && A(`table name '${e}' is ${e.length} chars — ${63 - e.length} from the Postgres 63-byte limit. Auto-named indexes on this table will run out of room fast.`);
544
+ }, M = (e, t) => {
545
+ if (Ue("column name", t), t.length > 63) throw Error(`column '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Rename it.`);
546
+ t.length > 60 && A(`column '${t}' on table '${e}' is ${t.length} chars — close to the 63-byte limit.`);
547
+ }, N = (e, t, n, r) => {
548
+ if (Ue("index name", t), t.length > 63) throw Error(n ? `auto-named index '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Supply an explicit short name: .index('<shortName>', ${JSON.stringify([...r])}).` : `index name '${t}' on table '${e}' is ${t.length} chars — exceeds the 63-byte cross-dialect limit (Postgres floor). Shorten it.`);
549
+ t.length > 60 && A(`index '${t}' on table '${e}' is ${t.length} chars — ${63 - t.length} from the 63-byte limit. ${n ? `Consider .index('<shortName>', ${JSON.stringify([...r])}) before it grows.` : ""}`);
550
+ }, P = (e, t) => {
532
551
  if (e.length === 0) throw Error(`typeid prefix on table '${t.tableName}' cannot be empty.`);
533
552
  if (!/^[a-z][a-z0-9_]*$/.test(e)) {
534
553
  let n = t.kind === "derived" ? "the derived prefix doesn't match typeid's required shape — supply an explicit one via id({ prefix: '...' })." : "the prefix must match typeid's required shape /^[a-z][a-z0-9_]*$/.";
@@ -538,7 +557,7 @@ var pe = () => new l({
538
557
  let n = t.kind === "derived" ? "shorten the table name, or supply an explicit short prefix via id({ prefix: '...' })." : "pick a shorter prefix.";
539
558
  throw Error(`typeid prefix '${e}' on table '${t.tableName}' is ${e.length} chars — exceeds the 63-byte limit; ${n}`);
540
559
  }
541
- e.length > 60 && E(`typeid prefix '${e}' on table '${t.tableName}' is ${e.length} chars — close to the 63-byte limit. Generated ids will be even longer (prefix + '_' + 26).`);
560
+ e.length > 60 && A(`typeid prefix '${e}' on table '${t.tableName}' is ${e.length} chars — close to the 63-byte limit. Generated ids will be even longer (prefix + '_' + 26).`);
542
561
  }, We = 1704067200000n, Ge = 10n, Ke = 12n, qe = (1n << Ge) - 1n, Je = (1n << Ke) - 1n, Ye = Ke, Xe = 22n, Ze = () => {
543
562
  let e = process.env.SNOWFLAKE_MACHINE_ID;
544
563
  if (e === void 0 || e === "") return 0n;
@@ -549,33 +568,33 @@ var pe = () => new l({
549
568
  lastMs: 0n,
550
569
  sequence: 0n,
551
570
  machineId: Ze()
552
- }), M, $e = () => (M === void 0 && (M = Qe()), M), et = () => {
553
- M = Qe();
554
- }, N = () => BigInt(Date.now()), tt = (e) => {
555
- let t = N();
556
- for (; t <= e;) t = N();
571
+ }), F, $e = () => (F === void 0 && (F = Qe()), F), et = () => {
572
+ F = Qe();
573
+ }, tt = () => BigInt(Date.now()), nt = (e) => {
574
+ let t = tt();
575
+ for (; t <= e;) t = tt();
557
576
  return t;
558
- }, nt = () => {
559
- let e = $e(), t = N();
560
- t === e.lastMs ? (e.sequence = e.sequence + 1n & Je, e.sequence === 0n && (t = tt(e.lastMs), e.lastMs = t)) : (e.sequence = 0n, e.lastMs = t);
577
+ }, rt = () => {
578
+ let e = $e(), t = tt();
579
+ t === e.lastMs ? (e.sequence = e.sequence + 1n & Je, e.sequence === 0n && (t = nt(e.lastMs), e.lastMs = t)) : (e.sequence = 0n, e.lastMs = t);
561
580
  let n = t - We;
562
581
  if (n < 0n) throw Error("Snowflake timestamp before configured epoch (2024-01-01). System clock is wrong.");
563
582
  return (n << Xe | e.machineId << Ye | e.sequence).toString();
564
- }, P = (e) => {
583
+ }, it = (e) => {
565
584
  let t = e.toLowerCase();
566
585
  if (t.startsWith("_")) throw Error(`cannot derive a typeid prefix for table '${e}' (table names starting with '_' are not valid typeid prefixes). Pick an explicit prefix via id({ prefix: '...' }) or use a different scheme like id({ scheme: 'numeric' }) for internal tables.`);
567
586
  if (!/^[a-z][a-z0-9_]*$/.test(t)) throw Error(`cannot derive a typeid prefix from table name '${e}' (must match [a-z][a-z0-9_]*). Pick an explicit prefix via id({ prefix: '...' }).`);
568
587
  let n = t.endsWith("ies") && t.length > 3 ? t.slice(0, -3) + "y" : t.endsWith("ses") || t.endsWith("xes") || t.endsWith("zes") || t.endsWith("shes") || t.endsWith("ches") ? t.slice(0, -2) : t.endsWith("s") && t.length > 1 ? t.slice(0, -1) : t;
569
- return j(n, {
588
+ return P(n, {
570
589
  kind: "derived",
571
590
  tableName: e
572
591
  }), n;
573
- }, rt = (e, t) => {
592
+ }, at = (e, t) => {
574
593
  if (e === void 0) return {
575
594
  kind: "typeid",
576
- prefix: P(t)
595
+ prefix: it(t)
577
596
  };
578
- if ("prefix" in e && !("scheme" in e)) return j(e.prefix, {
597
+ if ("prefix" in e && !("scheme" in e)) return P(e.prefix, {
579
598
  kind: "explicit",
580
599
  tableName: t
581
600
  }), {
@@ -585,8 +604,8 @@ var pe = () => new l({
585
604
  if (!("scheme" in e)) throw Error("invalid id() options: no scheme or prefix");
586
605
  switch (e.scheme) {
587
606
  case "typeid": {
588
- let n = e.prefix ?? P(t);
589
- return e.prefix !== void 0 && j(e.prefix, {
607
+ let n = e.prefix ?? it(t);
608
+ return e.prefix !== void 0 && P(e.prefix, {
590
609
  kind: "explicit",
591
610
  tableName: t
592
611
  }), {
@@ -602,22 +621,22 @@ var pe = () => new l({
602
621
  generate: e.generate
603
622
  };
604
623
  }
605
- }, it = (e, t) => {
624
+ }, ot = (e, t) => {
606
625
  switch (e.kind) {
607
626
  case "typeid": return i(e.prefix).toString();
608
627
  case "ulid": return a();
609
628
  case "numeric": return null;
610
- case "snowflake": return nt();
629
+ case "snowflake": return rt();
611
630
  case "custom": return e.generate(t);
612
631
  }
613
- }, at = (e) => ({
614
- fields: _(e.fields),
632
+ }, st = (e) => ({
633
+ fields: C(e.fields),
615
634
  ...e.id === void 0 ? {} : { id: e.id },
616
635
  ...e.requires === void 0 ? {} : { requires: e.requires },
617
636
  ...e.indexes === void 0 ? {} : { indexes: e.indexes },
618
637
  ...e.behaviors === void 0 ? {} : { behaviors: e.behaviors },
619
638
  ...e.policies === void 0 ? {} : { policies: e.policies }
620
- }), ot = at, st = (e) => {
639
+ }), ct = st, lt = (e) => {
621
640
  let t = /* @__PURE__ */ new Set(), n = [], r = (e) => {
622
641
  let i = e.id ?? e;
623
642
  if (!t.has(i)) {
@@ -627,7 +646,7 @@ var pe = () => new l({
627
646
  };
628
647
  for (let t of e) r(t);
629
648
  return n;
630
- }, ct = (e, ...t) => {
649
+ }, ut = (e, ...t) => {
631
650
  if (t.length === 0) throw Error(`jsonIndex("${e}"): at least one path segment is required`);
632
651
  let n = (r) => ({
633
652
  jsonPath: {
@@ -638,14 +657,14 @@ var pe = () => new l({
638
657
  numeric: () => n(!0)
639
658
  });
640
659
  return n(!1);
641
- }, lt = (e = "cosine", t = "float32") => {
660
+ }, dt = (e = "cosine", t = "float32") => {
642
661
  let n = t === "half" ? "halfvec" : "vector";
643
662
  switch (e) {
644
663
  case "cosine": return `${n}_cosine_ops`;
645
664
  case "l2": return `${n}_l2_ops`;
646
665
  case "inner": return `${n}_ip_ops`;
647
666
  }
648
- }, ut = [
667
+ }, ft = [
649
668
  "id",
650
669
  "tenantId",
651
670
  "createdAt",
@@ -654,7 +673,7 @@ var pe = () => new l({
654
673
  "updatedBy",
655
674
  "deletedAt",
656
675
  "deletedBy"
657
- ], dt = (e) => e.id ?? `<anonymous mixin: ${Object.keys(e.fields).join(", ")}>`, F = (e, t) => `${e}_${t.join("_")}_idx`, ft = (e, t) => `${e}_${t.join("_")}_uq`, I = (e, t, n, r, i) => {
676
+ ], pt = (e) => e.id ?? `<anonymous mixin: ${Object.keys(e.fields).join(", ")}>`, mt = (e, t) => `${e}_${t.join("_")}_idx`, ht = (e, t) => `${e}_${t.join("_")}_uq`, gt = (e, t, n, r, i) => {
658
677
  if (n !== "hnsw") return;
659
678
  if (r.length !== 1) throw Error(`hnsw index '${t}' on table '${e}' must cover exactly one vector column — got ${r.length} fields. pgvector's HNSW access method indexes a single vector column.`);
660
679
  let a = r[0];
@@ -662,14 +681,14 @@ var pe = () => new l({
662
681
  let o = i[a];
663
682
  if (o === void 0) throw Error(`hnsw index '${t}' on table '${e}' references unknown column '${a}'.`);
664
683
  if (o.type !== "vector") throw Error(`hnsw index '${t}' on table '${e}' requires a vector() column — column '${a}' is '${o.type}'. HNSW is the pgvector approximate-nearest-neighbour method and only applies to vectors.`);
665
- }, pt = (e, t) => {
684
+ }, _t = (e, t) => {
666
685
  let n;
667
686
  for (let [r, i] of Object.entries(e)) i.type === "id" && i.idScheme === void 0 && (n === void 0 && (n = { ...e }), n[r] = {
668
687
  ...i,
669
- idScheme: rt(i.idSchemeInput, t)
688
+ idScheme: at(i.idSchemeInput, t)
670
689
  });
671
690
  return n ?? e;
672
- }, L = (e) => {
691
+ }, I = (e) => {
673
692
  let t = e.appliedPrimaryKey ?? [];
674
693
  return {
675
694
  tableName: e.tableName,
@@ -688,8 +707,8 @@ var pe = () => new l({
688
707
  ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema },
689
708
  fullTextIndex: ((t, n, r) => {
690
709
  if (n.length === 0) throw Error(`fullTextIndex '${t}' on '${e.tableName}' has no columns.`);
691
- if (A(e.tableName, t, !1, n), e.appliedFullText.some((e) => e.name === t)) throw Error(`duplicate full-text index '${t}' on table '${e.tableName}'.`);
692
- return L({
710
+ if (N(e.tableName, t, !1, n), e.appliedFullText.some((e) => e.name === t)) throw Error(`duplicate full-text index '${t}' on table '${e.tableName}'.`);
711
+ return I({
693
712
  ...e,
694
713
  tableName: e.tableName,
695
714
  fields: e.fields,
@@ -710,27 +729,27 @@ var pe = () => new l({
710
729
  });
711
730
  }),
712
731
  with: ((...t) => {
713
- let n = st(t), r = { ...e.fields }, i = /* @__PURE__ */ new Map();
732
+ let n = lt(t), r = { ...e.fields }, i = /* @__PURE__ */ new Map();
714
733
  for (let e of Object.keys(r)) i.set(e, {
715
734
  id: "<table>",
716
735
  fields: {}
717
736
  });
718
737
  for (let t of n) for (let [n, a] of Object.entries(t.fields)) {
719
738
  let o = i.get(n);
720
- if (o !== void 0) throw Error(`mixin collision on column '${n}' in table '${e.tableName}': '${dt(o)}' and '${dt(t)}' both define it. If they're the same mixin reached via different paths, set a shared 'id' on both. If they're genuinely different concerns, rename one of the columns.`);
721
- k(e.tableName, n), r[n] = a, i.set(n, t);
739
+ if (o !== void 0) throw Error(`mixin collision on column '${n}' in table '${e.tableName}': '${pt(o)}' and '${pt(t)}' both define it. If they're the same mixin reached via different paths, set a shared 'id' on both. If they're genuinely different concerns, rename one of the columns.`);
740
+ M(e.tableName, n), r[n] = a, i.set(n, t);
722
741
  }
723
742
  let a = [...e.appliedIndexes];
724
743
  for (let t of n) for (let n of t.indexes ?? []) {
725
- let t = n.name ?? F(e.tableName, n.fields);
726
- a.some((e) => e.name === t) || (A(e.tableName, t, n.name === void 0, n.fields), I(e.tableName, t, n.kind, n.fields, r), a.push({
744
+ let t = n.name ?? mt(e.tableName, n.fields);
745
+ a.some((e) => e.name === t) || (N(e.tableName, t, n.name === void 0, n.fields), gt(e.tableName, t, n.kind, n.fields, r), a.push({
727
746
  name: t,
728
747
  fields: n.fields,
729
748
  ...n.kind === void 0 ? {} : { kind: n.kind },
730
749
  ...n.kindOptions === void 0 ? {} : { kindOptions: n.kindOptions }
731
750
  }));
732
751
  }
733
- return L({
752
+ return I({
734
753
  ...e,
735
754
  tableName: e.tableName,
736
755
  fields: r,
@@ -747,10 +766,10 @@ var pe = () => new l({
747
766
  }),
748
767
  index: ((...t) => {
749
768
  let n, r, i, a = Array.isArray(t[0]);
750
- if (a ? (r = t[0], i = t[1], n = F(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`index '${n}' on table '${e.tableName}' has no fields — an index must cover at least one column.`);
769
+ if (a ? (r = t[0], i = t[1], n = mt(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`index '${n}' on table '${e.tableName}' has no fields — an index must cover at least one column.`);
751
770
  let o = r.filter((e) => typeof e == "string");
752
- if (A(e.tableName, n, a, o), I(e.tableName, n, i?.kind, r, e.fields), e.appliedIndexes.some((e) => e.name === n)) throw t.length === 1 ? Error(`duplicate auto-named index '${n}' on table '${e.tableName}' — you've called .index(${JSON.stringify(r)}) twice. Pass an explicit name to the second one if both are intended (rare).`) : Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table.`);
753
- return L({
771
+ if (N(e.tableName, n, a, o), gt(e.tableName, n, i?.kind, r, e.fields), e.appliedIndexes.some((e) => e.name === n)) throw t.length === 1 ? Error(`duplicate auto-named index '${n}' on table '${e.tableName}' — you've called .index(${JSON.stringify(r)}) twice. Pass an explicit name to the second one if both are intended (rare).`) : Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table.`);
772
+ return I({
754
773
  ...e,
755
774
  tableName: e.tableName,
756
775
  fields: e.fields,
@@ -774,8 +793,8 @@ var pe = () => new l({
774
793
  expressionIndex: ((t, n, r) => {
775
794
  if (n.length === 0) throw Error(`expressionIndex '${t}' on table '${e.tableName}' has no fields — an index must cover at least one column or expression.`);
776
795
  let i = n.filter((e) => typeof e == "string");
777
- if (A(e.tableName, t, !1, i), I(e.tableName, t, r?.kind, n, e.fields), e.appliedIndexes.some((e) => e.name === t)) throw Error(`duplicate index '${t}' on table '${e.tableName}': each index name must be unique within a table.`);
778
- return L({
796
+ if (N(e.tableName, t, !1, i), gt(e.tableName, t, r?.kind, n, e.fields), e.appliedIndexes.some((e) => e.name === t)) throw Error(`duplicate index '${t}' on table '${e.tableName}': each index name must be unique within a table.`);
797
+ return I({
779
798
  ...e,
780
799
  tableName: e.tableName,
781
800
  fields: e.fields,
@@ -798,9 +817,9 @@ var pe = () => new l({
798
817
  }),
799
818
  unique: ((...t) => {
800
819
  let n, r, i, a = Array.isArray(t[0]);
801
- if (a ? (r = t[0], i = t[1], n = ft(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`unique '${n}' on table '${e.tableName}' has no fields — a UNIQUE constraint must cover at least one column.`);
802
- if (A(e.tableName, n, a, r), e.appliedUniques.some((e) => e.name === n)) throw Error(a ? `duplicate auto-named UNIQUE '${n}' on table '${e.tableName}' — you've called .unique(${JSON.stringify(r)}) twice. Pass an explicit name to the second one if both are intended (very rare).` : `duplicate UNIQUE '${n}' on table '${e.tableName}': each constraint name must be unique within a table.`);
803
- return L({
820
+ if (a ? (r = t[0], i = t[1], n = ht(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`unique '${n}' on table '${e.tableName}' has no fields — a UNIQUE constraint must cover at least one column.`);
821
+ if (N(e.tableName, n, a, r), e.appliedUniques.some((e) => e.name === n)) throw Error(a ? `duplicate auto-named UNIQUE '${n}' on table '${e.tableName}' — you've called .unique(${JSON.stringify(r)}) twice. Pass an explicit name to the second one if both are intended (very rare).` : `duplicate UNIQUE '${n}' on table '${e.tableName}': each constraint name must be unique within a table.`);
822
+ return I({
804
823
  ...e,
805
824
  tableName: e.tableName,
806
825
  fields: e.fields,
@@ -821,10 +840,10 @@ var pe = () => new l({
821
840
  }),
822
841
  uniqueActive: ((...t) => {
823
842
  let n, r, i, a = Array.isArray(t[0]);
824
- if (a ? (r = t[0], i = t[1], n = F(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`uniqueActive '${n}' on table '${e.tableName}' has no fields — a partial UNIQUE must cover at least one column.`);
825
- if (A(e.tableName, n, a, r), e.appliedIndexes.some((e) => e.name === n)) throw Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table (uniqueActive shares the index namespace).`);
843
+ if (a ? (r = t[0], i = t[1], n = mt(e.tableName, r)) : (n = t[0], r = t[1], i = t[2]), r.length === 0) throw Error(`uniqueActive '${n}' on table '${e.tableName}' has no fields — a partial UNIQUE must cover at least one column.`);
844
+ if (N(e.tableName, n, a, r), e.appliedIndexes.some((e) => e.name === n)) throw Error(`duplicate index '${n}' on table '${e.tableName}': each index name must be unique within a table (uniqueActive shares the index namespace).`);
826
845
  let o = i?.where ?? "\"deletedAt\" IS NULL";
827
- return L({
846
+ return I({
828
847
  ...e,
829
848
  tableName: e.tableName,
830
849
  fields: e.fields,
@@ -846,8 +865,8 @@ var pe = () => new l({
846
865
  }),
847
866
  check: ((t, n) => {
848
867
  if (n.trim().length === 0) throw Error(`CHECK '${t}' on table '${e.tableName}' has an empty expression.`);
849
- if (A(e.tableName, t, !1, []), e.appliedChecks.some((e) => e.name === t)) throw Error(`duplicate CHECK '${t}' on table '${e.tableName}': each constraint name must be unique within a table.`);
850
- return L({
868
+ if (N(e.tableName, t, !1, []), e.appliedChecks.some((e) => e.name === t)) throw Error(`duplicate CHECK '${t}' on table '${e.tableName}': each constraint name must be unique within a table.`);
869
+ return I({
851
870
  ...e,
852
871
  tableName: e.tableName,
853
872
  fields: e.fields,
@@ -869,7 +888,7 @@ var pe = () => new l({
869
888
  if (t.trim().length === 0) throw Error(`rule on table '${e.tableName}' has an empty name.`);
870
889
  let i = e.appliedRules ?? [];
871
890
  if (i.some((e) => e.name === t)) throw Error(`duplicate rule '${t}' on table '${e.tableName}': each rule name must be unique within a table.`);
872
- return L({
891
+ return I({
873
892
  ...e,
874
893
  appliedRules: [...i, {
875
894
  name: t,
@@ -880,7 +899,7 @@ var pe = () => new l({
880
899
  }),
881
900
  renamedFrom: ((t) => {
882
901
  if (t === e.tableName) throw Error(`renamedFrom('${t}') on table '${e.tableName}' names the table itself — drop the marker, there is nothing to rename.`);
883
- return O(t), L({
902
+ return j(t), I({
884
903
  ...e,
885
904
  previousTableName: t
886
905
  });
@@ -895,7 +914,7 @@ var pe = () => new l({
895
914
  }
896
915
  if (t.length > 0) throw Error(`primaryKey([...]) declared twice on table '${e.tableName}'.`);
897
916
  for (let [t, r] of Object.entries(e.fields)) if (r.type === "id" && !n.includes(t)) throw Error(`primaryKey([...]) on table '${e.tableName}' conflicts with the id() column '${t}'. The explicit primary key IS the key — drop the id() column, or include '${t}' in the composite key.`);
898
- return L({
917
+ return I({
899
918
  ...e,
900
919
  tableName: e.tableName,
901
920
  fields: e.fields,
@@ -910,7 +929,7 @@ var pe = () => new l({
910
929
  ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
911
930
  });
912
931
  }),
913
- nonReactive: (() => L({
932
+ nonReactive: (() => I({
914
933
  ...e,
915
934
  tableName: e.tableName,
916
935
  fields: e.fields,
@@ -924,7 +943,7 @@ var pe = () => new l({
924
943
  ...e.insertSchema === void 0 ? {} : { insertSchema: e.insertSchema },
925
944
  ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
926
945
  })),
927
- validate: ((t) => L({
946
+ validate: ((t) => I({
928
947
  ...e,
929
948
  tableName: e.tableName,
930
949
  fields: e.fields,
@@ -938,7 +957,7 @@ var pe = () => new l({
938
957
  insertSchema: t,
939
958
  ...e.validatePatchSchema === void 0 ? {} : { validatePatchSchema: e.validatePatchSchema }
940
959
  })),
941
- validatePatch: ((t) => L({
960
+ validatePatch: ((t) => I({
942
961
  ...e,
943
962
  tableName: e.tableName,
944
963
  fields: e.fields,
@@ -953,22 +972,22 @@ var pe = () => new l({
953
972
  validatePatchSchema: r.partial(t)
954
973
  }))
955
974
  };
956
- }, R = (e, t) => {
957
- O(e);
975
+ }, L = (e, t) => {
976
+ j(e);
958
977
  let n = Object.entries(t).flatMap(([e, t]) => {
959
- let n = xe(t);
978
+ let n = he(t);
960
979
  return n === void 0 ? [] : [{
961
980
  column: e,
962
981
  ...n
963
982
  }];
964
- }), r = pt(_(t), e);
965
- for (let t of Object.keys(r)) k(e, t);
983
+ }), r = _t(C(t), e);
984
+ for (let t of Object.keys(r)) M(e, t);
966
985
  let i;
967
- for (let [t, n] of Object.entries(r)) n.references === g && (n.references = () => {
986
+ for (let [t, n] of Object.entries(r)) n.references === S && (n.references = () => {
968
987
  if (i === void 0) throw Error(`selfReference() on '${e}.${t}' read before table() returned`);
969
988
  return i;
970
989
  });
971
- return i = L({
990
+ return i = I({
972
991
  appliedPluginRefs: n,
973
992
  tableName: e,
974
993
  fields: r,
@@ -980,7 +999,7 @@ var pe = () => new l({
980
999
  appliedChecks: [],
981
1000
  appliedRules: []
982
1001
  }), i;
983
- }, mt = (e) => e === "sqlite" || e === "turso", ht = (e) => e === "mysql" || e === "mariadb", z = (e, t) => {
1002
+ }, vt = (e) => e === "sqlite" || e === "turso", yt = (e) => e === "mysql" || e === "mariadb", R = (e, t) => {
984
1003
  switch (t) {
985
1004
  case "mysql":
986
1005
  case "mariadb": return `\`${e.replace(/`/g, "``")}\``;
@@ -989,51 +1008,51 @@ var pe = () => new l({
989
1008
  case "sqlite":
990
1009
  case "turso": return `"${e.replace(/"/g, "\"\"")}"`;
991
1010
  }
992
- }, gt = 1e4, _t = Symbol.for("@voltro/database/tableRegistry"), B = globalThis, V = B[_t] ?? (B[_t] = /* @__PURE__ */ new Map()), vt = (e) => {
993
- let t = V.get(e.tableName);
1011
+ }, bt = 1e4, xt = Symbol.for("@voltro/database/tableRegistry"), St = globalThis, z = St[xt] ?? (St[xt] = /* @__PURE__ */ new Map()), Ct = (e) => {
1012
+ let t = z.get(e.tableName);
994
1013
  if (t === void 0) {
995
- V.set(e.tableName, e);
1014
+ z.set(e.tableName, e);
996
1015
  return;
997
1016
  }
998
1017
  if (t !== e) throw Error(`duplicate table '${e.tableName}' registration: two different table descriptors claim the same name. Rename one or import the shared module that defines it.`);
999
- }, yt = (e) => {
1000
- V.get(e.tableName) === void 0 && V.set(e.tableName, e);
1001
- }, H = (e) => V.get(e), bt = (e) => {
1002
- let t = V.get(e);
1018
+ }, wt = (e) => {
1019
+ z.get(e.tableName) === void 0 && z.set(e.tableName, e);
1020
+ }, B = (e) => z.get(e), Tt = (e) => {
1021
+ let t = z.get(e);
1003
1022
  if (t === void 0) throw Error(`table '${e}' is not registered. Register it by wrapping it in \`databaseHandle({ ... })\` (the usual path) or call \`registerTable(t)\` explicitly before this runs. Note a \`queryFor(t)\` query carries its own source table, so eager-loads don't hit this — this error means a reconstructed descriptor or by-name tooling reached an unregistered table.`);
1004
1023
  return t;
1005
- }, xt = () => [...V.values()], St = (e) => V.delete(e), Ct = () => {
1006
- V.clear();
1007
- }, wt = (e) => V.get(e)?.isReactive !== !1, Tt = (e) => e.order ?? [], Et = (e) => ({
1024
+ }, Et = () => [...z.values()], Dt = (e) => z.delete(e), Ot = () => {
1025
+ z.clear();
1026
+ }, kt = (e) => z.get(e)?.isReactive !== !1, V = (e) => e.order ?? [], At = (e) => ({
1008
1027
  op: "count",
1009
1028
  alias: e ?? "count"
1010
- }), Dt = (e, t) => ({
1029
+ }), jt = (e, t) => ({
1011
1030
  op: "count-distinct",
1012
1031
  column: e,
1013
1032
  alias: t ?? `count_distinct_${e}`
1014
- }), Ot = (e, t) => ({
1033
+ }), Mt = (e, t) => ({
1015
1034
  op: "sum",
1016
1035
  column: e,
1017
1036
  alias: t ?? `sum_${e}`
1018
- }), kt = (e, t) => ({
1037
+ }), Nt = (e, t) => ({
1019
1038
  op: "avg",
1020
1039
  column: e,
1021
1040
  alias: t ?? `avg_${e}`
1022
- }), At = (e, t) => ({
1041
+ }), Pt = (e, t) => ({
1023
1042
  op: "min",
1024
1043
  column: e,
1025
1044
  alias: t ?? `min_${e}`
1026
- }), jt = (e, t) => ({
1045
+ }), Ft = (e, t) => ({
1027
1046
  op: "max",
1028
1047
  column: e,
1029
1048
  alias: t ?? `max_${e}`
1030
- }), Mt = (e, t) => ({
1049
+ }), It = (e, t) => ({
1031
1050
  op: "column",
1032
1051
  column: e,
1033
1052
  alias: t ?? e
1034
- }), U = (e) => (...t) => {
1053
+ }), H = (e) => (...t) => {
1035
1054
  if (t.length < 2) throw Error(`${e}: requires at least two queries`);
1036
- return G({
1055
+ return W({
1037
1056
  table: t[0].descriptor.table,
1038
1057
  predicate: void 0,
1039
1058
  order: [],
@@ -1045,55 +1064,55 @@ var pe = () => new l({
1045
1064
  queries: t.map((e) => e.descriptor)
1046
1065
  }
1047
1066
  });
1048
- }, Nt = U("union"), Pt = U("union-all"), Ft = U("intersect"), It = U("except"), W = (e) => ({ over: (t) => ({
1067
+ }, Lt = H("union"), Rt = H("union-all"), zt = H("intersect"), Bt = H("except"), U = (e) => ({ over: (t) => ({
1049
1068
  ...e,
1050
1069
  window: t
1051
- }) }), Lt = (e = "rowNumber") => W({
1070
+ }) }), Vt = (e = "rowNumber") => U({
1052
1071
  op: "window-row-number",
1053
1072
  alias: e
1054
- }), Rt = (e = "rank") => W({
1073
+ }), Ht = (e = "rank") => U({
1055
1074
  op: "window-rank",
1056
1075
  alias: e
1057
- }), zt = (e = "denseRank") => W({
1076
+ }), Ut = (e = "denseRank") => U({
1058
1077
  op: "window-dense-rank",
1059
1078
  alias: e
1060
- }), Bt = (e, t = 1, n) => W({
1079
+ }), Wt = (e, t = 1, n) => U({
1061
1080
  op: "window-lag",
1062
1081
  column: e,
1063
1082
  alias: n ?? `lag_${e}`,
1064
1083
  offset: t
1065
- }), Vt = (e, t = 1, n) => W({
1084
+ }), Gt = (e, t = 1, n) => U({
1066
1085
  op: "window-lead",
1067
1086
  column: e,
1068
1087
  alias: n ?? `lead_${e}`,
1069
1088
  offset: t
1070
- }), Ht = (e, t) => W({
1089
+ }), Kt = (e, t) => U({
1071
1090
  op: "window-sum-over",
1072
1091
  column: e,
1073
1092
  alias: t ?? `sum_${e}_over`
1074
- }), Ut = (e, t) => W({
1093
+ }), qt = (e, t) => U({
1075
1094
  op: "window-avg-over",
1076
1095
  column: e,
1077
1096
  alias: t ?? `avg_${e}_over`
1078
- }), Wt = (e, t, n) => {
1079
- let r = n?.find((e) => e.name === t) ?? H(e)?.appliedFullText?.find((e) => e.name === t);
1097
+ }), Jt = (e, t, n) => {
1098
+ let r = n?.find((e) => e.name === t) ?? B(e)?.appliedFullText?.find((e) => e.name === t);
1080
1099
  if (r === void 0) throw Error(`.matching('${t}', ...): no full-text index named '${t}' is declared on table '${e}'. Declare it with \`table(...).fullTextIndex('${t}', [columns])\` first.`);
1081
1100
  return {
1082
1101
  columns: r.columns,
1083
1102
  ...r.config === void 0 ? {} : { config: r.config },
1084
1103
  ...r.weights === void 0 ? {} : { weights: r.weights }
1085
1104
  };
1086
- }, G = (e) => ({
1105
+ }, W = (e) => ({
1087
1106
  descriptor: e,
1088
1107
  where(t) {
1089
1108
  let n = e.predicate ? { and: [e.predicate, t] } : t;
1090
- return G({
1109
+ return W({
1091
1110
  ...e,
1092
1111
  predicate: n
1093
1112
  });
1094
1113
  },
1095
1114
  orderBy(t, n = "asc") {
1096
- return G({
1115
+ return W({
1097
1116
  ...e,
1098
1117
  order: [...e.order, {
1099
1118
  column: t,
@@ -1102,43 +1121,43 @@ var pe = () => new l({
1102
1121
  });
1103
1122
  },
1104
1123
  limit(t) {
1105
- return G({
1124
+ return W({
1106
1125
  ...e,
1107
1126
  take: t
1108
1127
  });
1109
1128
  },
1110
1129
  offset(t) {
1111
- return G({
1130
+ return W({
1112
1131
  ...e,
1113
1132
  skip: t
1114
1133
  });
1115
1134
  },
1116
1135
  select(...t) {
1117
- return G({
1136
+ return W({
1118
1137
  ...e,
1119
1138
  projection: t
1120
1139
  });
1121
1140
  },
1122
1141
  using(t) {
1123
- return G({
1142
+ return W({
1124
1143
  ...e,
1125
1144
  usingIndex: t
1126
1145
  });
1127
1146
  },
1128
1147
  withDeleted() {
1129
- return G({
1148
+ return W({
1130
1149
  ...e,
1131
1150
  includeDeleted: !0
1132
1151
  });
1133
1152
  },
1134
1153
  forUpdate() {
1135
- return G({
1154
+ return W({
1136
1155
  ...e,
1137
1156
  lock: "update"
1138
1157
  });
1139
1158
  },
1140
1159
  unscoped() {
1141
- return G({
1160
+ return W({
1142
1161
  ...e,
1143
1162
  crossTenant: !0
1144
1163
  });
@@ -1148,13 +1167,13 @@ var pe = () => new l({
1148
1167
  ...e.eager ?? {},
1149
1168
  ...t
1150
1169
  };
1151
- return G({
1170
+ return W({
1152
1171
  ...e,
1153
1172
  eager: n
1154
1173
  });
1155
1174
  },
1156
1175
  count() {
1157
- return G({
1176
+ return W({
1158
1177
  ...e,
1159
1178
  projection: void 0,
1160
1179
  aggregations: [{
@@ -1168,15 +1187,15 @@ var pe = () => new l({
1168
1187
  ...t,
1169
1188
  alias: e
1170
1189
  }));
1171
- return G({
1190
+ return W({
1172
1191
  ...e,
1173
1192
  projection: void 0,
1174
1193
  aggregations: n
1175
1194
  });
1176
1195
  },
1177
1196
  matching(t, n) {
1178
- let r = Wt(e.table, t, e.fullTextIndexes);
1179
- return G({
1197
+ let r = Jt(e.table, t, e.fullTextIndexes);
1198
+ return W({
1180
1199
  ...e,
1181
1200
  fullTextSearch: {
1182
1201
  indexName: t,
@@ -1190,7 +1209,7 @@ var pe = () => new l({
1190
1209
  rankBy(t) {
1191
1210
  let n = e.fullTextSearch;
1192
1211
  if (n === void 0) throw Error(".rankBy() requires a preceding .matching(...) clause — there is no full-text search to rank on this query.");
1193
- return G({
1212
+ return W({
1194
1213
  ...e,
1195
1214
  fullTextSearch: {
1196
1215
  ...n,
@@ -1209,7 +1228,7 @@ var pe = () => new l({
1209
1228
  distance: r?.distance ?? "cosine",
1210
1229
  ...e.annClause?.ef === void 0 ? {} : { ef: e.annClause.ef }
1211
1230
  };
1212
- return G({
1231
+ return W({
1213
1232
  ...e,
1214
1233
  annClause: i
1215
1234
  });
@@ -1221,7 +1240,7 @@ var pe = () => new l({
1221
1240
  distance: "cosine",
1222
1241
  ...e.annClause?.ef === void 0 ? {} : { ef: e.annClause.ef }
1223
1242
  };
1224
- return G({
1243
+ return W({
1225
1244
  ...e,
1226
1245
  annClause: r,
1227
1246
  take: n
@@ -1234,7 +1253,7 @@ var pe = () => new l({
1234
1253
  column: "",
1235
1254
  distance: "cosine"
1236
1255
  };
1237
- return G({
1256
+ return W({
1238
1257
  ...e,
1239
1258
  annClause: {
1240
1259
  ...n,
@@ -1243,22 +1262,22 @@ var pe = () => new l({
1243
1262
  });
1244
1263
  },
1245
1264
  use(t) {
1246
- return G({ ...t(e) });
1265
+ return W({ ...t(e) });
1247
1266
  },
1248
1267
  distinct() {
1249
- return G({
1268
+ return W({
1250
1269
  ...e,
1251
1270
  distinct: !0
1252
1271
  });
1253
1272
  },
1254
1273
  distinctOn(t) {
1255
- return G({
1274
+ return W({
1256
1275
  ...e,
1257
1276
  distinctOn: [...t]
1258
1277
  });
1259
1278
  },
1260
1279
  as(t) {
1261
- return G({
1280
+ return W({
1262
1281
  ...e,
1263
1282
  alias: t
1264
1283
  });
@@ -1270,7 +1289,7 @@ var pe = () => new l({
1270
1289
  alias: n,
1271
1290
  on: r
1272
1291
  }];
1273
- return G({
1292
+ return W({
1274
1293
  ...e,
1275
1294
  joins: a
1276
1295
  });
@@ -1282,7 +1301,7 @@ var pe = () => new l({
1282
1301
  alias: n,
1283
1302
  on: r
1284
1303
  }];
1285
- return G({
1304
+ return W({
1286
1305
  ...e,
1287
1306
  joins: a
1288
1307
  });
@@ -1292,7 +1311,7 @@ var pe = () => new l({
1292
1311
  outputKey: e,
1293
1312
  source: t
1294
1313
  }));
1295
- return G({
1314
+ return W({
1296
1315
  ...e,
1297
1316
  projection: void 0,
1298
1317
  joinedProjection: n
@@ -1301,7 +1320,7 @@ var pe = () => new l({
1301
1320
  withCte(t, n) {
1302
1321
  let r = e.ctes ?? [];
1303
1322
  if (r.some((e) => e.name === t)) throw Error(`Query.withCte: duplicate CTE name '${t}'`);
1304
- return G({
1323
+ return W({
1305
1324
  ...e,
1306
1325
  ctes: [...r, {
1307
1326
  name: t,
@@ -1312,7 +1331,7 @@ var pe = () => new l({
1312
1331
  recursiveCte(t, n) {
1313
1332
  let r = e.ctes ?? [];
1314
1333
  if (r.some((e) => e.name === t)) throw Error(`Query.recursiveCte: duplicate CTE name '${t}'`);
1315
- return G({
1334
+ return W({
1316
1335
  ...e,
1317
1336
  ctes: [...r, {
1318
1337
  name: t,
@@ -1323,20 +1342,20 @@ var pe = () => new l({
1323
1342
  },
1324
1343
  groupBy(t) {
1325
1344
  let n = e.groupBy ? [...e.groupBy, ...t] : [...t];
1326
- return G({
1345
+ return W({
1327
1346
  ...e,
1328
1347
  groupBy: n
1329
1348
  });
1330
1349
  },
1331
1350
  having(t) {
1332
1351
  let n = e.having ? { and: [e.having, t] } : t;
1333
- return G({
1352
+ return W({
1334
1353
  ...e,
1335
1354
  having: n
1336
1355
  });
1337
1356
  },
1338
1357
  exists() {
1339
- return G({
1358
+ return W({
1340
1359
  ...e,
1341
1360
  projection: void 0,
1342
1361
  aggregations: [{
@@ -1347,8 +1366,8 @@ var pe = () => new l({
1347
1366
  });
1348
1367
  }
1349
1368
  });
1350
- function K(e) {
1351
- return G({
1369
+ function Yt(e) {
1370
+ return W({
1352
1371
  table: e.tableName,
1353
1372
  predicate: void 0,
1354
1373
  order: [],
@@ -1359,7 +1378,7 @@ function K(e) {
1359
1378
  sourceTable: e
1360
1379
  });
1361
1380
  }
1362
- var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1381
+ var Xt = (e, t, n) => Zt(e, "id", t, n), Zt = (e, t, n, r, i = "asc") => {
1363
1382
  let a = [...e.order.filter((e) => e.column !== t), {
1364
1383
  column: t,
1365
1384
  direction: i
@@ -1374,21 +1393,21 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1374
1393
  order: a,
1375
1394
  take: r
1376
1395
  };
1377
- }, qt = (e) => {
1396
+ }, Qt = (e) => {
1378
1397
  let t = {};
1379
- for (let [n, r] of Object.entries(e)) vt(r), t[n] = K(r);
1398
+ for (let [n, r] of Object.entries(e)) Ct(r), t[n] = Yt(r);
1380
1399
  return t;
1381
- }, Jt = (e) => e.isView === !0, Yt = (e, t, n) => {
1382
- if (O(e), n.trim().length === 0) throw Error(`view('${e}', …): the SELECT body is empty — a view must define a query.`);
1383
- let r = _(t);
1384
- for (let t of Object.keys(r)) k(e, t);
1400
+ }, $t = (e) => e.isView === !0, en = (e, t, n) => {
1401
+ if (j(e), n.trim().length === 0) throw Error(`view('${e}', …): the SELECT body is empty — a view must define a query.`);
1402
+ let r = C(t);
1403
+ for (let t of Object.keys(r)) M(e, t);
1385
1404
  return {
1386
1405
  tableName: e,
1387
1406
  fields: r,
1388
1407
  isView: !0,
1389
1408
  viewSelect: n
1390
1409
  };
1391
- }, Xt = (e) => K({
1410
+ }, tn = (e) => Yt({
1392
1411
  ...e,
1393
1412
  isReactive: !1,
1394
1413
  appliedMixins: [],
@@ -1396,8 +1415,8 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1396
1415
  appliedUniques: [],
1397
1416
  appliedFullText: [],
1398
1417
  appliedChecks: []
1399
- }), Zt = (e, t, n = null) => {
1400
- let r = n === null ? z(e.tableName, t) : `${z(n, t)}.${z(e.tableName, t)}`, i = e.viewSelect.trim();
1418
+ }), nn = (e, t, n = null) => {
1419
+ let r = n === null ? R(e.tableName, t) : `${R(n, t)}.${R(e.tableName, t)}`, i = e.viewSelect.trim();
1401
1420
  switch (t) {
1402
1421
  case "postgres":
1403
1422
  case "mysql":
@@ -1406,7 +1425,7 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1406
1425
  case "sqlite":
1407
1426
  case "turso": return `DROP VIEW IF EXISTS ${r};\nCREATE VIEW ${r} AS ${i};`;
1408
1427
  }
1409
- }, Qt = (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, q = (e) => {
1428
+ }, rn = (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, an = (e) => {
1410
1429
  if (e == null || typeof e != "string") return e;
1411
1430
  let t = e.trim();
1412
1431
  if (t.length === 0) return e;
@@ -1417,7 +1436,7 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1417
1436
  } catch {
1418
1437
  return e;
1419
1438
  }
1420
- }, $t = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, en = (e) => {
1439
+ }, on = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, sn = (e) => {
1421
1440
  if (e == null || e instanceof Date) return e;
1422
1441
  if (typeof e == "string") {
1423
1442
  let t = new Date(e);
@@ -1428,24 +1447,24 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1428
1447
  return isNaN(t.getTime()) ? e : t;
1429
1448
  }
1430
1449
  return e;
1431
- }, tn = (e, t, n) => {
1450
+ }, cn = (e, t, n) => {
1432
1451
  if (e == null) return e;
1433
1452
  switch (t) {
1434
- case "boolean": return n === "postgres" ? e : Qt(e);
1435
- case "vector": return n === "postgres" ? q(e) : e;
1436
- case "json": return n === "postgres" || n === "mysql" || n === "mariadb" ? e : q(e);
1437
- case "array": return n === "postgres" ? e : q(e);
1453
+ case "boolean": return n === "postgres" ? e : rn(e);
1454
+ case "vector": return n === "postgres" ? an(e) : e;
1455
+ case "json": return n === "postgres" || n === "mysql" || n === "mariadb" ? e : an(e);
1456
+ case "array": return n === "postgres" ? e : an(e);
1438
1457
  case "timestamp":
1439
- case "date": return n === "sqlite" || n === "turso" ? en(e) : e;
1458
+ case "date": return n === "sqlite" || n === "turso" ? sn(e) : e;
1440
1459
  case "decimal":
1441
- case "bigint": return $t(e);
1460
+ case "bigint": return on(e);
1442
1461
  default: return e;
1443
1462
  }
1444
- }, nn = (e, t, n) => {
1463
+ }, ln = (e, t, n) => {
1445
1464
  if (e.length === 0) return e;
1446
- let r = H(t);
1447
- return r === void 0 ? e : rn(e, r, n);
1448
- }, rn = (e, t, n) => {
1465
+ let r = B(t);
1466
+ return r === void 0 ? e : un(e, r, n);
1467
+ }, un = (e, t, n) => {
1449
1468
  if (e.length === 0) return e;
1450
1469
  let r = t.fields, i = [];
1451
1470
  for (let [e, t] of Object.entries(r)) i.push({
@@ -1454,10 +1473,10 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1454
1473
  });
1455
1474
  return e.map((e) => {
1456
1475
  let t = { ...e };
1457
- for (let { key: e, type: r } of i) e in t && (t[e] = tn(t[e], r, n));
1476
+ for (let { key: e, type: r } of i) e in t && (t[e] = cn(t[e], r, n));
1458
1477
  return t;
1459
1478
  });
1460
- }, an = (e, t) => {
1479
+ }, dn = (e, t) => {
1461
1480
  if (e == null) return e;
1462
1481
  switch (t) {
1463
1482
  case "json": return JSON.stringify(e);
@@ -1465,25 +1484,25 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1465
1484
  case "vector": return typeof e == "string" ? e : JSON.stringify(e);
1466
1485
  default: return e;
1467
1486
  }
1468
- }, on = (e, t, n = ["json", "array"]) => {
1469
- let r = H(t);
1487
+ }, fn = (e, t, n = ["json", "array"]) => {
1488
+ let r = B(t);
1470
1489
  if (r === void 0) return e;
1471
1490
  let i = r.fields, a = null;
1472
1491
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
1473
- let n = an(e[t], r.type);
1492
+ let n = dn(e[t], r.type);
1474
1493
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
1475
1494
  }
1476
1495
  return a ?? e;
1477
- }, sn = /^[A-Za-z_][A-Za-z0-9_]*$/, cn = (e) => "$" + e.map((e) => typeof e == "number" ? `[${e}]` : sn.test(e) ? `.${e}` : `."${e.replace(/"/g, "\\\"")}"`).join(""), ln = (e) => "{" + e.map((e) => {
1496
+ }, pn = /^[A-Za-z_][A-Za-z0-9_]*$/, mn = (e) => "$" + e.map((e) => typeof e == "number" ? `[${e}]` : pn.test(e) ? `.${e}` : `."${e.replace(/"/g, "\\\"")}"`).join(""), hn = (e) => "{" + e.map((e) => {
1478
1497
  let t = String(e);
1479
1498
  return /^[A-Za-z0-9_]+$/.test(t) ? t : `"${t.replace(/(["\\])/g, "\\$1")}"`;
1480
- }).join(",") + "}", un = (e, t, n, r = {}) => {
1481
- let i = z(e, n), a = r.numeric ?? !1;
1499
+ }).join(",") + "}", G = (e, t, n, r = {}) => {
1500
+ let i = R(e, n), a = r.numeric ?? !1;
1482
1501
  if (n === "postgres") {
1483
- let e = `(${i} #>> '${ln(t)}'::text[])`;
1502
+ let e = `(${i} #>> '${hn(t)}'::text[])`;
1484
1503
  return a ? `${e}::numeric` : e;
1485
1504
  }
1486
- let o = cn(t);
1505
+ let o = mn(t);
1487
1506
  switch (n) {
1488
1507
  case "mysql":
1489
1508
  case "mariadb": {
@@ -1500,7 +1519,257 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1500
1519
  return a ? `CAST(${e} AS REAL)` : e;
1501
1520
  }
1502
1521
  }
1503
- }, J = (e, t) => {
1522
+ }, gn = class extends Error {
1523
+ _tag = "TenantNamespaceUnresolved";
1524
+ constructor(e) {
1525
+ super(e), this.name = "TenantNamespaceUnresolved";
1526
+ }
1527
+ }, _n = class extends Error {
1528
+ _tag = "TenantNamespaceInvalid";
1529
+ constructor(e) {
1530
+ super(e), this.name = "TenantNamespaceInvalid";
1531
+ }
1532
+ }, vn = 63, yn = "tenant_", bn = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), xn = (e) => {
1533
+ if (e == null || e === "") throw new gn("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.");
1534
+ let t = bn(e);
1535
+ if (t.replace(/_/g, "") === "") throw new _n(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
1536
+ let n = `${yn}${t}`;
1537
+ if (n.length > vn) throw new _n(`namespace '${n}' for tenant '${e}' exceeds the ${vn}-byte identifier limit. Use a shorter tenant id.`);
1538
+ return n;
1539
+ }, K = (e, t) => e === null ? t : `${e}.${t}`, Sn = /* @__PURE__ */ new Set(["timestamp", "date"]), Cn = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, wn = (e, t) => {
1540
+ if (e === void 0 || t == null || !Sn.has(e) || t instanceof Date) return t;
1541
+ if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
1542
+ if (typeof t == "string" && Cn.test(t)) {
1543
+ let e = new Date(t);
1544
+ return Number.isNaN(e.getTime()) ? t : e;
1545
+ }
1546
+ return t;
1547
+ }, Tn = (e, t) => e === void 0 || !Sn.has(e) ? t : t.map((t) => wn(e, t)), En = (e, t) => {
1548
+ let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
1549
+ for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
1550
+ return t`${i}`;
1551
+ }, q = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), J = (e, t, n = null, r) => {
1552
+ if ("not" in e) return t`NOT (${J(e.not, t, n, r)})`;
1553
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => J(e, t, n, r)));
1554
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => J(e, t, n, r)));
1555
+ if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1556
+ let r = e, i = Y(r.subquery, t, n);
1557
+ return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
1558
+ }
1559
+ if (e.op === "exists" || e.op === "not-exists") {
1560
+ let r = e, i = Y(r.subquery, t, n);
1561
+ return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
1562
+ }
1563
+ let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
1564
+ mysql: () => t.unsafe(G(i.column, o, "mysql")),
1565
+ mssql: () => t.unsafe(G(i.column, o, "mssql")),
1566
+ sqlite: () => t.unsafe(G(i.column, o, "sqlite")),
1567
+ orElse: () => t.unsafe(G(i.column, o, "postgres"))
1568
+ }), l = () => t.onDialectOrElse({
1569
+ mysql: () => t.unsafe(G(i.column, o, "mysql", { numeric: !0 })),
1570
+ mssql: () => t.unsafe(G(i.column, o, "mssql", { numeric: !0 })),
1571
+ sqlite: () => t.unsafe(G(i.column, o, "sqlite", { numeric: !0 })),
1572
+ orElse: () => t.unsafe(G(i.column, o, "postgres", { numeric: !0 }))
1573
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : B(r)?.fields?.[i.column]?.type, h = (e) => wn(m, e);
1574
+ switch (i.op) {
1575
+ case "eq": return t`${u} = ${f(h(i.value))}`;
1576
+ case "neq": return t`${u} <> ${f(h(i.value))}`;
1577
+ case "gt": return t`${d} > ${p(i.value)}`;
1578
+ case "gte": return t`${d} >= ${p(i.value)}`;
1579
+ case "lt": return t`${d} < ${p(i.value)}`;
1580
+ case "lte": return t`${d} <= ${p(i.value)}`;
1581
+ case "in": {
1582
+ let e = i.value ?? [];
1583
+ return e.length === 0 ? t`FALSE` : t`${u} IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
1584
+ }
1585
+ case "notIn": {
1586
+ let e = i.value ?? [];
1587
+ return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
1588
+ }
1589
+ case "contains": {
1590
+ let e = `%${q(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
1591
+ return t.onDialectOrElse({
1592
+ mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
1593
+ mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
1594
+ sqlite: () => t`LOWER(${u}) LIKE LOWER(${e})`,
1595
+ orElse: () => t`${u} ILIKE ${e} ESCAPE '\\'`
1596
+ });
1597
+ }
1598
+ case "startsWith": {
1599
+ let e = `${q(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
1600
+ return t.onDialectOrElse({
1601
+ mysql: () => t`${u} LIKE ${e}`,
1602
+ orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
1603
+ });
1604
+ }
1605
+ case "arrayContains": {
1606
+ let e = i.value ?? [];
1607
+ return e.length === 0 ? t`TRUE` : t.onDialectOrElse({
1608
+ mysql: () => t`JSON_CONTAINS(${u}, ${JSON.stringify(e)})`,
1609
+ mssql: () => t`(SELECT COUNT(DISTINCT value) FROM OPENJSON(${u}) WHERE value IN ${t.in(e)}) = ${e.length}`,
1610
+ sqlite: () => t`(SELECT COUNT(DISTINCT value) FROM json_each(${u}) WHERE value IN ${t.in(e)}) = ${e.length}`,
1611
+ orElse: () => t`${u} @> ${e}`
1612
+ });
1613
+ }
1614
+ case "arrayOverlaps": {
1615
+ let e = i.value ?? [];
1616
+ return e.length === 0 ? t`FALSE` : t.onDialectOrElse({
1617
+ mysql: () => t.or(e.map((e) => t`JSON_CONTAINS(${u}, ${JSON.stringify(e)})`)),
1618
+ mssql: () => t`EXISTS (SELECT 1 FROM OPENJSON(${u}) WHERE value IN ${t.in(e)})`,
1619
+ sqlite: () => t`EXISTS (SELECT 1 FROM json_each(${u}) WHERE value IN ${t.in(e)})`,
1620
+ orElse: () => t`${u} && ${e}`
1621
+ });
1622
+ }
1623
+ case "arrayHas": return t.onDialectOrElse({
1624
+ mysql: () => t`JSON_CONTAINS(${u}, ${JSON.stringify(i.value)})`,
1625
+ mssql: () => t`${i.value} IN (SELECT value FROM OPENJSON(${u}))`,
1626
+ sqlite: () => t`EXISTS (SELECT 1 FROM json_each(${u}) WHERE value = ${i.value})`,
1627
+ orElse: () => t`${i.value} = ANY(${u})`
1628
+ });
1629
+ case "isNull": return t`${u} IS NULL`;
1630
+ case "isNotNull": return t`${u} IS NOT NULL`;
1631
+ case "spatial": {
1632
+ let e = i.value, n = t.unsafe("::geometry"), r = e.bufferMeters === void 0 ? t`${e.geom}${n}` : t`ST_Buffer(${e.geom}::geography, ${e.bufferMeters})::geometry`;
1633
+ return t.onDialectOrElse({
1634
+ mysql: () => {
1635
+ throw E("@voltro/plugin-postgis: spatial predicates are postgres-only");
1636
+ },
1637
+ mssql: () => {
1638
+ throw E("@voltro/plugin-postgis: spatial predicates are postgres-only");
1639
+ },
1640
+ sqlite: () => {
1641
+ throw E("@voltro/plugin-postgis: spatial predicates are postgres-only");
1642
+ },
1643
+ orElse: () => e.fn === "ST_DWithin" ? t`ST_DWithin(${a}::geography, ${e.geom}::geography, ${e.distanceMeters})` : e.fn === "&&" ? t`${a}${n} && ${r}` : t`${t.unsafe(e.fn)}(${a}${n}, ${r})`
1644
+ });
1645
+ }
1646
+ }
1647
+ }, Dn = (e, t) => {
1648
+ let n = [];
1649
+ 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}`);
1650
+ }, On = (e, t) => t.csv(e.map((e) => {
1651
+ let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
1652
+ if (e.op.startsWith("window-")) {
1653
+ let r = Dn(e.window ?? {}, t);
1654
+ switch (e.op) {
1655
+ case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
1656
+ case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
1657
+ case "window-dense-rank": return t`DENSE_RANK() OVER (${r}) AS ${t(e.alias)}`;
1658
+ case "window-lag": return t`LAG(${n}, ${t.unsafe(String(e.offset ?? 1))}) OVER (${r}) AS ${t(e.alias)}`;
1659
+ case "window-lead": return t`LEAD(${n}, ${t.unsafe(String(e.offset ?? 1))}) OVER (${r}) AS ${t(e.alias)}`;
1660
+ case "window-sum-over": return t`SUM(${n}) OVER (${r}) AS ${t(e.alias)}`;
1661
+ case "window-avg-over": return t`AVG(${n}) OVER (${r}) AS ${t(e.alias)}`;
1662
+ default: throw E(`compileAggregateProjection: unknown window op '${e.op}'`);
1663
+ }
1664
+ }
1665
+ switch (e.op) {
1666
+ case "count": return t`COUNT(${n}) AS ${t(e.alias)}`;
1667
+ case "count-distinct": return t`COUNT(DISTINCT ${n}) AS ${t(e.alias)}`;
1668
+ case "sum": return t`SUM(${n}) AS ${t(e.alias)}`;
1669
+ case "avg": return t`AVG(${n}) AS ${t(e.alias)}`;
1670
+ case "min": return t`MIN(${n}) AS ${t(e.alias)}`;
1671
+ case "max": return t`MAX(${n}) AS ${t(e.alias)}`;
1672
+ case "column":
1673
+ if (e.column === void 0) throw E(`compileAggregateProjection: 'column' projection requires a column name (alias '${e.alias}')`);
1674
+ return t`${t(e.column)} AS ${t(e.alias)}`;
1675
+ default: throw E(`compileAggregateProjection: unknown op '${e.op}'`);
1676
+ }
1677
+ })), kn = (e) => `[${e.join(",")}]`, An = (e, t) => {
1678
+ if (e.queryVector === void 0) return null;
1679
+ let n = t(e.column), r = kn(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
1680
+ return t.onDialectOrElse({
1681
+ mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
1682
+ mssql: () => t`NULL`,
1683
+ sqlite: () => t`NULL`,
1684
+ orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
1685
+ });
1686
+ }, jn = (e, t) => {
1687
+ let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
1688
+ return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
1689
+ }, Mn = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Nn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Pn = (e, t) => `${t}_${e.indexName}_fts`, Fn = (e, t, n) => {
1690
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${q(e.query)}%`;
1691
+ return n.onDialectOrElse({
1692
+ mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
1693
+ sqlite: () => {
1694
+ let r = n(Pn(e, t));
1695
+ return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
1696
+ },
1697
+ mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
1698
+ orElse: () => n`${Nn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
1699
+ });
1700
+ }, In = (e, t, n) => {
1701
+ let r = `%${q(e.query)}%`;
1702
+ return n.onDialectOrElse({
1703
+ mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
1704
+ sqlite: () => {
1705
+ let r = n(Pn(e, t));
1706
+ return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
1707
+ },
1708
+ 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}`),
1709
+ orElse: () => n`ts_rank(${Nn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
1710
+ });
1711
+ }, Y = (e, t, n = null) => {
1712
+ if (e.setOp && e.setOp.queries.length >= 2) {
1713
+ 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`(${Y(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
1714
+ if (V(e).length > 0 && a.push(t` ORDER BY ${t.csv(V(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
1715
+ if (!Number.isInteger(e.take) || e.take < 0) throw E(`compileSelect: invalid take ${e.take}`);
1716
+ a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
1717
+ }
1718
+ if (e.skip !== void 0) {
1719
+ if (!Number.isInteger(e.skip) || e.skip < 0) throw E(`compileSelect: invalid skip ${e.skip}`);
1720
+ a.push(t` OFFSET ${t.unsafe(String(e.skip))}`);
1721
+ }
1722
+ return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
1723
+ }
1724
+ let r = e.annClause === void 0 ? null : An(e.annClause, t);
1725
+ e.spatialClause !== void 0 && t.onDialectOrElse({
1726
+ mysql: () => {
1727
+ throw E("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
1728
+ },
1729
+ mssql: () => {
1730
+ throw E("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
1731
+ },
1732
+ sqlite: () => {
1733
+ throw E("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
1734
+ },
1735
+ orElse: () => t``
1736
+ });
1737
+ let i = e.spatialClause?.projectAs === void 0 ? null : jn(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? On(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 ? In(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({
1738
+ orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
1739
+ mysql: () => t`DISTINCT `,
1740
+ mssql: () => t`DISTINCT `,
1741
+ sqlite: () => t`DISTINCT `
1742
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.lock === "update", m = p ? t.onDialectOrElse({
1743
+ mssql: () => t` WITH (UPDLOCK, ROWLOCK)`,
1744
+ orElse: () => t``
1745
+ }) : t``, h = p ? t.onDialectOrElse({
1746
+ mssql: () => t``,
1747
+ sqlite: () => t``,
1748
+ orElse: () => t` FOR UPDATE`
1749
+ }) : t``, g = e.alias === void 0 ? t`${t(K(n, e.table))}${m}` : t`${t(K(n, e.table))} AS ${t(e.alias)}${m}`, ee = (e.joins ?? []).map((e) => {
1750
+ let r = e.kind === "inner" ? "INNER" : "LEFT";
1751
+ return t` ${t.unsafe(r)} JOIN ${t(K(n, e.table))} AS ${t(e.alias)} ON ${J(e.on, t, n)}`;
1752
+ }), te = ee.length > 0 ? ee.reduce((e, n) => t`${e}${n}`, g) : g, ne = c === void 0 ? null : Fn(c, e.table, t), _ = [e.predicate ? J(e.predicate, t, n, e.table) : null, ne].filter((e) => e !== null), v = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, re = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, y = e.having ? t` HAVING ${J(e.having, t, n, e.table)}` : t``, b = e.skip !== void 0, x = [];
1753
+ r !== null && x.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && x.push(e.spatialClause.order === "desc" ? t`${Mn(e.spatialClause, t)} DESC` : t`${Mn(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && x.push(t`${l} DESC`);
1754
+ for (let n of V(e)) x.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1755
+ let ie = x.length > 0 ? t` ORDER BY ${t.csv(x)}` : b ? t.onDialectOrElse({
1756
+ mssql: () => t` ORDER BY (SELECT NULL)`,
1757
+ orElse: () => t``
1758
+ }) : t``, S = (e) => {
1759
+ if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw E(`compileSelect: expected non-negative integer take/skip, got ${e}`);
1760
+ return t.unsafe(String(e));
1761
+ }, ae = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Y(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``;
1762
+ return t.onDialectOrElse({
1763
+ mssql: () => {
1764
+ let n = e.take !== void 0 && !b ? t`TOP ${S(e.take)} ` : t``, r = b ? t` OFFSET ${S(e.skip)} ROWS FETCH NEXT ${S(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1765
+ return t`${se}SELECT ${n}${f}${d} FROM ${te}${v}${re}${y}${ie}${r}`;
1766
+ },
1767
+ orElse: () => {
1768
+ let n = e.take === void 0 ? t`` : t` LIMIT ${S(e.take)}`, r = b ? t` OFFSET ${S(e.skip)}` : t``;
1769
+ return t`${se}SELECT ${f}${d} FROM ${te}${v}${re}${y}${ie}${n}${r}${h}`;
1770
+ }
1771
+ });
1772
+ }, X = (e, t) => {
1504
1773
  let n = (e) => {
1505
1774
  if (typeof e != "string" || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e)) return null;
1506
1775
  let [t = "", n = ""] = e.replace(/^[+-]/, "").split("."), r = t.replace(/^0+/, "") || "0";
@@ -1518,74 +1787,74 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1518
1787
  a = t === n ? 0 : t > n ? 1 : -1;
1519
1788
  }
1520
1789
  return a === 0 ? 0 : (a > 0 ? 1 : -1) * (r.negative ? -1 : 1);
1521
- }, dn = (e, t) => ({
1790
+ }, Ln = (e, t) => ({
1522
1791
  column: e,
1523
1792
  op: "eq",
1524
1793
  value: t
1525
- }), fn = (e, t) => ({
1794
+ }), Rn = (e, t) => ({
1526
1795
  column: e,
1527
1796
  op: "neq",
1528
1797
  value: t
1529
- }), pn = (e, t) => ({
1798
+ }), zn = (e, t) => ({
1530
1799
  column: e,
1531
1800
  op: "gt",
1532
1801
  value: t
1533
- }), mn = (e, t) => ({
1802
+ }), Bn = (e, t) => ({
1534
1803
  column: e,
1535
1804
  op: "gte",
1536
1805
  value: t
1537
- }), hn = (e, t) => ({
1806
+ }), Vn = (e, t) => ({
1538
1807
  column: e,
1539
1808
  op: "lt",
1540
1809
  value: t
1541
- }), gn = (e, t) => ({
1810
+ }), Hn = (e, t) => ({
1542
1811
  column: e,
1543
1812
  op: "lte",
1544
1813
  value: t
1545
- }), _n = (e, t) => ({
1814
+ }), Un = (e, t) => ({
1546
1815
  column: e,
1547
1816
  op: "in",
1548
1817
  value: t
1549
- }), vn = (e, t) => ({
1818
+ }), Wn = (e, t) => ({
1550
1819
  column: e,
1551
1820
  op: "notIn",
1552
1821
  value: t
1553
- }), yn = (e, t) => ({
1822
+ }), Gn = (e, t) => ({
1554
1823
  column: e,
1555
1824
  op: "contains",
1556
1825
  value: t
1557
- }), bn = (e, t) => ({
1826
+ }), Kn = (e, t) => ({
1558
1827
  column: e,
1559
1828
  op: "startsWith",
1560
1829
  value: t
1561
- }), xn = (e, t) => ({
1830
+ }), qn = (e, t) => ({
1562
1831
  column: e,
1563
1832
  op: "arrayContains",
1564
1833
  value: t
1565
- }), Sn = (e, t) => ({
1834
+ }), Jn = (e, t) => ({
1566
1835
  column: e,
1567
1836
  op: "arrayOverlaps",
1568
1837
  value: t
1569
- }), Cn = (e, t) => ({
1838
+ }), Yn = (e, t) => ({
1570
1839
  column: e,
1571
1840
  op: "arrayHas",
1572
1841
  value: t
1573
- }), wn = {
1842
+ }), Xn = {
1574
1843
  column: "id",
1575
1844
  op: "in",
1576
1845
  value: []
1577
- }, Tn = (e) => ({
1846
+ }, Zn = (e) => ({
1578
1847
  column: e,
1579
1848
  op: "isNull"
1580
- }), En = (e) => ({
1849
+ }), Qn = (e) => ({
1581
1850
  column: e,
1582
1851
  op: "isNotNull"
1583
- }), Dn = (e, t) => ({
1852
+ }), $n = (e, t) => ({
1584
1853
  column: e,
1585
1854
  op: "spatial",
1586
1855
  value: t
1587
- }), On = (...e) => ({ and: e }), kn = (...e) => ({ or: e }), An = (e) => ({ not: e }), jn = (e, ...t) => {
1588
- if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1856
+ }), er = (...e) => ({ and: e }), tr = (...e) => ({ or: e }), nr = (e) => ({ not: e }), rr = (e, ...t) => {
1857
+ if (t.length === 0) throw E(`jsonField("${e}"): at least one path segment is required`);
1589
1858
  let n = (n, r) => ({
1590
1859
  column: e,
1591
1860
  path: t,
@@ -1606,56 +1875,56 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1606
1875
  isNull: () => n("isNull"),
1607
1876
  isNotNull: () => n("isNotNull")
1608
1877
  };
1609
- }, Y = (e) => "descriptor" in e ? e.descriptor : e, Mn = (e, t) => ({
1878
+ }, Z = (e) => "descriptor" in e ? e.descriptor : e, ir = (e, t) => ({
1610
1879
  column: e,
1611
1880
  op: "subquery-in",
1612
- subquery: Y(t)
1613
- }), Nn = (e, t) => ({
1881
+ subquery: Z(t)
1882
+ }), ar = (e, t) => ({
1614
1883
  column: e,
1615
1884
  op: "subquery-not-in",
1616
- subquery: Y(t)
1617
- }), Pn = (e) => ({
1885
+ subquery: Z(t)
1886
+ }), or = (e) => ({
1618
1887
  op: "exists",
1619
- subquery: Y(e)
1620
- }), Fn = (e) => ({
1888
+ subquery: Z(e)
1889
+ }), sr = (e) => ({
1621
1890
  op: "not-exists",
1622
- subquery: Y(e)
1623
- }), In = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/, Ln = (e) => {
1891
+ subquery: Z(e)
1892
+ }), cr = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/, lr = (e) => {
1624
1893
  if (e instanceof Date) return e.getTime();
1625
- if (typeof e == "string" && In.test(e)) {
1894
+ if (typeof e == "string" && cr.test(e)) {
1626
1895
  let t = Date.parse(e);
1627
1896
  return Number.isNaN(t) ? void 0 : t;
1628
1897
  }
1629
- }, Rn = (e, t) => {
1898
+ }, ur = (e, t) => {
1630
1899
  if (!(e instanceof Date) && !(t instanceof Date)) return;
1631
- let n = Ln(e), r = Ln(t);
1900
+ let n = lr(e), r = lr(t);
1632
1901
  return n === void 0 || r === void 0 ? void 0 : [n, r];
1633
- }, zn = (e, t) => {
1902
+ }, dr = (e, t) => {
1634
1903
  if (e === t) return !0;
1635
- let n = Rn(e, t);
1904
+ let n = ur(e, t);
1636
1905
  return n !== void 0 && n[0] === n[1];
1637
- }, Bn = (e, t) => {
1906
+ }, fr = (e, t) => {
1638
1907
  if (e == null || t == null) return null;
1639
- let n = Rn(e, t);
1908
+ let n = ur(e, t);
1640
1909
  if (n !== void 0) return n[0] === n[1] ? 0 : n[0] > n[1] ? 1 : -1;
1641
1910
  let r = e instanceof Date ? e.getTime() : e, i = t instanceof Date ? t.getTime() : t;
1642
1911
  return typeof r == typeof i ? r === i ? 0 : r > i ? 1 : -1 : null;
1643
- }, X = (e, t, n = null, r = {}) => {
1912
+ }, Q = (e, t, n = null, r = {}) => {
1644
1913
  if (!t) return !1;
1645
- if ("not" in e) return !X(e.not, t, n, r);
1914
+ if ("not" in e) return !Q(e.not, t, n, r);
1646
1915
  if ("and" in e) {
1647
- for (let i of e.and) if (!X(i, t, n, r)) return !1;
1916
+ for (let i of e.and) if (!Q(i, t, n, r)) return !1;
1648
1917
  return !0;
1649
1918
  }
1650
1919
  if ("or" in e) {
1651
- for (let i of e.or) if (X(i, t, n, r)) return !0;
1920
+ for (let i of e.or) if (Q(i, t, n, r)) return !0;
1652
1921
  return !1;
1653
1922
  }
1654
1923
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1655
1924
  if (!n) return !1;
1656
1925
  let i = n.get(e.subquery);
1657
1926
  if (!(i instanceof Set)) return !1;
1658
- let a = t[e.column], o = r[e.column]?.type === "decimal" ? [...i].some((e) => J(a, e) === 0) : i.has(a);
1927
+ let a = t[e.column], o = r[e.column]?.type === "decimal" ? [...i].some((e) => X(a, e) === 0) : i.has(a);
1659
1928
  return e.op === "subquery-in" ? o : !o;
1660
1929
  }
1661
1930
  if (e.op === "exists" || e.op === "not-exists") {
@@ -1663,7 +1932,7 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1663
1932
  let t = n.get(e.subquery), r = typeof t == "number" ? t > 0 : t instanceof Set && t.size > 0;
1664
1933
  return e.op === "exists" ? r : !r;
1665
1934
  }
1666
- let i = e, a = t[i.column], o = r[i.column]?.type === "decimal", s = (e, t) => o && e != null && t != null ? J(e, t) === 0 : zn(e, t), c = o ? J : Bn;
1935
+ let i = e, a = t[i.column], o = r[i.column]?.type === "decimal", s = (e, t) => o && e != null && t != null ? X(e, t) === 0 : dr(e, t), c = o ? X : fr;
1667
1936
  switch (i.op) {
1668
1937
  case "eq": return s(a, i.value);
1669
1938
  case "neq": return !s(a, i.value);
@@ -1686,19 +1955,19 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1686
1955
  case "arrayHas": return Array.isArray(a) && a.includes(i.value);
1687
1956
  case "isNull": return a == null;
1688
1957
  case "isNotNull": return a != null;
1689
- 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.");
1958
+ case "spatial": throw E("@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.");
1690
1959
  }
1691
- }, Z = function* (e) {
1960
+ }, $ = function* (e) {
1692
1961
  if ("not" in e) {
1693
- yield* Z(e.not);
1962
+ yield* $(e.not);
1694
1963
  return;
1695
1964
  }
1696
1965
  if ("and" in e) {
1697
- for (let t of e.and) yield* Z(t);
1966
+ for (let t of e.and) yield* $(t);
1698
1967
  return;
1699
1968
  }
1700
1969
  if ("or" in e) {
1701
- for (let t of e.or) yield* Z(t);
1970
+ for (let t of e.or) yield* $(t);
1702
1971
  return;
1703
1972
  }
1704
1973
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1708,30 +1977,30 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1708
1977
  kind: "exists",
1709
1978
  descriptor: e.subquery
1710
1979
  });
1711
- }, Q = function* (e, t = !0) {
1980
+ }, pr = function* (e, t = !0) {
1712
1981
  if ("not" in e) {
1713
- yield* Q(e.not, !1);
1982
+ yield* pr(e.not, !1);
1714
1983
  return;
1715
1984
  }
1716
1985
  if ("and" in e) {
1717
- for (let n of e.and) yield* Q(n, t);
1986
+ for (let n of e.and) yield* pr(n, t);
1718
1987
  return;
1719
1988
  }
1720
1989
  if ("or" in e) {
1721
- for (let t of e.or) yield* Q(t, !1);
1990
+ for (let t of e.or) yield* pr(t, !1);
1722
1991
  return;
1723
1992
  }
1724
1993
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1725
1994
  ...e,
1726
1995
  conjunctive: t
1727
1996
  });
1728
- }, Vn = (e, t) => ({
1997
+ }, mr = (e, t) => ({
1729
1998
  name: e,
1730
1999
  body: t
1731
- }), Hn = (e) => {
2000
+ }), hr = (e) => {
1732
2001
  if (e.lifecycle === "cron" && !e.cron) throw Error(`seed "${e.id}": lifecycle 'cron' requires a 'cron' field`);
1733
2002
  if (e.lifecycle === "onSchemaChange" && (!e.watchedTables || e.watchedTables.length === 0)) throw Error(`seed "${e.id}": lifecycle 'onSchemaChange' requires at least one entry in 'watchedTables'`);
1734
- let t = e.steps({ step: Vn });
2003
+ let t = e.steps({ step: mr });
1735
2004
  if (t.length === 0) throw Error(`seed "${e.id}": at least one step is required`);
1736
2005
  return {
1737
2006
  __seed: !0,
@@ -1744,68 +2013,75 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1744
2013
  ...e.fingerprint === void 0 ? {} : { fingerprint: e.fingerprint },
1745
2014
  steps: t
1746
2015
  };
1747
- }, Un = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, Wn = null, Gn = null, Kn = (e) => {
1748
- Wn = e;
1749
- }, qn = (e) => {
1750
- Gn = e;
1751
- }, Jn = async (e) => {
1752
- let t = Wn;
2016
+ }, gr = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, _r = null, vr = null, yr = (e) => {
2017
+ _r = e;
2018
+ }, br = (e) => {
2019
+ vr = e;
2020
+ }, xr = async (e) => {
2021
+ let t = _r;
1753
2022
  t !== null && await t(e);
1754
- }, Yn = async (e) => {
1755
- let t = Gn;
2023
+ }, Sr = async (e) => {
2024
+ let t = vr;
1756
2025
  t !== null && e.changedTables.length !== 0 && await t(e);
1757
- }, Xn = (e) => {
2026
+ }, Cr = (e) => {
1758
2027
  if (!e.id || e.id.length === 0) throw Error("migration: `id` is required + must be non-empty");
1759
2028
  if (!e.up || !e.down) throw Error(`migration ${e.id}: both \`up\` and \`down\` must be functions`);
1760
2029
  return e;
1761
- }, Zn = Symbol.for("voltro.migration.irreversible"), $ = class extends Error {
2030
+ }, wr = Symbol.for("voltro.migration.irreversible"), Tr = class extends Error {
1762
2031
  migrationId;
1763
2032
  reason;
1764
2033
  _tag = "IrreversibleMigrationError";
1765
2034
  constructor(e, t) {
1766
2035
  super(`migration ${e} cannot be rolled back: ${t}`), this.migrationId = e, this.reason = t, this.name = "IrreversibleMigrationError";
1767
2036
  }
1768
- }, Qn = (e) => {
2037
+ }, Er = (e) => {
1769
2038
  if (!e || e.trim().length === 0) throw Error("irreversible(): a reason is required");
1770
- return Object.assign(() => t.fail(new $("<unknown>", e)), { [Zn]: e });
1771
- }, $n = (e) => {
1772
- let t = e[Zn];
2039
+ return Object.assign(() => t.fail(new Tr("<unknown>", e)), { [wr]: e });
2040
+ }, Dr = (e) => {
2041
+ let t = e[wr];
1773
2042
  return typeof t == "string" ? t : void 0;
1774
- }, er = class {
2043
+ }, Or = class {
1775
2044
  reason;
1776
2045
  _tag = "MigrationSkipped";
1777
2046
  constructor(e) {
1778
2047
  this.reason = e;
1779
2048
  }
1780
- }, tr = class extends Error {
2049
+ }, kr = class extends Error {
1781
2050
  migrationId;
1782
2051
  failed;
1783
2052
  _tag = "MigrationExpectationFailed";
1784
2053
  constructor(e, t) {
1785
2054
  super(`migration ${e}: ${t.length} post-condition(s) did not hold after up():\n` + t.map((e) => ` - ${e}`).join("\n") + "\n The migration is NOT recorded; the next run applies it again."), this.migrationId = e, this.failed = t, this.name = "MigrationExpectationFailed";
1786
2055
  }
1787
- }, nr = class extends Error {
2056
+ }, Ar = class extends Error {
1788
2057
  migrationId;
1789
2058
  dialect;
1790
2059
  _tag = "TransactionBrokenByBodyError";
1791
2060
  constructor(e, t) {
1792
2061
  super(`migration ${e} is transactional, and its body COMMITTED the transaction from inside — on ${t} a DDL statement commits everything before it. The work is in the database and the migration is recorded; it will not run again. What did not hold is the all-or-nothing guarantee. Either mark it \`transactional: false\` (per-statement, resumable through your own idempotency) or move the schema change into \`ctx.schema\` in a migration of its own and keep this one to data.`), this.migrationId = e, this.dialect = t, this.name = "TransactionBrokenByBodyError";
1793
2062
  }
1794
- }, rr = class extends Error {
2063
+ }, jr = class extends Error {
2064
+ migrationId;
2065
+ operation;
2066
+ _tag = "MigrationNeedsSqlClient";
2067
+ constructor(e, t, n) {
2068
+ super(`migration ${e}: ${t} — ${n}`), this.migrationId = e, this.operation = t, this.name = "MigrationNeedsSqlClient";
2069
+ }
2070
+ }, Mr = class extends Error {
1795
2071
  table;
1796
2072
  report;
1797
2073
  _tag = "RewriteUnstableError";
1798
2074
  constructor(e, t) {
1799
- super(`rewrite of ${e} did not stabilise after ${t.passes} pass(es): ${t.rewritten} rewritten, ${t.contended} contended on the last pass. Something is still writing these rows — raise maxPasses, or stop the writer first.`), this.table = e, this.report = t, this.name = "RewriteUnstableError";
2075
+ super(`rewrite of ${e} did not stabilise after ${t.passes} pass(es): ${t.rewritten} rewritten, ${t.contended} contended on the last pass. Check for concurrent writes and guard values that cannot round-trip exactly before raising maxPasses.`), this.table = e, this.report = t, this.name = "RewriteUnstableError";
1800
2076
  }
1801
- }, ir = /^\d{8}_\d{6}_[a-z0-9_]+\.ts$/, ar = (e) => typeof e == "object" && !!e && "id" in e && "up" in e && "down" in e && typeof e.id == "string" && typeof e.up == "function" && typeof e.down == "function", or = /* @__PURE__ */ new Set(["voltro_isr_cache"]), sr = (e) => or.has(e) || e.startsWith("_voltro_") || e.startsWith("_cloud_") || e.startsWith("cluster_") || e.startsWith("__turso_internal_"), cr = "_voltro_staging_", lr = (e) => e.startsWith(cr), ur = /__dropped_\d{14}$/, dr = (e) => ur.test(e), fr = 7, pr = (e) => {
2077
+ }, Nr = /^\d{8}_\d{6}_[a-z0-9_]+\.ts$/, Pr = (e) => typeof e == "object" && !!e && "id" in e && "up" in e && "down" in e && typeof e.id == "string" && typeof e.up == "function" && typeof e.down == "function", Fr = /* @__PURE__ */ new Set(["voltro_isr_cache"]), Ir = (e) => Fr.has(e) || e.startsWith("_voltro_") || e.startsWith("_cloud_") || e.startsWith("cluster_") || e.startsWith("__turso_internal_"), Lr = "_voltro_staging_", Rr = (e) => e.startsWith(Lr), zr = /__dropped_\d{14}$/, Br = (e) => zr.test(e), Vr = 7, Hr = (e) => {
1802
2078
  let t = /__dropped_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec(e);
1803
2079
  if (t === null) return;
1804
2080
  let [, n, r, i, a, o, s] = t;
1805
2081
  return new Date(Date.UTC(Number(n), Number(r) - 1, Number(i), Number(a), Number(o), Number(s)));
1806
- }, mr = (e, t = {}) => {
2082
+ }, Ur = (e, t = {}) => {
1807
2083
  let n = t.now ?? /* @__PURE__ */ new Date(), r = t.retentionDays ?? 7, i = [], a = (e, t) => {
1808
- let a = pr(e);
2084
+ let a = Hr(e);
1809
2085
  if (a === void 0) return;
1810
2086
  let o = Math.floor((n.getTime() - a.getTime()) / 864e5);
1811
2087
  o >= r && i.push({
@@ -1814,123 +2090,170 @@ var Gt = (e, t, n) => Kt(e, "id", t, n), Kt = (e, t, n, r, i = "asc") => {
1814
2090
  ageDays: o
1815
2091
  });
1816
2092
  };
1817
- for (let t of e.tables) if (a(t.name, t.name), !dr(t.name)) for (let e of t.columns ?? []) a(e.name, `${t.name}.${e.name}`);
2093
+ for (let t of e.tables) if (a(t.name, t.name), !Br(t.name)) for (let e of t.columns ?? []) a(e.name, `${t.name}.${e.name}`);
1818
2094
  return i;
1819
- }, hr = (e, t) => {
2095
+ }, Wr = (e, t) => {
1820
2096
  let n = e.reduce((e, t) => e.ageDays >= t.ageDays ? e : t), r = (/* @__PURE__ */ new Date(Date.now() - t * 864e5)).toISOString().slice(0, 10);
1821
2097
  return `${e.length} soft-drop snapshot(s) older than ${t} day(s) still hold the dropped data (oldest: ${n.name}, ${n.ageDays}d) — ${e.map((e) => e.name).join(", ")}. Restore with \`voltro db restore-snapshot\` or reclaim with \`voltro db gc-snapshots --before ${r}\`; the window is \`database.softDropRetentionDays\` in app.config.`;
1822
- }, gr = R("_voltro_migrations", {
1823
- id: d({ prefix: "mig" }),
1824
- name: f(),
1825
- hash: f(),
1826
- status: f(),
1827
- appliedAt: m().nullable(),
1828
- durationMs: p().nullable(),
1829
- errorMessage: f().nullable(),
1830
- errorStack: f().nullable(),
1831
- workflowRunId: f().nullable(),
1832
- createdAt: m().default("now"),
1833
- updatedAt: m().default("now").onUpdate("now")
1834
- }).index(["status"]), _r = R("_voltro_seeds", {
1835
- id: d({ prefix: "seed" }),
1836
- name: f(),
1837
- lifecycle: f(),
1838
- fingerprint: f(),
1839
- cronSchedule: f().nullable(),
1840
- watchedTables: h().nullable(),
1841
- nextRunAt: m().nullable(),
1842
- lastRunStatus: f().nullable(),
1843
- lastRunAt: m().nullable(),
1844
- lastRunDurationMs: p().nullable(),
1845
- lastRunRowsTouched: p().nullable(),
1846
- lastError: f().nullable(),
1847
- workflowRunId: f().nullable(),
1848
- createdAt: m().default("now"),
1849
- updatedAt: m().default("now").onUpdate("now")
1850
- }).index(["lifecycle"]).index(["nextRunAt"]), vr = R("_voltro_migration_plans", {
1851
- id: d({ prefix: "plan" }),
1852
- fingerprint: f(),
1853
- liveFingerprint: f().nullable(),
1854
- operations: h(),
1855
- rollbackPlan: h().nullable(),
1856
- appliedBy: f(),
1857
- environment: f(),
1858
- source: f(),
1859
- onlineStrategy: f().nullable(),
1860
- durationMs: p(),
1861
- notes: f().nullable(),
1862
- squashedAt: m().nullable(),
1863
- appliedAt: m().default("now"),
1864
- createdAt: m().default("now"),
1865
- updatedAt: m().default("now").onUpdate("now")
1866
- }).index(["fingerprint"]).index(["environment"]), yr = R("_voltro_idempotency", {
1867
- id: d({ prefix: "idem" }),
1868
- scope: f(),
1869
- key: f(),
1870
- status: f(),
1871
- response: h().nullable(),
1872
- createdAt: m().default("now")
1873
- }).unique(["scope", "key"]).index(["createdAt"]), br = R("_voltro_devices", {
1874
- id: d({ prefix: "device" }),
1875
- tenantId: f(),
1876
- name: f(),
1877
- scopes: h().nullable(),
1878
- pairingHash: f().maxLength(64).nullable(),
1879
- pairingExpiresAt: m().nullable(),
1880
- accessHash: f().maxLength(64).nullable(),
1881
- accessExpiresAt: m().nullable(),
1882
- refreshHash: f().maxLength(64).nullable(),
1883
- refreshExpiresAt: m().nullable(),
1884
- previousRefreshHash: f().maxLength(64).nullable(),
1885
- generation: p().default(0),
1886
- pairedAt: m().nullable(),
1887
- lastSeenAt: m().nullable(),
1888
- revokedAt: m().nullable(),
1889
- revokedReason: f().nullable(),
1890
- createdBy: f().nullable(),
1891
- metadata: h().nullable(),
1892
- createdAt: m()
1893
- }).index(["tenantId"]).index(["pairingHash"]).index(["accessHash"]).index(["refreshHash"]).index(["previousRefreshHash"]), xr = R("_voltro_tenant_selections", {
1894
- id: d({ prefix: "tsel" }),
1895
- subjectType: f().maxLength(32),
1896
- subjectId: f(),
1897
- tenantId: f(),
1898
- selectedAt: m()
1899
- }).primaryKey(["id"]).nonReactive(), Sr = R("_voltro_kv", {
1900
- id: d({ prefix: "kv" }),
1901
- key: f().unique(),
1902
- value: f().nullable(),
1903
- expiresAt: m().nullable(),
1904
- createdAt: m().default("now"),
1905
- updatedAt: m().default("now").onUpdate("now")
1906
- }).index(["expiresAt"]), Cr = R("_voltro_api_keys", {
1907
- id: d({ prefix: "apikey" }),
1908
- tenantId: f().nullable(),
1909
- name: f(),
1910
- hashedKey: f().maxLength(64).unique(),
1911
- keyPrefix: f(),
1912
- scopes: h().nullable(),
1913
- lastUsedAt: m().nullable(),
1914
- requestCount: p().default(0),
1915
- expiresAt: m().nullable(),
1916
- revokedAt: m().nullable(),
1917
- createdBy: f().nullable(),
1918
- onBehalfOf: f().nullable(),
1919
- metadata: h().nullable(),
1920
- createdAt: m().default("now")
1921
- }).index("byApiKeyTenant", ["tenantId"]), wr = R("_voltro_replica_observations", {
1922
- id: d({ prefix: "robs" }),
1923
- replicaId: f().maxLength(191),
1924
- startedAt: m(),
1925
- version: f().maxLength(64).nullable(),
1926
- kind: f().maxLength(64),
1927
- payload: f().nullable(),
1928
- reachableAt: f().maxLength(255).nullable(),
1929
- writtenAt: m().default("now").onUpdate("now")
1930
- }).unique(["replicaId", "kind"]).index(["kind"]), Tr = [
1931
- gr,
1932
- _r,
1933
- vr
1934
- ];
2098
+ }, Gr = (e, t) => e.filter((e) => !Ir(e.name) || t.has(e.name)), Kr = L("_voltro_migrations", {
2099
+ id: f({ prefix: "mig" }),
2100
+ name: p(),
2101
+ hash: p(),
2102
+ status: p(),
2103
+ appliedAt: v().nullable(),
2104
+ durationMs: m().nullable(),
2105
+ errorMessage: p().nullable(),
2106
+ errorStack: p().nullable(),
2107
+ workflowRunId: p().nullable(),
2108
+ createdAt: v().default("now"),
2109
+ updatedAt: v().default("now").onUpdate("now")
2110
+ }).index(["status"]), qr = L("_voltro_seeds", {
2111
+ id: f({ prefix: "seed" }),
2112
+ name: p(),
2113
+ lifecycle: p(),
2114
+ fingerprint: p(),
2115
+ cronSchedule: p().nullable(),
2116
+ watchedTables: y().nullable(),
2117
+ nextRunAt: v().nullable(),
2118
+ lastRunStatus: p().nullable(),
2119
+ lastRunAt: v().nullable(),
2120
+ lastRunDurationMs: m().nullable(),
2121
+ lastRunRowsTouched: m().nullable(),
2122
+ lastError: p().nullable(),
2123
+ workflowRunId: p().nullable(),
2124
+ createdAt: v().default("now"),
2125
+ updatedAt: v().default("now").onUpdate("now")
2126
+ }).index(["lifecycle"]).index(["nextRunAt"]), Jr = L("_voltro_migration_plans", {
2127
+ id: f({ prefix: "plan" }),
2128
+ fingerprint: p(),
2129
+ liveFingerprint: p().nullable(),
2130
+ operations: y(),
2131
+ rollbackPlan: y().nullable(),
2132
+ appliedBy: p(),
2133
+ environment: p(),
2134
+ source: p(),
2135
+ onlineStrategy: p().nullable(),
2136
+ durationMs: m(),
2137
+ notes: p().nullable(),
2138
+ squashedAt: v().nullable(),
2139
+ appliedAt: v().default("now"),
2140
+ createdAt: v().default("now"),
2141
+ updatedAt: v().default("now").onUpdate("now")
2142
+ }).index(["fingerprint"]).index(["environment"]), Yr = L("_voltro_idempotency", {
2143
+ id: f({ prefix: "idem" }),
2144
+ scope: p(),
2145
+ key: p(),
2146
+ status: p(),
2147
+ response: y().nullable(),
2148
+ createdAt: v().default("now")
2149
+ }).unique(["scope", "key"]).index(["createdAt"]), Xr = L("_voltro_devices", {
2150
+ id: f({ prefix: "device" }),
2151
+ tenantId: p(),
2152
+ name: p(),
2153
+ scopes: y().nullable(),
2154
+ pairingHash: p().maxLength(64).nullable(),
2155
+ pairingExpiresAt: v().nullable(),
2156
+ accessHash: p().maxLength(64).nullable(),
2157
+ accessExpiresAt: v().nullable(),
2158
+ refreshHash: p().maxLength(64).nullable(),
2159
+ refreshExpiresAt: v().nullable(),
2160
+ previousRefreshHash: p().maxLength(64).nullable(),
2161
+ generation: m().default(0),
2162
+ pairedAt: v().nullable(),
2163
+ lastSeenAt: v().nullable(),
2164
+ revokedAt: v().nullable(),
2165
+ revokedReason: p().nullable(),
2166
+ createdBy: p().nullable(),
2167
+ metadata: y().nullable(),
2168
+ createdAt: v()
2169
+ }).index(["tenantId"]).index(["pairingHash"]).index(["accessHash"]).index(["refreshHash"]).index(["previousRefreshHash"]), Zr = L("_voltro_tenant_selections", {
2170
+ id: f({ prefix: "tsel" }),
2171
+ subjectType: p().maxLength(32),
2172
+ subjectId: p(),
2173
+ tenantId: p(),
2174
+ selectedAt: v()
2175
+ }).primaryKey(["id"]).nonReactive(), Qr = L("_voltro_kv", {
2176
+ id: f({ prefix: "kv" }),
2177
+ key: p().unique(),
2178
+ value: p().nullable(),
2179
+ expiresAt: v().nullable(),
2180
+ createdAt: v().default("now"),
2181
+ updatedAt: v().default("now").onUpdate("now")
2182
+ }).index(["expiresAt"]), $r = L("_voltro_api_keys", {
2183
+ id: f({ prefix: "apikey" }),
2184
+ tenantId: p().nullable(),
2185
+ name: p(),
2186
+ hashedKey: p().maxLength(64).unique(),
2187
+ keyPrefix: p(),
2188
+ scopes: y().nullable(),
2189
+ lastUsedAt: v().nullable(),
2190
+ requestCount: m().default(0),
2191
+ expiresAt: v().nullable(),
2192
+ revokedAt: v().nullable(),
2193
+ createdBy: p().nullable(),
2194
+ onBehalfOf: p().nullable(),
2195
+ metadata: y().nullable(),
2196
+ createdAt: v().default("now")
2197
+ }).index("byApiKeyTenant", ["tenantId"]), ei = L("_voltro_replica_observations", {
2198
+ id: f({ prefix: "robs" }),
2199
+ replicaId: p().maxLength(191),
2200
+ startedAt: v(),
2201
+ version: p().maxLength(64).nullable(),
2202
+ kind: p().maxLength(64),
2203
+ payload: p().nullable(),
2204
+ reachableAt: p().maxLength(255).nullable(),
2205
+ writtenAt: v().default("now").onUpdate("now")
2206
+ }).unique(["replicaId", "kind"]).index(["kind"]), ti = [
2207
+ Kr,
2208
+ qr,
2209
+ Jr
2210
+ ], ni = "_voltro_replace_in_progress", ri = L(ni, {
2211
+ id: f({ prefix: "repl" }),
2212
+ startedAt: v().default("now"),
2213
+ kind: p().default("replace"),
2214
+ tables: p().nullable(),
2215
+ capture: p().nullable(),
2216
+ via: p(),
2217
+ staging: p().nullable(),
2218
+ heartbeatAt: v().nullable(),
2219
+ resumable: _().nullable()
2220
+ }), ii = 30, ai = (e, t) => {
2221
+ let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
2222
+ return (Number.isFinite(r) && r > 0 ? r : n) * 6e4;
2223
+ }, oi = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), si = (e) => {
2224
+ let t = e.filter((e) => e.kind !== "staging");
2225
+ if (t.length !== 0) return `refusing to start: a destructive data operation did not finish.
2226
+ ${t.map((e) => {
2227
+ 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";
2228
+ if (e.kind === "restore") return ` - a native \`restore\` over ${e.via} began loading an artefact over this database ${t}\n and never reported finishing.\n` + (e.capture === null ? " The artefact it was loading was not recorded. Re-run the restore from your backup\n directory, or restore from another backup." : ` The artefact it was loading:\n ${e.capture}\n Re-run it to completion with: voltro data restore ${e.capture} --allow-live`);
2229
+ let n = e.tables === null ? "this database" : `${e.tables} table(s)`;
2230
+ return ` - a \`replace\` over ${e.via} began emptying ${n} ${t} and never reported finishing.\n` + (e.capture === null ? " NO capture was taken for that run, so the previous rows are not recoverable from here.\n Restore from your own backup." : ` The target's previous rows were captured first:\n ${e.capture}\n Restore them with: voltro data import ${e.capture} --mode replace`);
2231
+ }).join("\n")}\n
2232
+ A half-replaced database is indistinguishable from an empty one from the inside — every table
2233
+ exists, every constraint holds, and every query returns nothing without erroring. That is why
2234
+ this is a refusal and not a warning.
2235
+
2236
+ When the data is back, or you have decided the current state is correct, clear the marker:
2237
+ voltro data clear-replace-marker --yes`;
2238
+ }, ci = (e, t, n) => {
2239
+ let r = e.filter((e) => e.kind === "staging");
2240
+ return {
2241
+ all: r,
2242
+ droppable: r.filter((e) => {
2243
+ if (e.resumable) return !1;
2244
+ let r = (e.heartbeatAt ?? e.startedAt).getTime();
2245
+ return Number.isFinite(r) ? t - r >= n : !1;
2246
+ })
2247
+ };
2248
+ }, li = (e, t) => {
2249
+ if (e.all.length === 0) return;
2250
+ let n = new Set(e.droppable.map((e) => e.id));
2251
+ return `staged data-import leftovers:
2252
+ ${e.all.map((e) => {
2253
+ let r = e.heartbeatAt ?? e.startedAt, i = Number.isFinite(r.getTime()) ? `${Math.max(0, Math.round((t - r.getTime()) / 6e4))} minute(s) ago` : "at an unknown time", a = `${e.staging.length} staging table(s) from a \`replace\` over ${e.via}, last active ${i}`;
2254
+ return n.has(e.id) ? ` - ${a} — DROPPED: the run is not resumable and has been silent long enough that nothing is loading into them.` : e.resumable ? ` - ${a} — KEPT: the run was started \`--no-atomic\`, so these ARE its resume point. Re-run the same\n bundle to continue from them, or drop them with: voltro data clear-staging --yes` : ` - ${a} — KEPT: still beating, so an import is loading into them right now.`;
2255
+ }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
2256
+ a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
2257
+ };
1935
2258
  //#endregion
1936
- export { hn as $, ge as $n, ht as $t, Hn as A, Ee as An, Vt as At, Sn as B, ce as Bn, Ot as Bt, er as C, Le as Cn, Et as Ct, $n as D, Ie as Dn, It as Dt, Qn as E, Fe as En, zt as Et, Kn as F, l as Fn, Gt as Ft, Pn as G, se as Gn, Ct as Gt, yn as H, ee as Hn, Nt as Ht, wn as I, g as In, K as It, _n as J, pe as Jn, wt as Jt, pn as K, ae as Kn, yt as Kt, On as L, he as Ln, Rt as Lt, Jn as M, we as Mn, At as Mt, Un as N, Se as Nn, Tt as Nt, ar as O, Ae as On, Ft as Ot, qn as P, xe as Pn, Kt as Pt, jn as Q, p as Qn, gt as Qt, xn as R, ie as Rn, Wt as Rt, tr as S, w as Sn, Mt as St, nr as T, b as Tn, qt as Tt, dn as U, s as Un, Pt as Ut, Z as V, ue as Vn, Ht as Vt, X as W, le as Wn, xt as Wt, En as X, ve as Xn, bt as Xt, Mn as Y, _e as Yn, vt as Yt, Tn as Z, d as Zn, St as Zt, dr as _, k as _n, Xt as _t, vr as a, lt as an, te as ar, Nn as at, ir as b, j as bn, kt as bt, _r as c, st as cn, o as cr, bn as ct, fr as d, rt as dn, me as dr, un as dt, mt as en, h as er, gn as et, or as f, nt as fn, tn as ft, sr as g, He as gn, Jt as gt, hr as h, Ve as hn, on as ht, Sr as i, R as in, c as ir, vn as it, Yn as j, Ce as jn, jt, Xn as k, Te as kn, Bt as kt, xr as l, P as ln, f as lr, Q as lt, mr as m, Be as mn, nn as mt, br as n, ut as nn, re as nr, An as nt, gr as o, ot as on, fe as or, kn as ot, cr as p, et as pn, rn as pt, mn as q, ne as qn, H as qt, yr as r, ct as rn, ye as rr, Fn as rt, wr as s, at as sn, de as sr, Dn as st, Cr as t, z as tn, _ as tr, fn as tt, Tr as u, it as un, m as ur, J as ut, lr as v, A as vn, Yt as vt, rr as w, Re as wn, Dt as wt, $ as x, y as xn, Ut as xt, pr as y, O as yn, Zt as yt, Cn as z, oe as zn, Lt as zt };
2259
+ export { Ln as $, be as $n, Pt as $t, Tr as A, it as An, ae as Ar, xn as At, hr as B, j as Bn, nn as Bt, Wr as C, ft as Cn, y as Cr, Y as Ct, Gr as D, ct as Dn, c as Dr, _n as Dt, Rr as E, dt as En, pe as Er, Tn as Et, Ar as F, ze as Fn, ln as Ft, yr as G, Ne as Gn, jt as Gt, xr as H, E as Hn, qt as Ht, Er as I, Be as In, fn as It, qn as J, we as Jn, Bt as Jt, Xn as K, Ie as Kn, Qt as Kt, Dr as L, Ve as Ln, $t as Lt, jr as M, at as Mn, p as Mr, G as Mt, Or as N, rt as Nn, v as Nr, cn as Nt, Hr as O, st as On, h as Or, gn as Ot, Mr as P, et as Pn, ce as Pr, un as Pt, Gn as Q, ye as Qn, Ft as Qt, Pr as R, M as Rn, tn as Rt, Ur as S, R as Sn, ue as Sr, En as St, Br as T, L as Tn, ee as Tr, wn as Tt, gr as U, De as Un, It as Ut, Sr as V, P as Vn, Nt as Vt, br as W, T as Wn, At as Wt, Jn as X, Fe as Xn, Wt as Xt, Yn as Y, Pe as Yn, zt as Yt, $ as Z, Te as Zn, Gt as Zt, Zr as _, Tt as _n, se as _r, $n as _t, li as a, Jt as an, S as ar, ir as at, Fr as b, yt as bn, f as br, X as bt, ai as c, Kt as cn, _ as cr, rr as ct, Yr as d, Et as dn, l as dr, Rn as dt, V as en, _e as er, Q as et, Qr as f, Ot as fn, s as fr, nr as ft, qr as g, Ct as gn, g as gr, tr as gt, ei as h, kt as hn, ne as hr, ar as ht, si as i, Ht as in, u as ir, Un as it, kr as j, ot as jn, o as jr, bn as jt, Nr as k, lt as kn, oe as kr, K as kt, $r as l, Lt as ln, b as lr, Vn as lt, Kr as m, B as mn, re as mr, Wn as mt, ii as n, Xt as nn, ge as nr, zn as nt, ci as o, Vt as on, le as or, Qn as ot, Jr as p, wt as pn, x as pr, sr as pt, er as q, Le as qn, Ut as qt, ri as r, Yt as rn, he as rr, Bn as rt, oi as s, Mt as sn, te as sr, Zn as st, ni as t, Zt as tn, ve as tr, or as tt, Xr as u, Rt as un, ie as ur, Hn as ut, ti as v, Dt as vn, de as vr, Kn as vt, Ir as w, ut as wn, C as wr, q as wt, Lr as x, vt as xn, m as xr, J as xt, Vr as y, bt as yn, fe as yr, pr as yt, Cr as z, N as zn, en as zt };