@voltro/runtime 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,24 +1,24 @@
1
1
  import { ENCRYPTED_PREFIX as e, and as t, attachEagerLoads as n, boolean as r, clearRetentions as i, collectSubqueries as a, contains as o, decryptFieldsOnRead as s, deserializeArraysOnRead as c, encryptFieldsForWrite as l, eq as u, evaluatePredicate as d, generateId as f, getRelations as p, getTable as m, gt as h, gte as g, hasEagerLoads as _, id as v, inSet as y, integer as b, isNull as x, json as S, listRetentions as C, lt as w, lte as ee, neq as te, or as T, queryFor as ne, registerRetention as re, requireTable as ie, retentionTtlMsFromEnv as ae, serializeArraysForWrite as oe, sweepRetention as se, table as E, text as D, timestamp as O, walkLeaves as ce } from "@voltro/database";
2
2
  import { createCipheriv as le, createDecipheriv as ue, createHash as de, randomBytes as fe, randomUUID as pe, scryptSync as me } from "node:crypto";
3
3
  import { EventEmitter as he } from "node:events";
4
- import { createLogger as ge } from "@voltro/logger";
5
- import { ADMIN_SCOPE as _e, ConnectionInfo as ve, SubjectService as ye, UndoConflict as be, UndoForbidden as xe, UndoNotFound as Se, WorkflowRunHandleSchema as Ce, diffRows as we, isIdKeyed as Te, publishServerError as Ee, systemSubject as De, tsMs as Oe } from "@voltro/protocol";
6
- import { Cause as k, Clock as ke, Context as Ae, Cron as A, Deferred as je, Duration as Me, Effect as j, Either as Ne, Exit as Pe, Layer as M, ManagedRuntime as Fe, Metric as N, MetricBoundaries as Ie, MetricState as Le, Option as P, Ref as F, Schema as I, Stream as L, Tracer as Re } from "effect";
7
- import * as ze from "node:http";
8
- import { createServer as Be } from "node:http";
9
- import { HttpClient as Ve, HttpClientRequest as He, HttpLayerRouter as R, HttpServer as Ue, HttpServerRequest as z, HttpServerResponse as B } from "@effect/platform";
10
- import { NodeContext as We, NodeHttpServer as Ge, NodeRuntime as Ke } from "@effect/platform-node";
11
- import { Rpc as qe, RpcSerialization as Je, RpcServer as V } from "@effect/rpc";
12
- import { defineRestRoute as Ye, dispatchSharedPath as Xe, requireScope as Ze } from "@voltro/protocol/rest";
13
- import { AsyncLocalStorage as Qe } from "node:async_hooks";
14
- import { SpanKind as H, SpanStatusCode as $e } from "@opentelemetry/api";
15
- import { Kv as et, KvError as tt, KvStore as nt, layerConnections as rt, layerMemory as it, layerRedis as at } from "@voltro/kv";
16
- import { apiKeyStrategy as ot } from "@voltro/protocol/apikey";
17
- import { getCurrentWorkflowExecutionId as st, inspectWorkflow as ct } from "@voltro/workflow";
18
- import { ArrayFormatter as lt } from "effect/ParseResult";
19
- import { spawn as ut } from "node:child_process";
4
+ import { ADMIN_SCOPE as ge, ConnectionInfo as _e, SubjectService as ve, UndoConflict as ye, UndoForbidden as be, UndoNotFound as xe, WorkflowRunHandleSchema as Se, checkGuards as Ce, diffRows as we, effectiveScopes as Te, hasEffectiveScope as Ee, isIdKeyed as De, publishServerError as Oe, requireScope as ke, systemSubject as Ae, tsMs as je } from "@voltro/protocol";
5
+ import { createLogger as Me } from "@voltro/logger";
6
+ import { Cause as k, Clock as Ne, Context as Pe, Cron as A, Deferred as Fe, Duration as Ie, Effect as j, Either as Le, Exit as Re, Layer as M, ManagedRuntime as ze, Metric as N, MetricBoundaries as Be, MetricState as Ve, Option as P, Ref as F, Schema as I, Stream as L, Tracer as He } from "effect";
7
+ import * as Ue from "node:http";
8
+ import { createServer as We } from "node:http";
9
+ import { HttpClient as Ge, HttpClientRequest as Ke, HttpLayerRouter as R, HttpServer as qe, HttpServerRequest as z, HttpServerResponse as B } from "@effect/platform";
10
+ import { NodeContext as Je, NodeHttpServer as Ye, NodeRuntime as Xe } from "@effect/platform-node";
11
+ import { Rpc as Ze, RpcSerialization as Qe, RpcServer as $e } from "@effect/rpc";
12
+ import { defineRestRoute as et, dispatchSharedPath as tt, requireScope as nt } from "@voltro/protocol/rest";
13
+ import { AsyncLocalStorage as rt } from "node:async_hooks";
14
+ import { SpanKind as it, SpanStatusCode as at } from "@opentelemetry/api";
15
+ import { Kv as ot, KvError as st, KvStore as ct, layerConnections as lt, layerMemory as ut, layerRedis as dt } from "@voltro/kv";
16
+ import { apiKeyStrategy as ft } from "@voltro/protocol/apikey";
17
+ import { getCurrentWorkflowExecutionId as pt, inspectWorkflow as mt } from "@voltro/workflow";
18
+ import { ArrayFormatter as ht } from "effect/ParseResult";
19
+ import { spawn as gt } from "node:child_process";
20
20
  //#region src/matcher.ts
21
- var dt = class {
21
+ var _t = class {
22
22
  byTable = /* @__PURE__ */ new Map();
23
23
  register(e) {
24
24
  let t = this.byTable.get(e.table);
@@ -59,7 +59,7 @@ var dt = class {
59
59
  });
60
60
  return { perTable: e };
61
61
  }
62
- }, ft = (e) => {
62
+ }, vt = (e) => {
63
63
  let t = [];
64
64
  for (let n of ce(e)) n.conjunctive && n.path === void 0 && (n.op === "eq" && t.push({
65
65
  column: n.column,
@@ -69,7 +69,7 @@ var dt = class {
69
69
  values: n.value
70
70
  }));
71
71
  return t;
72
- }, pt = (e) => {
72
+ }, yt = (e) => {
73
73
  let t = [];
74
74
  for (let n of ce(e)) n.conjunctive && n.path === void 0 && (n.op === "gt" || n.op === "gte" || n.op === "lt" || n.op === "lte") && t.push({
75
75
  column: n.column,
@@ -77,10 +77,10 @@ var dt = class {
77
77
  threshold: n.value
78
78
  });
79
79
  return t;
80
- }, mt = (e, t) => {
80
+ }, bt = (e, t) => {
81
81
  for (let n of ce(e)) if (n.conjunctive && n.path === void 0 && n.op === "eq" && n.column === t) return n.value;
82
82
  return null;
83
- }, ht = (e, t) => {
83
+ }, xt = (e, t) => {
84
84
  let n = [];
85
85
  for (let r of e) {
86
86
  let e = t(r);
@@ -88,8 +88,8 @@ var dt = class {
88
88
  n.push(`${typeof e}:${String(e)}`);
89
89
  }
90
90
  return n.join("|");
91
- }, gt = (e, t) => e === null || t === null ? null : e === t ? 0 : typeof e == typeof t ? e > t ? 1 : -1 : null, _t = (e, t, n) => {
92
- let r = gt(e, n);
91
+ }, St = (e, t) => e === null || t === null ? null : e === t ? 0 : typeof e == typeof t ? e > t ? 1 : -1 : null, Ct = (e, t, n) => {
92
+ let r = St(e, n);
93
93
  if (r === null) return !1;
94
94
  switch (t) {
95
95
  case "gt": return r > 0;
@@ -97,7 +97,7 @@ var dt = class {
97
97
  case "lt": return r < 0;
98
98
  case "lte": return r <= 0;
99
99
  }
100
- }, vt = class {
100
+ }, wt = class {
101
101
  columnByTable = /* @__PURE__ */ new Map();
102
102
  rangeByTable = /* @__PURE__ */ new Map();
103
103
  tupleByTable = /* @__PURE__ */ new Map();
@@ -105,9 +105,9 @@ var dt = class {
105
105
  subscriptions = /* @__PURE__ */ new Map();
106
106
  register(e) {
107
107
  this.columnByTable.has(e.table) || this.columnByTable.set(e.table, /* @__PURE__ */ new Map()), this.rangeByTable.has(e.table) || this.rangeByTable.set(e.table, /* @__PURE__ */ new Map()), this.tupleByTable.has(e.table) || this.tupleByTable.set(e.table, /* @__PURE__ */ new Map()), this.unindexedByTable.has(e.table) || this.unindexedByTable.set(e.table, /* @__PURE__ */ new Set());
108
- let t = ft(e.predicate), n = pt(e.predicate);
108
+ let t = vt(e.predicate), n = yt(e.predicate);
109
109
  if (e.usingIndex !== void 0) {
110
- let r = e.usingIndex, i = ht(r.fields, (t) => mt(e.predicate, t));
110
+ let r = e.usingIndex, i = xt(r.fields, (t) => bt(e.predicate, t));
111
111
  if (i !== null) {
112
112
  let a = `${r.name}|${i}`, o = this.tupleByTable.get(e.table), s = o.get(a);
113
113
  s || (s = /* @__PURE__ */ new Set(), o.set(a, s)), s.add(e.id), this.subscriptions.set(e.id, {
@@ -252,7 +252,7 @@ var dt = class {
252
252
  }
253
253
  }
254
254
  for (let [e, a] of i) {
255
- let i = ht(a, (e) => t[e]);
255
+ let i = xt(a, (e) => t[e]);
256
256
  if (i === null) continue;
257
257
  let o = r.get(`${e}|${i}`);
258
258
  if (o) for (let e of o) n.add(e);
@@ -266,7 +266,7 @@ var dt = class {
266
266
  let a = this.rangeByTable.get(e);
267
267
  if (a) for (let [e, r] of a) {
268
268
  let i = t[e];
269
- if (i !== null) for (let [e, t] of r) for (let r of t) _t(i, e, r.threshold) && n.add(r.subId);
269
+ if (i !== null) for (let [e, t] of r) for (let r of t) Ct(i, e, r.threshold) && n.add(r.subId);
270
270
  }
271
271
  return n;
272
272
  }
@@ -275,7 +275,7 @@ var dt = class {
275
275
  let e = t[n.column];
276
276
  if (n.kind === "eq") {
277
277
  if (e !== n.value) return !1;
278
- } else if (!_t(e, n.op, n.threshold)) return !1;
278
+ } else if (!Ct(e, n.op, n.threshold)) return !1;
279
279
  }
280
280
  return !0;
281
281
  }
@@ -297,23 +297,23 @@ var dt = class {
297
297
  }
298
298
  return i;
299
299
  }
300
- }, yt = (e) => {
300
+ }, Tt = (e) => {
301
301
  if (e == null) return null;
302
- if (Array.isArray(e)) return e.map(yt);
302
+ if (Array.isArray(e)) return e.map(Tt);
303
303
  if (typeof e == "object") {
304
304
  let t = e, n = Object.keys(t).sort(), r = {};
305
- for (let e of n) r[e] = yt(t[e]);
305
+ for (let e of n) r[e] = Tt(t[e]);
306
306
  return r;
307
307
  }
308
308
  return e;
309
- }, bt = (e, t, n) => {
310
- let r = yt({
309
+ }, Et = (e, t, n) => {
310
+ let r = Tt({
311
311
  table: e,
312
312
  predicate: t,
313
313
  indexHint: n ?? null
314
314
  });
315
315
  return de("sha256").update(JSON.stringify(r)).digest("hex").slice(0, 16);
316
- }, xt = class {
316
+ }, Dt = class {
317
317
  matcher;
318
318
  byFingerprint = /* @__PURE__ */ new Map();
319
319
  byClient = /* @__PURE__ */ new Map();
@@ -332,7 +332,7 @@ var dt = class {
332
332
  } catch {}
333
333
  }
334
334
  subscribe(e, t, n, r) {
335
- let i = bt(t, n, r?.name), a = this.byFingerprint.get(i);
335
+ let i = Et(t, n, r?.name), a = this.byFingerprint.get(i);
336
336
  return a ? (a.subscribers.add(e), this.byClient.set(e, i), this.notifyChange(), {
337
337
  fingerprint: i,
338
338
  deduplicated: !0
@@ -390,7 +390,7 @@ var dt = class {
390
390
  });
391
391
  return e;
392
392
  }
393
- }, St = (e, t) => t.length === 0 ? e : [...e].sort((e, n) => {
393
+ }, Ot = (e, t) => t.length === 0 ? e : [...e].sort((e, n) => {
394
394
  for (let r of t) {
395
395
  let t = e[r.column], i = n[r.column];
396
396
  if (t === i) continue;
@@ -400,7 +400,7 @@ var dt = class {
400
400
  return r.direction === "asc" ? a : -a;
401
401
  }
402
402
  return 0;
403
- }), Ct = (e, t, n) => {
403
+ }), kt = (e, t, n) => {
404
404
  let r = t.split("."), i = r[0], a = r.slice(1), o = (e) => typeof e == "object" && !!e && !Array.isArray(e), s = e[i], c;
405
405
  if (a.length === 0) c = o(s) && o(n) ? {
406
406
  ...s,
@@ -418,11 +418,11 @@ var dt = class {
418
418
  ...e,
419
419
  [i]: c
420
420
  };
421
- }, wt = (e, t, n) => !e || d(e, t, n), U = (e, t) => {
421
+ }, At = (e, t, n) => !e || d(e, t, n), V = (e, t) => {
422
422
  let n = /* @__PURE__ */ new Map();
423
423
  if (!e) return n;
424
424
  for (let r of a(e)) {
425
- let e = t.get(r.descriptor.table) ?? /* @__PURE__ */ new Map(), i = U(r.descriptor.predicate, t), a = Tt(r.descriptor, e, t, i);
425
+ let e = t.get(r.descriptor.table) ?? /* @__PURE__ */ new Map(), i = V(r.descriptor.predicate, t), a = jt(r.descriptor, e, t, i);
426
426
  if (r.kind === "exists") n.set(r.descriptor, a.length);
427
427
  else {
428
428
  let e = r.descriptor.projection, t = /* @__PURE__ */ new Set();
@@ -437,15 +437,15 @@ var dt = class {
437
437
  }
438
438
  }
439
439
  return n;
440
- }, Tt = (e, t, n = /* @__PURE__ */ new Map(), r = null) => {
441
- let i = r ?? U(e.predicate, n), a = [...t.values()].filter((t) => wt(e.predicate, t, i));
440
+ }, jt = (e, t, n = /* @__PURE__ */ new Map(), r = null) => {
441
+ let i = r ?? V(e.predicate, n), a = [...t.values()].filter((t) => At(e.predicate, t, i));
442
442
  if (e.aggregations && e.aggregations.length > 0) {
443
- let t = Et(a, e.aggregations, e.groupBy);
443
+ let t = Mt(a, e.aggregations, e.groupBy);
444
444
  if (!e.having) return t;
445
- let r = U(e.having, n);
446
- return t.filter((t) => wt(e.having, t, r));
445
+ let r = V(e.having, n);
446
+ return t.filter((t) => At(e.having, t, r));
447
447
  }
448
- let o = St(a, e.order), s = e.skip ? o.slice(e.skip) : o, c = e.take === void 0 ? s : s.slice(0, e.take);
448
+ let o = Ot(a, e.order), s = e.skip ? o.slice(e.skip) : o, c = e.take === void 0 ? s : s.slice(0, e.take);
449
449
  if (!e.projection) return c;
450
450
  let l = e.projection;
451
451
  return c.map((e) => {
@@ -453,7 +453,7 @@ var dt = class {
453
453
  for (let n of l) t[n] = e[n];
454
454
  return t;
455
455
  });
456
- }, Et = (e, t, n) => {
456
+ }, Mt = (e, t, n) => {
457
457
  let r = /* @__PURE__ */ new Map();
458
458
  for (let t of e) {
459
459
  let e = {};
@@ -471,11 +471,11 @@ var dt = class {
471
471
  let i = [];
472
472
  for (let e of r.values()) {
473
473
  let n = { ...e.keyVals };
474
- for (let r of t) n[r.alias] = Dt(r, e.rows);
474
+ for (let r of t) n[r.alias] = Nt(r, e.rows);
475
475
  i.push(n);
476
476
  }
477
477
  return i;
478
- }, Dt = (e, t) => {
478
+ }, Nt = (e, t) => {
479
479
  switch (e.op) {
480
480
  case "count": return e.column === void 0 ? t.length : t.reduce((t, n) => t + +(n[e.column] !== null && n[e.column] !== void 0), 0);
481
481
  case "count-distinct": {
@@ -519,7 +519,7 @@ var dt = class {
519
519
  }
520
520
  default: throw Error(`computeAggregates: unknown op '${e.op}'`);
521
521
  }
522
- }, Ot = "\0", kt = (e, t) => e === null ? t : `${e}${Ot}${t}`, At = class e {
522
+ }, Pt = "\0", Ft = (e, t) => e === null ? t : `${e}${Pt}${t}`, It = class e {
523
523
  #e;
524
524
  #t;
525
525
  #n;
@@ -535,7 +535,7 @@ var dt = class {
535
535
  let n = t.id;
536
536
  n && e.set(n, t);
537
537
  }
538
- this.#e.set(kt(t, n), e);
538
+ this.#e.set(Ft(t, n), e);
539
539
  }
540
540
  }
541
541
  withNamespace(t) {
@@ -546,11 +546,11 @@ var dt = class {
546
546
  }, t);
547
547
  }
548
548
  #a(e) {
549
- return kt(this.#r, e);
549
+ return Ft(this.#r, e);
550
550
  }
551
551
  #o() {
552
- let e = /* @__PURE__ */ new Map(), t = this.#r === null ? null : `${this.#r}${Ot}`;
553
- for (let [n, r] of this.#e) t === null ? n.includes(Ot) || e.set(n, r) : n.startsWith(t) && e.set(n.slice(t.length), r);
552
+ let e = /* @__PURE__ */ new Map(), t = this.#r === null ? null : `${this.#r}${Pt}`;
553
+ for (let [n, r] of this.#e) t === null ? n.includes(Pt) || e.set(n, r) : n.startsWith(t) && e.set(n.slice(t.length), r);
554
554
  return e;
555
555
  }
556
556
  #s(e) {
@@ -558,7 +558,7 @@ var dt = class {
558
558
  return n || (n = /* @__PURE__ */ new Map(), this.#e.set(t, n)), n;
559
559
  }
560
560
  async query(e) {
561
- let t = Tt(e, this.#e.get(this.#a(e.table)) ?? /* @__PURE__ */ new Map(), this.#o());
561
+ let t = jt(e, this.#e.get(this.#a(e.table)) ?? /* @__PURE__ */ new Map(), this.#o());
562
562
  return _(e) ? n(t, e.eager, ie(e.table), (e) => this.query(e)) : t;
563
563
  }
564
564
  async insert(e, t) {
@@ -588,7 +588,7 @@ var dt = class {
588
588
  if (!i) return null;
589
589
  let a = i.get(t);
590
590
  if (!a) return null;
591
- let o = Ct(a, n, r);
591
+ let o = kt(a, n, r);
592
592
  return i.set(t, o), this.#t.emit("change", {
593
593
  table: e,
594
594
  op: "update",
@@ -630,7 +630,7 @@ var dt = class {
630
630
  async updateMany(e, t, n) {
631
631
  let r = this.#e.get(this.#a(e));
632
632
  if (!r) return 0;
633
- let i = U(n.where, this.#o()), a = 0;
633
+ let i = V(n.where, this.#o()), a = 0;
634
634
  for (let [o, s] of r) {
635
635
  if (!d(n.where, s, i)) continue;
636
636
  let c = {
@@ -649,7 +649,7 @@ var dt = class {
649
649
  async deleteMany(e, t) {
650
650
  let n = this.#e.get(this.#a(e));
651
651
  if (!n) return 0;
652
- let r = U(t.where, this.#o()), i = [];
652
+ let r = V(t.where, this.#o()), i = [];
653
653
  for (let [e, a] of n) d(t.where, a, r) && i.push([e, a]);
654
654
  for (let [t, r] of i) n.delete(t), this.#t.emit("change", {
655
655
  table: e,
@@ -688,7 +688,7 @@ var dt = class {
688
688
  }
689
689
  }
690
690
  async transactional(e) {
691
- let t = new jt(this.#u());
691
+ let t = new Lt(this.#u());
692
692
  try {
693
693
  let n = await e(t);
694
694
  return t.commit(), n;
@@ -724,7 +724,7 @@ var dt = class {
724
724
  allocateNumericId: (e) => this.#c(e)
725
725
  };
726
726
  }
727
- }, jt = class {
727
+ }, Lt = class {
728
728
  parent;
729
729
  overlay = /* @__PURE__ */ new Map();
730
730
  tombstones = /* @__PURE__ */ new Map();
@@ -754,7 +754,7 @@ var dt = class {
754
754
  return t || (t = /* @__PURE__ */ new Map(), this.overlay.set(e, t)), t;
755
755
  }
756
756
  async query(e) {
757
- let t = this.buildTablesView(e), r = Tt(e, this.materialise(e.table), t);
757
+ let t = this.buildTablesView(e), r = jt(e, this.materialise(e.table), t);
758
758
  return _(e) ? n(r, e.eager, ie(e.table), (e) => this.query(e)) : r;
759
759
  }
760
760
  async insert(e, t) {
@@ -793,7 +793,7 @@ var dt = class {
793
793
  async patchJson(e, t, n, r) {
794
794
  let i = this.materialise(e).get(t);
795
795
  if (!i) return null;
796
- let a = Ct(i, n, r);
796
+ let a = kt(i, n, r);
797
797
  return this.getOrCreateOverlay(e).set(t, a), this.events.push({
798
798
  table: e,
799
799
  op: "update",
@@ -814,7 +814,7 @@ var dt = class {
814
814
  }), !0;
815
815
  }
816
816
  async updateMany(e, t, n) {
817
- let r = this.materialise(e), i = U(n.where, this.buildTablesViewForPred(n.where)), a = 0;
817
+ let r = this.materialise(e), i = V(n.where, this.buildTablesViewForPred(n.where)), a = 0;
818
818
  for (let [o, s] of r) {
819
819
  if (!d(n.where, s, i)) continue;
820
820
  let r = {
@@ -831,7 +831,7 @@ var dt = class {
831
831
  return a;
832
832
  }
833
833
  async deleteMany(e, t) {
834
- let n = this.materialise(e), r = U(t.where, this.buildTablesViewForPred(t.where)), i = 0, a = this.tombstones.get(e);
834
+ let n = this.materialise(e), r = V(t.where, this.buildTablesViewForPred(t.where)), i = 0, a = this.tombstones.get(e);
835
835
  for (let [o, s] of n) d(t.where, s, r) && (this.overlay.get(e)?.delete(o), a || (a = /* @__PURE__ */ new Set(), this.tombstones.set(e, a)), a.add(o), this.events.push({
836
836
  table: e,
837
837
  op: "delete",
@@ -894,7 +894,7 @@ var dt = class {
894
894
  discard() {
895
895
  this.settled || (this.settled = !0, this.overlay.clear(), this.tombstones.clear(), this.events.length = 0);
896
896
  }
897
- }, Mt = (e) => {
897
+ }, Rt = (e) => {
898
898
  let t = {}, n = [], r = e;
899
899
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
900
900
  let e = r;
@@ -905,16 +905,23 @@ var dt = class {
905
905
  (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = e.cause;
906
906
  }
907
907
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
908
- }, Nt = (e) => {
908
+ }, zt = (e) => {
909
909
  let t = e.dbCode;
910
910
  return t === "23503" || e.dbErrno === 1452 || t === 547 || t === "SQLITE_CONSTRAINT_FOREIGNKEY";
911
- }, Pt = (e) => {
911
+ }, Bt = (e) => ({
912
+ has: (t) => Ee(e, t),
913
+ hasAny: (t) => t.some((t) => Ee(e, t)),
914
+ require: (t) => ke(e, t),
915
+ get scopes() {
916
+ return Te(e);
917
+ }
918
+ }), Vt = (e) => {
912
919
  let t = /* @__PURE__ */ new Set();
913
- return Ft(e, t), t;
914
- }, Ft = (e, t) => {
915
- if (t.add(e.table), e.eager !== void 0 && It(e.table, e.eager, t), e.setOp !== void 0) for (let n of e.setOp.queries) Ft(n, t);
916
- if (e.ctes !== void 0) for (let n of e.ctes) Ft(n.descriptor, t);
917
- }, It = (e, t, n) => {
920
+ return Ht(e, t), t;
921
+ }, Ht = (e, t) => {
922
+ if (t.add(e.table), e.eager !== void 0 && Ut(e.table, e.eager, t), e.setOp !== void 0) for (let n of e.setOp.queries) Ht(n, t);
923
+ if (e.ctes !== void 0) for (let n of e.ctes) Ht(n.descriptor, t);
924
+ }, Ut = (e, t, n) => {
918
925
  let r = p(e);
919
926
  if (r !== void 0) for (let [e, i] of Object.entries(t)) {
920
927
  let t = r[e];
@@ -922,24 +929,24 @@ var dt = class {
922
929
  let a = i === !0 ? {} : i;
923
930
  if (t.kind === "manyToMany") {
924
931
  let e = t.through().tableName, r = t.target().tableName;
925
- n.add(e), n.add(r), a.with !== void 0 && It(r, a.with, n);
932
+ n.add(e), n.add(r), a.with !== void 0 && Ut(r, a.with, n);
926
933
  } else {
927
934
  let e = t.target().tableName;
928
- n.add(e), a.with !== void 0 && It(e, a.with, n);
935
+ n.add(e), a.with !== void 0 && Ut(e, a.with, n);
929
936
  }
930
937
  }
931
- }, Lt = (e) => e.setOp !== void 0 || e.ctes !== void 0 && e.ctes.length > 0 || e.aggregations !== void 0 && e.aggregations.some((e) => e.op.startsWith("window-")), Rt = /* @__PURE__ */ new Set(["*"]), zt = (e, t) => {
938
+ }, Wt = (e) => e.setOp !== void 0 || e.ctes !== void 0 && e.ctes.length > 0 || e.aggregations !== void 0 && e.aggregations.some((e) => e.op.startsWith("window-")), Gt = /* @__PURE__ */ new Set(["*"]), H = (e, t) => {
932
939
  if (e !== void 0) {
933
940
  if ("not" in e) {
934
- zt(e.not, t);
941
+ H(e.not, t);
935
942
  return;
936
943
  }
937
944
  if ("and" in e) {
938
- for (let n of e.and) zt(n, t);
945
+ for (let n of e.and) H(n, t);
939
946
  return;
940
947
  }
941
948
  if ("or" in e) {
942
- for (let n of e.or) zt(n, t);
949
+ for (let n of e.or) H(n, t);
943
950
  return;
944
951
  }
945
952
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -948,11 +955,11 @@ var dt = class {
948
955
  }
949
956
  e.op === "exists" || e.op === "not-exists" || t.add(e.column);
950
957
  }
951
- }, W = (e, t, n) => {
958
+ }, U = (e, t, n) => {
952
959
  let r = e.get(t);
953
960
  r === void 0 && (r = /* @__PURE__ */ new Set(), e.set(t, r));
954
961
  for (let e of n) r.add(e);
955
- }, Bt = (e, t, n) => {
962
+ }, Kt = (e, t, n) => {
956
963
  let r = p(e);
957
964
  if (r !== void 0) for (let [i, a] of Object.entries(t)) {
958
965
  let t = r[i];
@@ -960,65 +967,65 @@ var dt = class {
960
967
  let o = a === !0 ? {} : a;
961
968
  if (t.kind === "manyToMany") {
962
969
  let r = t.through(), i = t.target();
963
- W(n, r.tableName, [t.sourceKey, t.targetKey]), W(n, e, ["id"]), W(n, i.tableName, ["id"]), Vt(i.tableName, o, n), o.with !== void 0 && Bt(i.tableName, o.with, n);
970
+ U(n, r.tableName, [t.sourceKey, t.targetKey]), U(n, e, ["id"]), U(n, i.tableName, ["id"]), qt(i.tableName, o, n), o.with !== void 0 && Kt(i.tableName, o.with, n);
964
971
  continue;
965
972
  }
966
973
  let s = t.target();
967
- t.foreignKey !== void 0 && W(n, s.tableName, [t.foreignKey]), t.sourceKey === void 0 ? W(n, e, ["id"]) : W(n, e, [t.sourceKey]), W(n, s.tableName, ["id"]), Vt(s.tableName, o, n), o.with !== void 0 && Bt(s.tableName, o.with, n);
974
+ t.foreignKey !== void 0 && U(n, s.tableName, [t.foreignKey]), t.sourceKey === void 0 ? U(n, e, ["id"]) : U(n, e, [t.sourceKey]), U(n, s.tableName, ["id"]), qt(s.tableName, o, n), o.with !== void 0 && Kt(s.tableName, o.with, n);
968
975
  }
969
- }, Vt = (e, t, n) => {
976
+ }, qt = (e, t, n) => {
970
977
  if (t.where !== void 0) {
971
978
  let r = /* @__PURE__ */ new Set();
972
- zt(t.where, r), W(n, e, r);
979
+ H(t.where, r), U(n, e, r);
973
980
  }
974
- t.orderBy !== void 0 && W(n, e, t.orderBy.map((e) => e.column));
981
+ t.orderBy !== void 0 && U(n, e, t.orderBy.map((e) => e.column));
975
982
  let r = m(e);
976
- r === void 0 ? W(n, e, ["*"]) : W(n, e, Object.keys(r.fields));
977
- }, Ht = (e) => {
983
+ r === void 0 ? U(n, e, ["*"]) : U(n, e, Object.keys(r.fields));
984
+ }, Jt = (e) => {
978
985
  let t = /* @__PURE__ */ new Map();
979
- if (Lt(e)) {
980
- for (let n of Pt(e)) W(t, n, ["*"]);
986
+ if (Wt(e)) {
987
+ for (let n of Vt(e)) U(t, n, ["*"]);
981
988
  return t;
982
989
  }
983
990
  let n = /* @__PURE__ */ new Set();
984
991
  if (e.projection !== void 0) for (let t of e.projection) n.add(t);
985
992
  else n.add("*");
986
- zt(e.predicate, n);
993
+ H(e.predicate, n);
987
994
  for (let t of e.order) n.add(t.column);
988
- return W(t, e.table, n), e.eager !== void 0 && Bt(e.table, e.eager, t), t;
989
- }, Ut = (e) => {
990
- if (e.op === "insert" || e.op === "delete" || e.old === null || e.new === null) return Rt;
995
+ return U(t, e.table, n), e.eager !== void 0 && Kt(e.table, e.eager, t), t;
996
+ }, Yt = (e) => {
997
+ if (e.op === "insert" || e.op === "delete" || e.old === null || e.new === null) return Gt;
991
998
  let t = /* @__PURE__ */ new Set(), n = e.old, r = e.new, i = /* @__PURE__ */ new Set([...Object.keys(n), ...Object.keys(r)]);
992
999
  for (let e of i) Object.is(n[e], r[e]) || t.add(e);
993
1000
  return t;
994
- }, Wt = (e, t) => {
1001
+ }, Xt = (e, t) => {
995
1002
  let n = t.get(e.table);
996
1003
  if (n === void 0) return !1;
997
1004
  if (n.has("*")) return !0;
998
- let r = Ut(e);
1005
+ let r = Yt(e);
999
1006
  if (r.has("*")) return !0;
1000
1007
  for (let e of r) if (n.has(e)) return !0;
1001
1008
  return !1;
1002
- }, Gt = Ie.exponential({
1009
+ }, W = Be.exponential({
1003
1010
  start: .001,
1004
1011
  factor: 2,
1005
1012
  count: 16
1006
- }), Kt = N.counter("voltro_rpc_requests_total", { description: "Total RPC handler invocations." }), qt = N.counter("voltro_rpc_errors_total", { description: "RPC handler invocations that errored." }), Jt = N.histogram("voltro_rpc_duration_seconds", Gt, "RPC handler duration in seconds."), Yt = N.counter("voltro_http_requests_total", { description: "Total HTTP route invocations." }), Xt = N.histogram("voltro_http_duration_seconds", Gt, "HTTP route duration in seconds."), Zt = N.histogram("voltro_plugin_hook_duration_seconds", Gt, "Plugin interceptor duration in seconds."), Qt = N.counter("voltro_plugin_hook_errors_total", { description: "Plugin interceptor invocations that errored." }), $t = N.counter("voltro_subscription_deliveries_total", { description: "Total subscription deliveries (snapshot + delta)." }), en = N.histogram("voltro_subscription_delivery_seconds", Gt, "Subscription delivery produce→push latency in seconds."), tn = N.gauge("voltro_subscriptions_active", { description: "Currently-open subscriptions." }), nn = (e) => {
1007
- let t = e.durationMs / 1e3, n = e.kind === "rpc" ? j.zipRight(N.increment(Kt).pipe(j.tagMetrics("tag", e.tag), j.tagMetrics("status", e.status)), j.zipRight(N.update(Jt, t).pipe(j.tagMetrics("tag", e.tag)), e.status === "error" ? N.increment(qt).pipe(j.tagMetrics("tag", e.tag)) : j.void)) : e.kind === "request" ? j.zipRight(N.increment(Yt).pipe(j.tagMetrics("route", e.tag), j.tagMetrics("status", e.status)), N.update(Xt, t).pipe(j.tagMetrics("route", e.tag))) : j.zipRight(N.update(Zt, t).pipe(j.tagMetrics("hook", e.tag)), e.status === "error" ? N.increment(Qt).pipe(j.tagMetrics("hook", e.tag)) : j.void);
1013
+ }), Zt = N.counter("voltro_rpc_requests_total", { description: "Total RPC handler invocations." }), Qt = N.counter("voltro_rpc_errors_total", { description: "RPC handler invocations that errored." }), $t = N.histogram("voltro_rpc_duration_seconds", W, "RPC handler duration in seconds."), en = N.counter("voltro_http_requests_total", { description: "Total HTTP route invocations." }), tn = N.histogram("voltro_http_duration_seconds", W, "HTTP route duration in seconds."), nn = N.histogram("voltro_plugin_hook_duration_seconds", W, "Plugin interceptor duration in seconds."), rn = N.counter("voltro_plugin_hook_errors_total", { description: "Plugin interceptor invocations that errored." }), an = N.counter("voltro_subscription_deliveries_total", { description: "Total subscription deliveries (snapshot + delta)." }), on = N.histogram("voltro_subscription_delivery_seconds", W, "Subscription delivery produce→push latency in seconds."), sn = N.gauge("voltro_subscriptions_active", { description: "Currently-open subscriptions." }), cn = (e) => {
1014
+ let t = e.durationMs / 1e3, n = e.kind === "rpc" ? j.zipRight(N.increment(Zt).pipe(j.tagMetrics("tag", e.tag), j.tagMetrics("status", e.status)), j.zipRight(N.update($t, t).pipe(j.tagMetrics("tag", e.tag)), e.status === "error" ? N.increment(Qt).pipe(j.tagMetrics("tag", e.tag)) : j.void)) : e.kind === "request" ? j.zipRight(N.increment(en).pipe(j.tagMetrics("route", e.tag), j.tagMetrics("status", e.status)), N.update(tn, t).pipe(j.tagMetrics("route", e.tag))) : j.zipRight(N.update(nn, t).pipe(j.tagMetrics("hook", e.tag)), e.status === "error" ? N.increment(rn).pipe(j.tagMetrics("hook", e.tag)) : j.void);
1008
1015
  j.runSync(n);
1009
- }, rn = (e) => e.startsWith("subscription.") ? e.slice(13) : e, an = (e) => {
1010
- let t = rn(e.label);
1011
- j.runSync(j.zipRight(N.increment($t).pipe(j.tagMetrics("tag", t), j.tagMetrics("kind", e.kind)), N.update(en, e.durationMs / 1e3).pipe(j.tagMetrics("tag", t), j.tagMetrics("kind", e.kind))));
1012
- }, on = /* @__PURE__ */ new Map(), sn = (e, t) => {
1013
- let n = rn(e), r = Math.max(0, (on.get(n) ?? 0) + t);
1014
- r === 0 ? on.delete(n) : on.set(n, r), j.runSync(N.set(tn, r).pipe(j.tagMetrics("tag", n)));
1015
- }, cn = (e, t) => N.counter(e, t === void 0 ? {} : { description: t }), ln = (e, t) => N.gauge(e, t === void 0 ? {} : { description: t }), un = (e, t = Gt, n) => N.histogram(e, t, n), dn = (e) => {
1016
+ }, ln = (e) => e.startsWith("subscription.") ? e.slice(13) : e, un = (e) => {
1017
+ let t = ln(e.label);
1018
+ j.runSync(j.zipRight(N.increment(an).pipe(j.tagMetrics("tag", t), j.tagMetrics("kind", e.kind)), N.update(on, e.durationMs / 1e3).pipe(j.tagMetrics("tag", t), j.tagMetrics("kind", e.kind))));
1019
+ }, dn = /* @__PURE__ */ new Map(), fn = (e, t) => {
1020
+ let n = ln(e), r = Math.max(0, (dn.get(n) ?? 0) + t);
1021
+ r === 0 ? dn.delete(n) : dn.set(n, r), j.runSync(N.set(sn, r).pipe(j.tagMetrics("tag", n)));
1022
+ }, pn = (e, t) => N.counter(e, t === void 0 ? {} : { description: t }), mn = (e, t) => N.gauge(e, t === void 0 ? {} : { description: t }), hn = (e, t = W, n) => N.histogram(e, t, n), gn = (e) => {
1016
1023
  let t = {};
1017
1024
  for (let n of e) t[n.key] = n.value;
1018
1025
  return t;
1019
- }, fn = N.snapshot.pipe(j.map((e) => e.map((e) => {
1020
- let t = e.metricKey.name, n = dn(e.metricKey.tags), r = P.getOrUndefined(e.metricKey.description), i = r === void 0 ? {} : { description: r }, a = e.metricState;
1021
- if (Le.isHistogramState(a)) return {
1026
+ }, _n = N.snapshot.pipe(j.map((e) => e.map((e) => {
1027
+ let t = e.metricKey.name, n = gn(e.metricKey.tags), r = P.getOrUndefined(e.metricKey.description), i = r === void 0 ? {} : { description: r }, a = e.metricState;
1028
+ if (Ve.isHistogramState(a)) return {
1022
1029
  name: t,
1023
1030
  labels: n,
1024
1031
  ...i,
@@ -1030,14 +1037,14 @@ var dt = class {
1030
1037
  sum: a.sum,
1031
1038
  count: a.count
1032
1039
  };
1033
- if (Le.isGaugeState(a)) return {
1040
+ if (Ve.isGaugeState(a)) return {
1034
1041
  name: t,
1035
1042
  labels: n,
1036
1043
  ...i,
1037
1044
  type: "gauge",
1038
1045
  value: Number(a.value)
1039
1046
  };
1040
- if (Le.isSummaryState(a)) return {
1047
+ if (Ve.isSummaryState(a)) return {
1041
1048
  name: t,
1042
1049
  labels: n,
1043
1050
  ...i,
@@ -1049,7 +1056,7 @@ var dt = class {
1049
1056
  value: t.value
1050
1057
  }] : [])
1051
1058
  };
1052
- if (Le.isFrequencyState(a)) {
1059
+ if (Ve.isFrequencyState(a)) {
1053
1060
  let e = {};
1054
1061
  for (let [t, n] of a.occurrences) e[t] = n;
1055
1062
  return {
@@ -1067,7 +1074,7 @@ var dt = class {
1067
1074
  type: "counter",
1068
1075
  value: Number(a.count)
1069
1076
  };
1070
- }))), pn = () => j.runSync(fn), G = ge({ scope: "voltro:dispatcher" }), mn = class {
1077
+ }))), vn = () => j.runSync(_n), G = Me({ scope: "voltro:dispatcher" }), yn = class {
1071
1078
  deps;
1072
1079
  subscriptionRegistry;
1073
1080
  matcher;
@@ -1077,12 +1084,12 @@ var dt = class {
1077
1084
  computedSubs = /* @__PURE__ */ new Map();
1078
1085
  computedByTable = /* @__PURE__ */ new Map();
1079
1086
  constructor(e) {
1080
- this.deps = e, this.matcher = new vt(), this.subscriptionRegistry = new xt(this.matcher), this.unsubscribeChange = e.store.onChange((e) => {
1087
+ this.deps = e, this.matcher = new wt(), this.subscriptionRegistry = new Dt(this.matcher), this.unsubscribeChange = e.store.onChange((e) => {
1081
1088
  this.handleChange(e);
1082
1089
  });
1083
1090
  }
1084
1091
  async subscribe(e, t, n, r, i, a) {
1085
- let o = `sub_${pe()}`, s = i ?? `subscription.${e.table}`, c = Pt(e), l = Ht(e);
1092
+ let o = `sub_${pe()}`, s = i ?? `subscription.${e.table}`, c = Vt(e), l = Jt(e);
1086
1093
  e.predicate !== void 0 && this.subscriptionRegistry.subscribe(o, e.table, e.predicate, r);
1087
1094
  for (let e of c) {
1088
1095
  let t = this.dependentByTable.get(e);
@@ -1099,7 +1106,7 @@ var dt = class {
1099
1106
  relevantFields: l,
1100
1107
  lastDelivered: f,
1101
1108
  cacheBinding: a
1102
- }), sn(s, 1), t({
1109
+ }), fn(s, 1), t({
1103
1110
  _tag: "snapshot",
1104
1111
  revision: 0,
1105
1112
  data: f
@@ -1115,7 +1122,7 @@ var dt = class {
1115
1122
  durationMs: p - u,
1116
1123
  rowCount: f.length
1117
1124
  }), () => {
1118
- this.subscriptions.delete(o), sn(s, -1), this.subscriptionRegistry.unsubscribe(o);
1125
+ this.subscriptions.delete(o), fn(s, -1), this.subscriptionRegistry.unsubscribe(o);
1119
1126
  for (let e of c) {
1120
1127
  let t = this.dependentByTable.get(e);
1121
1128
  t !== void 0 && (t.delete(o), t.size === 0 && this.dependentByTable.delete(e));
@@ -1130,10 +1137,10 @@ var dt = class {
1130
1137
  emit: t,
1131
1138
  context: n,
1132
1139
  label: r ?? "subscription.computed",
1133
- lastJson: hn(e.value),
1140
+ lastJson: bn(e.value),
1134
1141
  revision: 0
1135
1142
  };
1136
- this.computedSubs.set(i, o), sn(o.label, 1);
1143
+ this.computedSubs.set(i, o), fn(o.label, 1);
1137
1144
  for (let e of a) {
1138
1145
  let t = this.computedByTable.get(e);
1139
1146
  t === void 0 && (t = /* @__PURE__ */ new Set(), this.computedByTable.set(e, t)), t.add(i);
@@ -1153,7 +1160,7 @@ var dt = class {
1153
1160
  durationMs: Date.now() - s,
1154
1161
  rowCount: 1
1155
1162
  }), () => {
1156
- this.computedSubs.delete(i), sn(o.label, -1);
1163
+ this.computedSubs.delete(i), fn(o.label, -1);
1157
1164
  for (let e of a) {
1158
1165
  let t = this.computedByTable.get(e);
1159
1166
  t !== void 0 && (t.delete(i), t.size === 0 && this.computedByTable.delete(e));
@@ -1163,7 +1170,7 @@ var dt = class {
1163
1170
  async recomputeComputed(e) {
1164
1171
  let t = Date.now();
1165
1172
  try {
1166
- let n = await e.recompute(), r = hn(n);
1173
+ let n = await e.recompute(), r = bn(n);
1167
1174
  if (r === e.lastJson) return;
1168
1175
  e.lastJson = r, e.revision += 1;
1169
1176
  let i = Date.now();
@@ -1231,21 +1238,21 @@ var dt = class {
1231
1238
  G.trace("missing subscription", { subscriberId: t });
1232
1239
  continue;
1233
1240
  }
1234
- if (!Wt(e, n.relevantFields)) {
1241
+ if (!Xt(e, n.relevantFields)) {
1235
1242
  o++;
1236
1243
  continue;
1237
1244
  }
1238
1245
  let r = Date.now();
1239
1246
  try {
1240
1247
  let i = await this.deps.store.query(n.descriptor), o = n.lastDelivered;
1241
- if (gn(i, o)) {
1248
+ if (xn(i, o)) {
1242
1249
  G.trace("suppressed no-op delta", {
1243
1250
  subscriberId: t,
1244
1251
  table: e.table
1245
1252
  });
1246
1253
  continue;
1247
1254
  }
1248
- n.lastDelivered = i, this.deps.cache !== void 0 && n.cacheBinding !== void 0 && this.deps.cache.put(n.cacheBinding, Array.from(n.dependentTables), i), Te(o) && Te(i) ? n.emit({
1255
+ n.lastDelivered = i, this.deps.cache !== void 0 && n.cacheBinding !== void 0 && this.deps.cache.put(n.cacheBinding, Array.from(n.dependentTables), i), De(o) && De(i) ? n.emit({
1249
1256
  _tag: "delta",
1250
1257
  revision: a,
1251
1258
  emittedAt: a,
@@ -1281,44 +1288,44 @@ var dt = class {
1281
1288
  skipped: o
1282
1289
  });
1283
1290
  }
1284
- }, hn = (e) => {
1291
+ }, bn = (e) => {
1285
1292
  try {
1286
1293
  return JSON.stringify(e) ?? "null";
1287
1294
  } catch {
1288
1295
  return String(e);
1289
1296
  }
1290
- }, gn = (e, t) => {
1297
+ }, xn = (e, t) => {
1291
1298
  if (e === t) return !0;
1292
1299
  if (e.length !== t.length) return !1;
1293
1300
  for (let n = 0; n < e.length; n++) if (JSON.stringify(e[n]) !== JSON.stringify(t[n])) return !1;
1294
1301
  return !0;
1295
- }, _n = (e) => typeof e == "object" && !!e && e.__voltroComputed === !0, vn = 1440 * 60 * 1e3, yn = 3600 * 1e3, K = /* @__PURE__ */ new Map(), bn = /* @__PURE__ */ new Set(), xn = (e, t) => {
1302
+ }, Sn = (e) => typeof e == "object" && !!e && e.__voltroComputed === !0, Cn = 1440 * 60 * 1e3, wn = 3600 * 1e3, K = /* @__PURE__ */ new Map(), Tn = /* @__PURE__ */ new Set(), En = (e, t) => {
1296
1303
  K.set(e, {
1297
1304
  subject: t,
1298
1305
  touchedAt: Date.now()
1299
1306
  });
1300
- for (let n of bn) try {
1307
+ for (let n of Tn) try {
1301
1308
  n(e, t);
1302
1309
  } catch {}
1303
- }, Sn = (e) => {
1310
+ }, Dn = (e) => {
1304
1311
  let t = K.get(e);
1305
1312
  if (t) return t.touchedAt = Date.now(), t.subject;
1306
- }, Cn = (e) => {
1313
+ }, On = (e) => {
1307
1314
  K.delete(e);
1308
- }, wn = (e) => (bn.add(e), () => {
1309
- bn.delete(e);
1310
- }), Tn = setInterval(() => {
1311
- let e = Date.now() - vn;
1315
+ }, kn = (e) => (Tn.add(e), () => {
1316
+ Tn.delete(e);
1317
+ }), An = setInterval(() => {
1318
+ let e = Date.now() - Cn;
1312
1319
  for (let [t, n] of K) n.touchedAt < e && K.delete(t);
1313
- }, yn);
1314
- typeof Tn == "object" && Tn && "unref" in Tn && Tn.unref();
1315
- var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1320
+ }, wn);
1321
+ typeof An == "object" && An && "unref" in An && An.unref();
1322
+ var q = /* @__PURE__ */ new Map(), jn = (e, t) => {
1316
1323
  let n = q.get(e);
1317
1324
  return n || (n = /* @__PURE__ */ new Set(), q.set(e, n)), n.add(t), () => {
1318
1325
  let n = q.get(e);
1319
1326
  n && (n.delete(t), n.size === 0 && q.delete(e));
1320
1327
  };
1321
- }, Dn = (e) => {
1328
+ }, Mn = (e) => {
1322
1329
  let t = q.get(e);
1323
1330
  if (t) {
1324
1331
  for (let e of [...t]) try {
@@ -1326,15 +1333,15 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1326
1333
  } catch {}
1327
1334
  q.delete(e);
1328
1335
  }
1329
- }, On = (e) => q.get(e)?.size ?? 0, kn = () => {
1336
+ }, Nn = (e) => q.get(e)?.size ?? 0, Pn = () => {
1330
1337
  K.clear(), q.clear();
1331
- }, An = () => [...K.entries()].map(([e, t]) => ({
1338
+ }, Fn = () => [...K.entries()].map(([e, t]) => ({
1332
1339
  clientId: e,
1333
1340
  subjectType: t.subject.type,
1334
1341
  tenantId: t.subject.tenantId
1335
- })), jn = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/, Mn = (e) => `00-${e.traceId}-${e.spanId}-${e.sampled ? "01" : "00"}`, Nn = (e) => {
1342
+ })), In = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/, Ln = (e) => `00-${e.traceId}-${e.spanId}-${e.sampled ? "01" : "00"}`, Rn = (e) => {
1336
1343
  if (typeof e != "string") return null;
1337
- let t = jn.exec(e.trim().toLowerCase());
1344
+ let t = In.exec(e.trim().toLowerCase());
1338
1345
  if (t === null) return null;
1339
1346
  let [, n, r, i] = t;
1340
1347
  return n === "0".repeat(32) || r === "0".repeat(16) ? null : {
@@ -1342,14 +1349,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1342
1349
  spanId: r,
1343
1350
  sampled: (parseInt(i, 16) & 1) == 1
1344
1351
  };
1345
- }, Pn = (e) => {
1346
- let t = Nn(e);
1347
- if (t !== null) return Re.externalSpan({
1352
+ }, zn = (e) => {
1353
+ let t = Rn(e);
1354
+ if (t !== null) return He.externalSpan({
1348
1355
  traceId: t.traceId,
1349
1356
  spanId: t.spanId,
1350
1357
  sampled: t.sampled
1351
1358
  });
1352
- }, Fn = new Qe(), In = (e, t) => Fn.run(e, t), Ln = () => Fn.getStore(), Rn = (e = {}) => {
1359
+ }, Bn = new rt(), Vn = (e, t) => Bn.run(e, t), Hn = () => Bn.getStore(), Un = (e = {}) => {
1353
1360
  let t = e.random ?? Math.random, n = /* @__PURE__ */ new Map(), r = (e) => n.get(e) ?? 0;
1354
1361
  return {
1355
1362
  pick(e) {
@@ -1374,7 +1381,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1374
1381
  }));
1375
1382
  }
1376
1383
  };
1377
- }, zn = (e = {}) => {
1384
+ }, Wn = (e = {}) => {
1378
1385
  let t = e.thresholdFailures ?? 3, n = e.windowMs ?? 1e4, r = e.blackoutMs ?? 6e4, i = e.now ?? Date.now, a = /* @__PURE__ */ new Map(), o = (e) => {
1379
1386
  let t = a.get(e);
1380
1387
  return t === void 0 && (t = {
@@ -1408,7 +1415,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1408
1415
  }));
1409
1416
  }
1410
1417
  };
1411
- }, Bn = (e = {}) => {
1418
+ }, Gn = (e = {}) => {
1412
1419
  let t = e.now ?? Date.now, n = /* @__PURE__ */ new Map();
1413
1420
  return {
1414
1421
  get(e) {
@@ -1431,7 +1438,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1431
1438
  return n.size;
1432
1439
  }
1433
1440
  };
1434
- }, Vn = (e, t) => e === null ? t === void 0 ? "anon:bg" : `anon:${t}` : `subject:${e}`, Hn = (e) => {
1441
+ }, Kn = (e, t) => e === null ? t === void 0 ? "anon:bg" : `anon:${t}` : `subject:${e}`, qn = (e) => {
1435
1442
  let t = e.now ?? Date.now, n = e.keyPrefix ?? "voltro:ryw", r = e.channel ?? `${n}:bus`, i = e.onError ?? ((e, t) => {
1436
1443
  process.stderr.write(`[voltro:ryw] redis ${t} failed: ${String(e)}\n`);
1437
1444
  }), a = `${process.pid ?? 0}:${Math.random() * 1e9 | 0}:${t()}`, o = /* @__PURE__ */ new Map(), s = (e) => {
@@ -1490,7 +1497,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1490
1497
  return o.size;
1491
1498
  }
1492
1499
  };
1493
- }, Un = ge({ scope: "voltro:replication" }), Wn = new Qe(), Gn = (e, t) => Wn.run(e, t), Kn = () => Wn.getStore(), qn = class {
1500
+ }, Jn = Me({ scope: "voltro:replication" }), Yn = new rt(), Xn = (e, t) => Yn.run(e, t), Zn = () => Yn.getStore(), Qn = class {
1494
1501
  primary;
1495
1502
  replicas;
1496
1503
  adapter;
@@ -1503,10 +1510,10 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1503
1510
  recordRouting;
1504
1511
  now;
1505
1512
  constructor(e) {
1506
- this.primary = e.primary, this.replicas = e.replicas, this.adapter = e.replicationAdapter, this.policy = e.rywPolicy ?? "fallback", this.rywTtlMs = e.rywTtlMs ?? 3e4, this.rywMaxWaitMs = e.rywMaxWaitMs ?? 500, this.now = e.now ?? Date.now, this.rywStore = e.rywStore ?? Bn({ now: this.now }), this.selector = e.replicaSelector ?? Rn(), this.health = e.replicaHealth ?? zn({ now: this.now }), e.recordRouting !== void 0 && (this.recordRouting = e.recordRouting);
1513
+ this.primary = e.primary, this.replicas = e.replicas, this.adapter = e.replicationAdapter, this.policy = e.rywPolicy ?? "fallback", this.rywTtlMs = e.rywTtlMs ?? 3e4, this.rywMaxWaitMs = e.rywMaxWaitMs ?? 500, this.now = e.now ?? Date.now, this.rywStore = e.rywStore ?? Gn({ now: this.now }), this.selector = e.replicaSelector ?? Un(), this.health = e.replicaHealth ?? Wn({ now: this.now }), e.recordRouting !== void 0 && (this.recordRouting = e.recordRouting);
1507
1514
  }
1508
1515
  async query(e) {
1509
- let t = Wn.getStore(), n = t?.subjectKey ?? "anon:bg";
1516
+ let t = Yn.getStore(), n = t?.subjectKey ?? "anon:bg";
1510
1517
  if (t?.forcePrimary === !0) return this.emitRouting({
1511
1518
  target: "primary",
1512
1519
  replicaIndex: null,
@@ -1570,7 +1577,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1570
1577
  waitMs: 0
1571
1578
  }), r;
1572
1579
  } catch (r) {
1573
- return this.health.reportFailure(i, String(r)), Un.warn("replica query failed; falling back to primary", {
1580
+ return this.health.reportFailure(i, String(r)), Jn.warn("replica query failed; falling back to primary", {
1574
1581
  idx: a,
1575
1582
  err: r
1576
1583
  }), this.emitRouting({
@@ -1639,7 +1646,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1639
1646
  fallbackReason: "wait-timeout"
1640
1647
  }), this.primary.query(e);
1641
1648
  }
1642
- await Jn(10);
1649
+ await $n(10);
1643
1650
  }
1644
1651
  }
1645
1652
  async insert(e, t) {
@@ -1679,8 +1686,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1679
1686
  return await this.stampPostWrite(), r;
1680
1687
  }
1681
1688
  async transactional(e) {
1682
- let t = await Gn({
1683
- subjectKey: Wn.getStore()?.subjectKey ?? "anon:bg",
1689
+ let t = await Xn({
1690
+ subjectKey: Yn.getStore()?.subjectKey ?? "anon:bg",
1684
1691
  forcePrimary: !0
1685
1692
  }, () => this.primary.transactional(e));
1686
1693
  return await this.stampPostWrite(), t;
@@ -1696,7 +1703,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1696
1703
  }
1697
1704
  async stampPostWrite() {
1698
1705
  if (this.replicas.length === 0) return;
1699
- let e = Wn.getStore()?.subjectKey ?? "anon:bg";
1706
+ let e = Yn.getStore()?.subjectKey ?? "anon:bg";
1700
1707
  try {
1701
1708
  let t = await this.adapter.capturePrimaryPosition(this.primary);
1702
1709
  this.rywStore.set(e, {
@@ -1704,29 +1711,29 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1704
1711
  expiresAt: this.now() + this.rywTtlMs
1705
1712
  });
1706
1713
  } catch (e) {
1707
- Un.warn("failed to capture primary position; RYW skipped", { err: e });
1714
+ Jn.warn("failed to capture primary position; RYW skipped", { err: e });
1708
1715
  }
1709
1716
  }
1710
1717
  emitRouting(e) {
1711
1718
  this.recordRouting?.(e);
1712
1719
  }
1713
- }, Jn = (e) => new Promise((t) => setTimeout(t, e)), Yn = (e, t, n) => ({
1720
+ }, $n = (e) => new Promise((t) => setTimeout(t, e)), er = (e, t, n) => ({
1714
1721
  subject: e,
1715
1722
  traceId: t?.traceId ?? pe(),
1716
1723
  ...t?.spanId === void 0 ? {} : { spanId: t.spanId },
1717
1724
  ...n === void 0 ? {} : { clientId: n }
1718
- }), Xn = j.currentSpan.pipe(j.catchAll(() => j.succeed(void 0))), Zn = (e) => ({
1725
+ }), tr = j.currentSpan.pipe(j.catchAll(() => j.succeed(void 0))), nr = (e) => ({
1719
1726
  traceId: e.traceId,
1720
1727
  ...e.spanId === void 0 ? {} : { spanId: e.spanId }
1721
- }), Qn = (e, t, n) => {
1728
+ }), rr = (e, t, n) => {
1722
1729
  e !== void 0 && (e.attribute("rpc.tag", t), e.attribute("subject.type", n.type), n.tenantId !== void 0 && n.tenantId !== null && e.attribute("tenant.id", n.tenantId));
1723
- }, $n = (e, t, n, r, i, a) => L.asyncScoped((o) => j.gen(function* () {
1730
+ }, ir = (e, t, n, r, i, a) => L.asyncScoped((o) => j.gen(function* () {
1724
1731
  let s = yield* j.tryPromise(() => t.subscribe(e, (e) => {
1725
1732
  o.single(e);
1726
1733
  }, n, r, i, a)).pipe(j.matchCause({
1727
- onFailure: (e) => (ar(`subscription.${i}`, n.traceId, e), {
1734
+ onFailure: (e) => (ur(`subscription.${i}`, n.traceId, e), {
1728
1735
  ok: !1,
1729
- error: lr(e)
1736
+ error: mr(e)
1730
1737
  }),
1731
1738
  onSuccess: (e) => ({
1732
1739
  ok: !0,
@@ -1742,21 +1749,21 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1742
1749
  }
1743
1750
  let c = s.unsubscribe;
1744
1751
  if (yield* j.addFinalizer(() => j.sync(() => c())), n.clientId !== void 0) {
1745
- let e = En(n.clientId, () => {
1752
+ let e = jn(n.clientId, () => {
1746
1753
  o.end();
1747
1754
  });
1748
1755
  yield* j.addFinalizer(() => j.sync(() => e()));
1749
1756
  }
1750
- })), er = (e, t, n, r) => L.asyncScoped((i) => j.gen(function* () {
1757
+ })), ar = (e, t, n, r) => L.asyncScoped((i) => j.gen(function* () {
1751
1758
  let a = yield* j.tryPromise(() => t.subscribeComputed(e, (e) => {
1752
1759
  i.single(e._tag === "snapshot" ? {
1753
1760
  ...e,
1754
1761
  computed: !0
1755
1762
  } : e);
1756
1763
  }, n, r)).pipe(j.matchCause({
1757
- onFailure: (e) => (ar(`subscription.${r}`, n.traceId, e), {
1764
+ onFailure: (e) => (ur(`subscription.${r}`, n.traceId, e), {
1758
1765
  ok: !1,
1759
- error: lr(e)
1766
+ error: mr(e)
1760
1767
  }),
1761
1768
  onSuccess: (e) => ({
1762
1769
  ok: !0,
@@ -1772,21 +1779,21 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1772
1779
  }
1773
1780
  let o = a.unsubscribe;
1774
1781
  if (yield* j.addFinalizer(() => j.sync(() => o())), n.clientId !== void 0) {
1775
- let e = En(n.clientId, () => {
1782
+ let e = jn(n.clientId, () => {
1776
1783
  i.end();
1777
1784
  });
1778
1785
  yield* j.addFinalizer(() => j.sync(() => e()));
1779
1786
  }
1780
- })), tr = (e, t, n = "rpc.subscription", r, i) => L.unwrap(j.gen(function* () {
1781
- let a = yield* ye, o = yield* ve, s = yield* Xn;
1782
- Qn(s, n, a);
1783
- let c = Yn(a, s, o.clientId), l = Vn(a.id, o.clientId), u = Gn({ subjectKey: l }, () => In({
1787
+ })), or = (e, t, n = "rpc.subscription", r, i) => L.unwrap(j.gen(function* () {
1788
+ let a = yield* ve, o = yield* _e, s = yield* tr;
1789
+ rr(s, n, a);
1790
+ let c = er(a, s, o.clientId), l = Kn(a.id, o.clientId), u = Xn({ subjectKey: l }, () => Vn({
1784
1791
  traceId: c.traceId,
1785
1792
  ...c.spanId === void 0 ? {} : { spanId: c.spanId }
1786
1793
  }, () => e(c))), d = j.isEffect(u) ? yield* u.pipe(j.matchCause({
1787
- onFailure: (e) => (ar(`subscription.${n}`, c.traceId, e), {
1794
+ onFailure: (e) => (ur(`subscription.${n}`, c.traceId, e), {
1788
1795
  ok: !1,
1789
- error: lr(e)
1796
+ error: mr(e)
1790
1797
  }),
1791
1798
  onSuccess: (e) => ({
1792
1799
  ok: !0,
@@ -1801,38 +1808,38 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1801
1808
  error: d.error
1802
1809
  });
1803
1810
  let f = d.value;
1804
- if (_n(f)) return er(f, t, c, n);
1811
+ if (Sn(f)) return ar(f, t, c, n);
1805
1812
  let p = f, m = r?.(p);
1806
- return $n(p, t, c, m, n, i === void 0 ? void 0 : {
1813
+ return ir(p, t, c, m, n, i === void 0 ? void 0 : {
1807
1814
  key: i.scope === "subject" ? `${i.baseKey}:s:${l}` : `${i.baseKey}:global`,
1808
1815
  ttlMs: i.ttlMs,
1809
1816
  swrMs: i.swrMs
1810
1817
  });
1811
- }).pipe(j.withSpan(n, { attributes: { "framework.kind": "subscription" } }))), nr = (e, t = "rpc.stream") => L.unwrap(j.gen(function* () {
1812
- let n = yield* ye, r = yield* ve, i = yield* Xn;
1813
- Qn(i, t, n);
1814
- let a = Yn(n, i, r.clientId), o = e(a), s = j.isEffect(o) ? yield* o.pipe(j.orDie) : o;
1818
+ }).pipe(j.withSpan(n, { attributes: { "framework.kind": "subscription" } }))), sr = (e, t = "rpc.stream") => L.unwrap(j.gen(function* () {
1819
+ let n = yield* ve, r = yield* _e, i = yield* tr;
1820
+ rr(i, t, n);
1821
+ let a = er(n, i, r.clientId), o = e(a), s = j.isEffect(o) ? yield* o.pipe(j.orDie) : o;
1815
1822
  if (a.clientId === void 0) return s;
1816
1823
  let c = a.clientId;
1817
1824
  return L.unwrapScoped(j.gen(function* () {
1818
- let e = yield* je.make(), t = En(c, () => {
1819
- je.unsafeDone(e, j.void);
1825
+ let e = yield* Fe.make(), t = jn(c, () => {
1826
+ Fe.unsafeDone(e, j.void);
1820
1827
  });
1821
- return yield* j.addFinalizer(() => j.sync(() => t())), s.pipe(L.interruptWhen(je.await(e)));
1828
+ return yield* j.addFinalizer(() => j.sync(() => t())), s.pipe(L.interruptWhen(Fe.await(e)));
1822
1829
  }));
1823
- }).pipe(j.withSpan(t, { attributes: { "framework.kind": "stream" } }))), rr = ge({ scope: "voltro:rpc" }), ir = ge({ scope: "voltro:http" }), ar = (e, t, n) => {
1830
+ }).pipe(j.withSpan(t, { attributes: { "framework.kind": "stream" } }))), cr = Me({ scope: "voltro:rpc" }), lr = Me({ scope: "voltro:http" }), ur = (e, t, n) => {
1824
1831
  if (k.isInterruptedOnly(n)) return;
1825
- let r = k.squash(n), i = r?._tag, a = r instanceof Error ? r.message : r?.message ?? String(r), o = k.dieOption(n)._tag === "Some", s = Mt(r), c = {
1832
+ let r = k.squash(n), i = r?._tag, a = r instanceof Error ? r.message : r?.message ?? String(r), o = k.dieOption(n)._tag === "Some", s = Rt(r), c = {
1826
1833
  traceId: t,
1827
1834
  ...i === void 0 ? {} : { errorTag: i },
1828
1835
  ...s
1829
1836
  }, l = a === "Failed to execute statement" && typeof s.dbMessage == "string" ? s.dbMessage : a;
1830
- o ? rr.error(`${e} failed: ${l}`, c) : rr.warn(`${e} failed: ${l}`, c);
1831
- }, or = /* @__PURE__ */ new Set(["SqlError", "ResultLengthMismatch"]), sr = (e) => typeof e == "object" && !!e && typeof e._tag == "string" && or.has(e._tag), cr = (e) => ({
1837
+ o ? cr.error(`${e} failed: ${l}`, c) : cr.warn(`${e} failed: ${l}`, c);
1838
+ }, dr = /* @__PURE__ */ new Set(["SqlError", "ResultLengthMismatch"]), fr = (e) => typeof e == "object" && !!e && typeof e._tag == "string" && dr.has(e._tag), pr = (e) => ({
1832
1839
  _tag: "InternalError",
1833
1840
  message: "internal server error",
1834
1841
  traceId: e
1835
- }), lr = (e) => {
1842
+ }), mr = (e) => {
1836
1843
  let t = k.squash(e);
1837
1844
  t && typeof t == "object" && t._tag === "UnknownException" && (t = t.error ?? t.cause ?? t);
1838
1845
  let n = t && typeof t == "object" ? t : {}, r = {};
@@ -1843,19 +1850,19 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1843
1850
  ...typeof i == "string" ? { _tag: i } : {},
1844
1851
  message: typeof a == "string" ? a : String(t)
1845
1852
  };
1846
- }, ur = (e, t, n = "rpc.mutation") => j.gen(function* () {
1847
- let r = yield* ye, i = yield* ve, a = yield* Xn;
1848
- Qn(a, n, r);
1849
- let o = Yn(r, a, i.clientId), s = Gn({ subjectKey: Vn(r.id, i.clientId) }, () => In({
1853
+ }, hr = (e, t, n = "rpc.mutation") => j.gen(function* () {
1854
+ let r = yield* ve, i = yield* _e, a = yield* tr;
1855
+ rr(a, n, r);
1856
+ let o = er(r, a, i.clientId), s = Xn({ subjectKey: Kn(r.id, i.clientId) }, () => Vn({
1850
1857
  traceId: o.traceId,
1851
1858
  ...o.spanId === void 0 ? {} : { spanId: o.spanId }
1852
1859
  }, () => e(t, o)));
1853
1860
  return yield* (j.isEffect(s) ? s : j.tryPromise({
1854
1861
  try: () => Promise.resolve(s),
1855
1862
  catch: (e) => e
1856
- })).pipe(j.tapErrorCause((e) => j.sync(() => ar(n, o.traceId, e))), j.catchIf(sr, () => j.die(cr(o.traceId))), j.annotateLogs(Zn(o)));
1857
- }).pipe(j.withSpan(n, { attributes: { "framework.kind": "mutation" } })), dr = 8 * 1024 * 1024, fr = (e) => {
1858
- let t = e.port ?? 4e3, n = e.path ?? "/ws", r = Be(), i = (t) => z.HttpServerRequest.pipe(j.flatMap((t) => j.gen(function* () {
1863
+ })).pipe(j.tapErrorCause((e) => j.sync(() => ur(n, o.traceId, e))), j.catchIf(fr, () => j.die(pr(o.traceId))), j.annotateLogs(nr(o)));
1864
+ }).pipe(j.withSpan(n, { attributes: { "framework.kind": "mutation" } })), gr = 8 * 1024 * 1024, _r = (e) => {
1865
+ let t = e.port ?? 4e3, n = e.path ?? "/ws", r = We(), i = (t) => z.HttpServerRequest.pipe(j.flatMap((t) => j.gen(function* () {
1859
1866
  if (!e.inspectRoute) return B.text("inspect route not configured", { status: 404 });
1860
1867
  let n = {};
1861
1868
  for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
@@ -1931,7 +1938,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1931
1938
  let t = (e) => z.HttpServerRequest.pipe(j.flatMap((t) => j.gen(function* () {
1932
1939
  let n = {};
1933
1940
  for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
1934
- let r = t.method !== "GET" && t.method !== "HEAD" ? yield* t.text.pipe(j.orElseSucceed(() => "")) : "", i = new TextEncoder().encode(r), a = t.url.split("?")[0], o = Pn(n.traceparent), s = yield* j.promise(() => e.handle({
1941
+ let r = t.method !== "GET" && t.method !== "HEAD" ? yield* t.text.pipe(j.orElseSucceed(() => "")) : "", i = new TextEncoder().encode(r), a = t.url.split("?")[0], o = zn(n.traceparent), s = yield* j.promise(() => e.handle({
1935
1942
  method: t.method,
1936
1943
  path: a,
1937
1944
  headers: n,
@@ -1961,8 +1968,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1961
1968
  query: a,
1962
1969
  headers: n,
1963
1970
  rawBody: o
1964
- }, c = yield* j.promise(() => Xe(e, s));
1965
- c.status >= 500 && ir.warn(`${t.method} ${i} → ${c.status}`, {
1971
+ }, c = yield* j.promise(() => tt(e, s));
1972
+ c.status >= 500 && lr.warn(`${t.method} ${i} → ${c.status}`, {
1966
1973
  method: t.method,
1967
1974
  path: i,
1968
1975
  status: c.status,
@@ -1974,7 +1981,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1974
1981
  headers: l
1975
1982
  };
1976
1983
  return c.body instanceof Uint8Array ? B.uint8Array(c.body, u) : B.text(c.body ?? "", u);
1977
- })), j.tapErrorCause((t) => k.isInterruptedOnly(t) ? j.void : j.sync(() => ir.error(`${e.map((e) => e.method).join("|")} ${e[0].path} threw`, { path: e[0].path }, k.squash(t))))), n = /* @__PURE__ */ new Map();
1984
+ })), j.tapErrorCause((t) => k.isInterruptedOnly(t) ? j.void : j.sync(() => lr.error(`${e.map((e) => e.method).join("|")} ${e[0].path} threw`, { path: e[0].path }, k.squash(t))))), n = /* @__PURE__ */ new Map();
1978
1985
  for (let t of e.httpRoutes) {
1979
1986
  let e = n.get(t.path);
1980
1987
  e ? e.push(t) : n.set(t.path, [t]);
@@ -1985,13 +1992,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
1985
1992
  });
1986
1993
  l = M.mergeAll(...r);
1987
1994
  }
1988
- let u = V.layerProtocolWebsocketRouter({ path: n }), d = V.layer(e.group), f = V.layer(e.group).pipe(M.provide(V.layerProtocolHttpRouter({ path: "/rpc" })), M.provide(Je.layerJson), M.provide(e.httpHandlersLayer ?? e.handlersLayer)), p = M.scopedDiscard(j.gen(function* () {
1989
- let e = yield* V.Protocol;
1995
+ let u = $e.layerProtocolWebsocketRouter({ path: n }), d = $e.layer(e.group), f = $e.layer(e.group).pipe(M.provide($e.layerProtocolHttpRouter({ path: "/rpc" })), M.provide(Qe.layerJson), M.provide(e.httpHandlersLayer ?? e.handlersLayer)), p = M.scopedDiscard(j.gen(function* () {
1996
+ let e = yield* $e.Protocol;
1990
1997
  yield* j.forkScoped(j.gen(function* () {
1991
1998
  let t = yield* e.disconnects.take;
1992
- Cn(t), Dn(t);
1999
+ On(t), Mn(t);
1993
2000
  }).pipe(j.forever));
1994
- })), m = M.mergeAll(d, p).pipe(M.provide(u), M.provide(Je.layerJson), M.provide(e.handlersLayer)), h = M.mergeAll(m, f, s, c, l), g = e.pluginHttpInterceptor, _ = e.healthCheck, v = Number(process.env.VOLTRO_MAX_RPC_BODY_BYTES), y = e.maxRpcBodyBytes ?? (Number.isFinite(v) && v > 0 ? v : 8388608), b = { "cache-control": "no-store" }, x = (e) => j.gen(function* () {
2001
+ })), m = M.mergeAll(d, p).pipe(M.provide(u), M.provide(Qe.layerJson), M.provide(e.handlersLayer)), h = M.mergeAll(m, f, s, c, l), g = e.pluginHttpInterceptor, _ = e.healthCheck, v = Number(process.env.VOLTRO_MAX_RPC_BODY_BYTES), y = e.maxRpcBodyBytes ?? (Number.isFinite(v) && v > 0 ? v : 8388608), b = { "cache-control": "no-store" }, x = (e) => j.gen(function* () {
1995
2002
  let t = yield* z.HttpServerRequest, n = {};
1996
2003
  for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
1997
2004
  let r = t.url.indexOf("?"), i = r === -1 ? t.url : t.url.slice(0, r);
@@ -2032,13 +2039,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2032
2039
  status: l.status,
2033
2040
  ...l.headers ? { headers: l.headers } : {}
2034
2041
  });
2035
- }), S = M.unwrapEffect(R.toHttpEffect(h).pipe(j.map((e) => Ue.serve(x(e))))).pipe(M.provide(Ge.layer(() => r, { port: t })), M.provide(We.layer));
2042
+ }), S = M.unwrapEffect(R.toHttpEffect(h).pipe(j.map((e) => qe.serve(x(e))))).pipe(M.provide(Ye.layer(() => r, { port: t })), M.provide(Je.layer));
2036
2043
  e.tracerLayer && (S = S.pipe(M.provide(e.tracerLayer)));
2037
- let C = ge({ scope: "voltro:rpc" }), w = M.launch(S).pipe(j.catchAllCause((e) => j.sync(() => {
2044
+ let C = Me({ scope: "voltro:rpc" }), w = M.launch(S).pipe(j.catchAllCause((e) => j.sync(() => {
2038
2045
  C.error("rpc server crashed", {}, k.squash(e)), process.exit(1);
2039
2046
  })));
2040
- return Ke.runMain(w, { disableErrorReporting: !0 }), r;
2041
- }, pr = (e, t = 1e4) => new Promise((n, r) => {
2047
+ return Xe.runMain(w, { disableErrorReporting: !0 }), r;
2048
+ }, vr = (e, t = 1e4) => new Promise((n, r) => {
2042
2049
  if (e.listening) {
2043
2050
  n();
2044
2051
  return;
@@ -2054,13 +2061,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2054
2061
  o(e);
2055
2062
  }
2056
2063
  a = setTimeout(() => o(/* @__PURE__ */ Error(`rpc server did not bind within ${t}ms`)), t), e.on("listening", s), e.on("error", c);
2057
- }), mr = () => {
2064
+ }), yr = () => {
2058
2065
  let e = process.env.FRAMEWORK_TRACING?.toLowerCase();
2059
2066
  return e === "console" || e === "otlp" || e === "off" ? e : process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ? "otlp" : "off";
2060
- }, hr = () => {
2067
+ }, br = () => {
2061
2068
  let e = process.env.FRAMEWORK_METRICS?.toLowerCase();
2062
2069
  return e === "console" || e === "otlp" || e === "off" ? e : process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ? "otlp" : "off";
2063
- }, gr = async () => {
2070
+ }, xr = async () => {
2064
2071
  let [e, t, n, r, i] = await Promise.all([
2065
2072
  import("@opentelemetry/sdk-trace-base"),
2066
2073
  import("@opentelemetry/sdk-metrics"),
@@ -2075,7 +2082,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2075
2082
  otlpMetrics: r,
2076
2083
  nodeSdk: i
2077
2084
  };
2078
- }, _r = (e, t, n) => {
2085
+ }, Sr = (e, t, n) => {
2079
2086
  let { PeriodicExportingMetricReader: r, ConsoleMetricExporter: i, InMemoryMetricExporter: a, AggregationTemporality: o } = e.sdkMetrics;
2080
2087
  if (t === "off") return {
2081
2088
  reader: void 0,
@@ -2098,8 +2105,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2098
2105
  }),
2099
2106
  inMemory: void 0
2100
2107
  };
2101
- }, vr = async (e = {}) => {
2102
- let t = e.mode ?? mr(), n = e.metricsMode ?? hr(), r = e.extraSpanProcessors ?? [], i = e.extraMetricReaders ?? [];
2108
+ }, Cr = async (e = {}) => {
2109
+ let t = e.mode ?? yr(), n = e.metricsMode ?? br(), r = e.extraSpanProcessors ?? [], i = e.extraMetricReaders ?? [];
2103
2110
  if (t === "off" && e.traceSink === void 0 && n === "off" && r.length === 0 && i.length === 0) return {
2104
2111
  layer: M.empty,
2105
2112
  mode: t,
@@ -2108,13 +2115,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2108
2115
  metricsMode: n,
2109
2116
  inMemoryMetricExporter: void 0
2110
2117
  };
2111
- let a = await gr(), { ConsoleSpanExporter: o, InMemorySpanExporter: s, SimpleSpanProcessor: c, BatchSpanProcessor: l } = a.sdkTrace, u = t === "off", d = e.serviceName ?? process.env.OTEL_SERVICE_NAME ?? "voltro-app", f, p;
2118
+ let a = await xr(), { ConsoleSpanExporter: o, InMemorySpanExporter: s, SimpleSpanProcessor: c, BatchSpanProcessor: l } = a.sdkTrace, u = t === "off", d = e.serviceName ?? process.env.OTEL_SERVICE_NAME ?? "voltro-app", f, p;
2112
2119
  e.spanProcessor ? p = e.spanProcessor : u ? p = void 0 : t === "memory" ? (f = new s(), p = new c(f)) : p = t === "console" ? new c(new o()) : new l(new a.otlpTrace.OTLPTraceExporter());
2113
2120
  let m = [
2114
2121
  ...e.traceSink ? [e.traceSink] : [],
2115
2122
  ...p ? [p] : [],
2116
2123
  ...r
2117
- ], h = m.length === 1 ? m[0] : m, { reader: g, inMemory: _ } = _r(a, n, e.metricExportIntervalMillis ?? (process.env.OTEL_METRIC_EXPORT_INTERVAL ? Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) : 6e4)), v = [...g ? [g] : [], ...i], y = v.length === 0 ? void 0 : v.length === 1 ? v[0] : v, b = {
2124
+ ], h = m.length === 1 ? m[0] : m, { reader: g, inMemory: _ } = Sr(a, n, e.metricExportIntervalMillis ?? (process.env.OTEL_METRIC_EXPORT_INTERVAL ? Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) : 6e4)), v = [...g ? [g] : [], ...i], y = v.length === 0 ? void 0 : v.length === 1 ? v[0] : v, b = {
2118
2125
  serviceName: d,
2119
2126
  ...e.serviceVersion ? { serviceVersion: e.serviceVersion } : {},
2120
2127
  ...e.resourceAttributes ? { attributes: e.resourceAttributes } : {}
@@ -2132,18 +2139,18 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2132
2139
  metricsMode: n,
2133
2140
  inMemoryMetricExporter: _
2134
2141
  };
2135
- }, yr = {
2136
- [H.INTERNAL]: "internal",
2137
- [H.SERVER]: "server",
2138
- [H.CLIENT]: "client",
2139
- [H.PRODUCER]: "producer",
2140
- [H.CONSUMER]: "consumer"
2141
- }, br = (e) => e[0] * 1e3 + e[1] / 1e6, xr = 512, Sr = 48, Cr = (e) => {
2142
+ }, wr = {
2143
+ [it.INTERNAL]: "internal",
2144
+ [it.SERVER]: "server",
2145
+ [it.CLIENT]: "client",
2146
+ [it.PRODUCER]: "producer",
2147
+ [it.CONSUMER]: "consumer"
2148
+ }, Tr = (e) => e[0] * 1e3 + e[1] / 1e6, Er = 512, Dr = 48, Or = (e) => {
2142
2149
  let t = {}, n = 0;
2143
2150
  for (let r in e) {
2144
- if (n >= Sr) break;
2151
+ if (n >= Dr) break;
2145
2152
  let i = e[r];
2146
- if (typeof i == "string") t[r] = i.length > xr ? `${i.slice(0, xr)}…` : i;
2153
+ if (typeof i == "string") t[r] = i.length > Er ? `${i.slice(0, Er)}…` : i;
2147
2154
  else if (typeof i == "number" || typeof i == "boolean" || i == null) t[r] = i;
2148
2155
  else {
2149
2156
  let e;
@@ -2152,49 +2159,49 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2152
2159
  } catch {
2153
2160
  e = String(i);
2154
2161
  }
2155
- t[r] = e.length > xr ? `${e.slice(0, xr)}…` : e;
2162
+ t[r] = e.length > Er ? `${e.slice(0, Er)}…` : e;
2156
2163
  }
2157
2164
  n++;
2158
2165
  }
2159
2166
  return t;
2160
- }, wr = {
2161
- [$e.UNSET]: "unset",
2162
- [$e.OK]: "ok",
2163
- [$e.ERROR]: "error"
2164
- }, Tr = (e) => {
2167
+ }, kr = {
2168
+ [at.UNSET]: "unset",
2169
+ [at.OK]: "ok",
2170
+ [at.ERROR]: "error"
2171
+ }, Ar = (e) => {
2165
2172
  let t = e.spanContext(), n = e.events.length > 0 ? e.events.slice(0, 16).map((e) => ({
2166
2173
  name: e.name,
2167
- tsMs: br(e.time),
2168
- ...e.attributes ? { attributes: Cr(e.attributes) } : {}
2174
+ tsMs: Tr(e.time),
2175
+ ...e.attributes ? { attributes: Or(e.attributes) } : {}
2169
2176
  })) : void 0;
2170
2177
  return {
2171
2178
  traceId: t.traceId,
2172
2179
  spanId: t.spanId,
2173
2180
  parentSpanId: e.parentSpanContext?.spanId ?? null,
2174
2181
  name: e.name,
2175
- kind: yr[e.kind] ?? "internal",
2176
- attributes: Cr(e.attributes),
2177
- startMs: br(e.startTime),
2178
- endMs: br(e.endTime),
2179
- durationMs: br(e.duration),
2180
- status: wr[e.status.code] ?? "unset",
2182
+ kind: wr[e.kind] ?? "internal",
2183
+ attributes: Or(e.attributes),
2184
+ startMs: Tr(e.startTime),
2185
+ endMs: Tr(e.endTime),
2186
+ durationMs: Tr(e.duration),
2187
+ status: kr[e.status.code] ?? "unset",
2181
2188
  ...e.status.message ? { statusMessage: e.status.message } : {},
2182
2189
  ...n ? { events: n } : {}
2183
2190
  };
2184
- }, Er = (e) => ({
2191
+ }, jr = (e) => ({
2185
2192
  onStart: () => {},
2186
2193
  onEnd: (t) => {
2187
2194
  try {
2188
- e(Tr(t));
2195
+ e(Ar(t));
2189
2196
  } catch {}
2190
2197
  },
2191
2198
  forceFlush: () => Promise.resolve(),
2192
2199
  shutdown: () => Promise.resolve()
2193
- }), Dr = { get: (e) => Promise.resolve(process.env[e]) }, Or = Dr, kr = (e) => {
2194
- Or = e;
2195
- }, Ar = () => {
2196
- Or = Dr;
2197
- }, jr = async (e) => await Or.get(e) ?? process.env[e], Mr = (e) => process.env[e], Nr = (e, t = 6e4, n = () => Date.now()) => {
2200
+ }), Mr = { get: (e) => Promise.resolve(process.env[e]) }, Nr = Mr, Pr = (e) => {
2201
+ Nr = e;
2202
+ }, Fr = () => {
2203
+ Nr = Mr;
2204
+ }, Ir = async (e) => await Nr.get(e) ?? process.env[e], Lr = (e) => process.env[e], Rr = (e, t = 6e4, n = () => Date.now()) => {
2198
2205
  let r = /* @__PURE__ */ new Map();
2199
2206
  return { get: async (i) => {
2200
2207
  let a = r.get(i);
@@ -2205,12 +2212,12 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2205
2212
  at: n()
2206
2213
  }), o;
2207
2214
  } };
2208
- }, Pr = (e) => {
2215
+ }, zr = (e) => {
2209
2216
  let t = {
2210
2217
  accept: "application/json",
2211
2218
  ...e.headers ?? {}
2212
2219
  };
2213
- if (e.perKey) return Nr({ get: async (n) => {
2220
+ if (e.perKey) return Rr({ get: async (n) => {
2214
2221
  let r = await fetch(`${e.url.replace(/\/$/, "")}/${encodeURIComponent(n)}`, { headers: t });
2215
2222
  if (!r.ok) return;
2216
2223
  let i = await r.json();
@@ -2221,7 +2228,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2221
2228
  let t = (await a())[e];
2222
2229
  return typeof t == "string" ? t : void 0;
2223
2230
  } };
2224
- }, Fr = (e) => e === void 0 || e === "env" || typeof e == "object" && e.kind === "env" ? Dr : e.kind === "custom" ? e.backend : e.kind === "http" ? Pr(e) : Dr, Ir = (e) => /^[0-9a-f]{64}$/i.test(e) ? Buffer.from(e, "hex") : me(e, "voltro:field-encryption:v1", 32), Lr = (t) => {
2231
+ }, Br = (e) => e === void 0 || e === "env" || typeof e == "object" && e.kind === "env" ? Mr : e.kind === "custom" ? e.backend : e.kind === "http" ? zr(e) : Mr, Vr = (e) => /^[0-9a-f]{64}$/i.test(e) ? Buffer.from(e, "hex") : me(e, "voltro:field-encryption:v1", 32), Hr = (t) => {
2225
2232
  if (t.length !== 32) throw Error(`field cipher key must be 32 bytes, got ${t.length}`);
2226
2233
  return {
2227
2234
  encrypt: (n) => {
@@ -2235,29 +2242,29 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2235
2242
  return o.setAuthTag(Buffer.from(i, "base64")), Buffer.concat([o.update(Buffer.from(a, "base64")), o.final()]).toString("utf8");
2236
2243
  }
2237
2244
  };
2238
- }, Rr = (e) => Lr(Ir(e)), zr, Br = (e) => {
2239
- zr = e;
2240
- }, Vr = () => zr, J = "_voltro_idempotency", Hr = (e) => {
2245
+ }, Ur = (e) => Hr(Vr(e)), Wr, Gr = (e) => {
2246
+ Wr = e;
2247
+ }, Kr = () => Wr, J = "_voltro_idempotency", qr = (e) => {
2241
2248
  if (e == null) return null;
2242
2249
  let t = typeof e == "string" ? JSON.parse(e) : e;
2243
2250
  return t && typeof t == "object" && "status" in t ? t : null;
2244
- }, Ur = (e) => ({
2251
+ }, Jr = (e) => ({
2245
2252
  scope: e.scope,
2246
2253
  key: e.key,
2247
2254
  status: e.status === "completed" ? "completed" : "in_flight",
2248
- response: Hr(e.response),
2249
- createdAt: Oe(e.createdAt)
2250
- }), Wr = async (e, n, r) => (await e.query({
2255
+ response: qr(e.response),
2256
+ createdAt: je(e.createdAt)
2257
+ }), Yr = async (e, n, r) => (await e.query({
2251
2258
  table: J,
2252
2259
  predicate: t(u("scope", n), u("key", r)),
2253
2260
  order: [],
2254
2261
  take: 1,
2255
2262
  skip: void 0,
2256
2263
  projection: void 0
2257
- }))[0] ?? null, Gr = (e) => ({
2264
+ }))[0] ?? null, Xr = (e) => ({
2258
2265
  get: async (t, n) => {
2259
- let r = await Wr(e, t, n);
2260
- return r ? Ur(r) : null;
2266
+ let r = await Yr(e, t, n);
2267
+ return r ? Jr(r) : null;
2261
2268
  },
2262
2269
  claim: async (t, n, r, i) => {
2263
2270
  for (let a = 0; a < 2; a++) {
@@ -2273,11 +2280,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2273
2280
  createdAt: new Date(r)
2274
2281
  }, { conflictColumns: ["scope", "key"] });
2275
2282
  if (o.id === a) return "claimed";
2276
- if (r - Oe(o.createdAt) < i) return Ur(o);
2283
+ if (r - je(o.createdAt) < i) return Jr(o);
2277
2284
  await e.delete(J, o.id);
2278
2285
  }
2279
- let a = await Wr(e, t, n);
2280
- return a ? Ur(a) : {
2286
+ let a = await Yr(e, t, n);
2287
+ return a ? Jr(a) : {
2281
2288
  scope: t,
2282
2289
  key: n,
2283
2290
  status: "in_flight",
@@ -2286,36 +2293,36 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2286
2293
  };
2287
2294
  },
2288
2295
  complete: async (t, n, r, i) => {
2289
- let a = await Wr(e, t, n);
2296
+ let a = await Yr(e, t, n);
2290
2297
  a && await e.update(J, a.id, {
2291
2298
  status: "completed",
2292
2299
  response: r
2293
2300
  });
2294
2301
  },
2295
2302
  release: async (t, n) => {
2296
- let r = await Wr(e, t, n);
2303
+ let r = await Yr(e, t, n);
2297
2304
  r && await e.delete(J, r.id);
2298
2305
  }
2299
- }), Y = "_voltro_kv", Kr = (e) => {
2306
+ }), Y = "_voltro_kv", Zr = (e) => {
2300
2307
  if (e == null) return null;
2301
2308
  if (e instanceof Date) return e.getTime();
2302
2309
  if (typeof e == "number") return e;
2303
2310
  let t = Date.parse(String(e));
2304
2311
  return Number.isNaN(t) ? null : t;
2305
- }, qr = (e, t) => {
2306
- let n = Kr(e.expiresAt);
2312
+ }, Qr = (e, t) => {
2313
+ let n = Zr(e.expiresAt);
2307
2314
  return n !== null && n <= t;
2308
- }, Jr = (e) => e === null ? null : JSON.parse(e), Yr = async (e, t) => (await e.query({
2315
+ }, $r = (e) => e === null ? null : JSON.parse(e), ei = async (e, t) => (await e.query({
2309
2316
  table: Y,
2310
2317
  predicate: u("key", t),
2311
2318
  order: [],
2312
2319
  take: 1,
2313
2320
  skip: void 0,
2314
2321
  projection: void 0
2315
- }))[0] ?? null, Xr = (e) => {
2322
+ }))[0] ?? null, ti = (e) => {
2316
2323
  let n = (e, t, n) => j.tryPromise({
2317
2324
  try: n,
2318
- catch: (n) => new tt({
2325
+ catch: (n) => new st({
2319
2326
  operation: e,
2320
2327
  key: t,
2321
2328
  cause: String(n)
@@ -2323,8 +2330,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2323
2330
  });
2324
2331
  return {
2325
2332
  get: (t) => n("get", t, async () => {
2326
- let n = await Yr(e, t);
2327
- return n === null ? P.none() : qr(n, Date.now()) ? (await e.delete(Y, n.id), P.none()) : P.some(Jr(n.value));
2333
+ let n = await ei(e, t);
2334
+ return n === null ? P.none() : Qr(n, Date.now()) ? (await e.delete(Y, n.id), P.none()) : P.some($r(n.value));
2328
2335
  }),
2329
2336
  set: (t, r, i) => n("set", t, async () => {
2330
2337
  let n = Date.now(), a = i?.ttlMs !== void 0 && i.ttlMs > 0 ? new Date(n + i.ttlMs) : null, o = f({
@@ -2347,14 +2354,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2347
2354
  });
2348
2355
  }),
2349
2356
  delete: (t) => n("delete", t, async () => {
2350
- let n = await Yr(e, t);
2357
+ let n = await ei(e, t);
2351
2358
  if (n === null) return !1;
2352
- let r = !qr(n, Date.now());
2359
+ let r = !Qr(n, Date.now());
2353
2360
  return await e.delete(Y, n.id), r;
2354
2361
  }),
2355
2362
  has: (t) => n("has", t, async () => {
2356
- let n = await Yr(e, t);
2357
- return n === null ? !1 : qr(n, Date.now()) ? (await e.delete(Y, n.id), !1) : !0;
2363
+ let n = await ei(e, t);
2364
+ return n === null ? !1 : Qr(n, Date.now()) ? (await e.delete(Y, n.id), !1) : !0;
2358
2365
  }),
2359
2366
  list: (r) => n("list", "", async () => {
2360
2367
  let n = Date.now(), i = T(x("expiresAt"), h("expiresAt", new Date(n))), a = r === "" ? i : t(o("key", r), i), s = await e.query({
@@ -2365,7 +2372,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2365
2372
  skip: void 0,
2366
2373
  projection: void 0
2367
2374
  }), c = [];
2368
- for (let e of s) qr(e, n) || (r === "" || e.key.startsWith(r)) && c.push(e.key);
2375
+ for (let e of s) Qr(e, n) || (r === "" || e.key.startsWith(r)) && c.push(e.key);
2369
2376
  return c;
2370
2377
  }),
2371
2378
  clear: () => n("clear", "", async () => {
@@ -2375,8 +2382,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2375
2382
  } });
2376
2383
  })
2377
2384
  };
2378
- }, Zr = async ({ store: e, env: t = process.env }) => {
2379
- let n = (t.KV_BACKEND ?? "database").toLowerCase(), r = n === "redis" ? "redis" : n === "memory" ? "memory" : "database", i = r === "redis" ? at(t.KV_KEY_PREFIX ? { keyPrefix: t.KV_KEY_PREFIX } : {}).pipe(M.provide(rt)) : r === "memory" ? it() : M.succeed(nt, nt.of(Xr(e))), a = Fe.make(et.Default.pipe(M.provide(i))), o = await a.runPromise(et);
2385
+ }, ni = async ({ store: e, env: t = process.env }) => {
2386
+ let n = (t.KV_BACKEND ?? "database").toLowerCase(), r = n === "redis" ? "redis" : n === "memory" ? "memory" : "database", i = r === "redis" ? dt(t.KV_KEY_PREFIX ? { keyPrefix: t.KV_KEY_PREFIX } : {}).pipe(M.provide(lt)) : r === "memory" ? ut() : M.succeed(ct, ct.of(ti(e))), a = ze.make(ot.Default.pipe(M.provide(i))), o = await a.runPromise(ot);
2380
2387
  return {
2381
2388
  kv: {
2382
2389
  get: (e) => a.runPromise(o.get(e)).then((e) => P.getOrUndefined(e)),
@@ -2391,7 +2398,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2391
2398
  backend: r,
2392
2399
  dispose: () => a.dispose()
2393
2400
  };
2394
- }, Qr = {
2401
+ }, ri = {
2395
2402
  get: () => Promise.resolve(void 0),
2396
2403
  getOrElse: (e, t) => Promise.resolve(t()),
2397
2404
  set: () => Promise.resolve(),
@@ -2399,7 +2406,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2399
2406
  has: () => Promise.resolve(!1),
2400
2407
  list: () => Promise.resolve([]),
2401
2408
  clear: () => Promise.resolve()
2402
- }, $r = "_voltro_api_keys", ei = (e) => de("sha256").update(e, "utf8").digest("hex"), ti = (e = "voltro_") => `${e}${fe(30).toString("base64url")}`, ni = (e) => ({
2409
+ }, ii = "_voltro_api_keys", ai = (e) => de("sha256").update(e, "utf8").digest("hex"), oi = (e = "voltro_") => `${e}${fe(30).toString("base64url")}`, si = (e) => ({
2403
2410
  id: e.id,
2404
2411
  name: e.name,
2405
2412
  keyPrefix: e.keyPrefix,
@@ -2409,17 +2416,17 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2409
2416
  expiresAt: e.expiresAt,
2410
2417
  revokedAt: e.revokedAt,
2411
2418
  createdAt: e.createdAt
2412
- }), ri = (e, t) => e.revokedAt === null && (e.expiresAt === null || e.expiresAt > t), ii = (e, t = {}) => {
2419
+ }), ci = (e, t) => e.revokedAt === null && (e.expiresAt === null || e.expiresAt > t), li = (e, t = {}) => {
2413
2420
  let n = t.prefix ?? "voltro_", r = async (t) => {
2414
- let r = ti(n), i = f({
2421
+ let r = oi(n), i = f({
2415
2422
  kind: "typeid",
2416
2423
  prefix: "apikey"
2417
- }, $r), a = t.scopes ?? [], o = t.expiresAt == null ? null : t.expiresAt instanceof Date ? t.expiresAt.getTime() : t.expiresAt;
2424
+ }, ii), a = t.scopes ?? [], o = t.expiresAt == null ? null : t.expiresAt instanceof Date ? t.expiresAt.getTime() : t.expiresAt;
2418
2425
  return await e.insert({
2419
2426
  id: i,
2420
2427
  tenantId: t.tenantId ?? null,
2421
2428
  name: t.name,
2422
- hashedKey: ei(r),
2429
+ hashedKey: ai(r),
2423
2430
  keyPrefix: r.slice(0, n.length + 6),
2424
2431
  scopes: a,
2425
2432
  lastUsedAt: null,
@@ -2437,7 +2444,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2437
2444
  };
2438
2445
  }, i = async (t, n = Date.now()) => {
2439
2446
  let r = await e.findByHash(t);
2440
- return !r || !ri(r, n) ? null : (await e.patch(r.id, { lastUsedAt: n }), {
2447
+ return !r || !ci(r, n) ? null : (await e.patch(r.id, { lastUsedAt: n }), {
2441
2448
  id: r.id,
2442
2449
  tenantId: r.tenantId ?? "",
2443
2450
  scopes: r.scopes ?? []
@@ -2446,7 +2453,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2446
2453
  return {
2447
2454
  issue: r,
2448
2455
  resolveByHash: i,
2449
- verify: (e, t) => i(ei(e), t),
2456
+ verify: (e, t) => i(ai(e), t),
2450
2457
  revoke: async (t, n = Date.now()) => await e.findById(t) ? (await e.patch(t, { revokedAt: n }), !0) : !1,
2451
2458
  rotate: async (t, n = Date.now()) => {
2452
2459
  let i = await e.findById(t);
@@ -2457,9 +2464,9 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2457
2464
  createdBy: i.createdBy
2458
2465
  })) : null;
2459
2466
  },
2460
- list: async (t) => (await e.listByTenant(t)).map(ni)
2467
+ list: async (t) => (await e.listByTenant(t)).map(si)
2461
2468
  };
2462
- }, ai = () => {
2469
+ }, ui = () => {
2463
2470
  let e = /* @__PURE__ */ new Map();
2464
2471
  return {
2465
2472
  insert: async (t) => {
@@ -2476,21 +2483,21 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2476
2483
  });
2477
2484
  }
2478
2485
  };
2479
- }, oi = (e) => e == null ? null : e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : null, si = (e) => ({
2486
+ }, di = (e) => e == null ? null : e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : null, fi = (e) => ({
2480
2487
  id: String(e.id),
2481
2488
  tenantId: e.tenantId ?? null,
2482
2489
  name: String(e.name),
2483
2490
  hashedKey: String(e.hashedKey),
2484
2491
  keyPrefix: String(e.keyPrefix),
2485
2492
  scopes: e.scopes ?? null,
2486
- lastUsedAt: oi(e.lastUsedAt),
2487
- expiresAt: oi(e.expiresAt),
2488
- revokedAt: oi(e.revokedAt),
2493
+ lastUsedAt: di(e.lastUsedAt),
2494
+ expiresAt: di(e.expiresAt),
2495
+ revokedAt: di(e.revokedAt),
2489
2496
  createdBy: e.createdBy ?? null,
2490
- createdAt: oi(e.createdAt) ?? 0
2491
- }), ci = (e) => {
2497
+ createdAt: di(e.createdAt) ?? 0
2498
+ }), pi = (e) => {
2492
2499
  let t = async (t) => await e.query({
2493
- table: $r,
2500
+ table: ii,
2494
2501
  predicate: t,
2495
2502
  order: [],
2496
2503
  take: void 0,
@@ -2508,32 +2515,32 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2508
2515
  };
2509
2516
  return {
2510
2517
  insert: async (t) => {
2511
- await e.insert($r, n(t));
2518
+ await e.insert(ii, n(t));
2512
2519
  },
2513
2520
  findByHash: async (e) => {
2514
2521
  let n = await t(u("hashedKey", e));
2515
- return n[0] ? si(n[0]) : null;
2522
+ return n[0] ? fi(n[0]) : null;
2516
2523
  },
2517
2524
  findById: async (e) => {
2518
2525
  let n = await t(u("id", e));
2519
- return n[0] ? si(n[0]) : null;
2526
+ return n[0] ? fi(n[0]) : null;
2520
2527
  },
2521
- listByTenant: async (e) => (await t(e === null ? void 0 : u("tenantId", e))).map(si).filter((t) => e === null || t.tenantId === e),
2528
+ listByTenant: async (e) => (await t(e === null ? void 0 : u("tenantId", e))).map(fi).filter((t) => e === null || t.tenantId === e),
2522
2529
  patch: async (t, r) => {
2523
- await e.update($r, t, n(r));
2530
+ await e.update(ii, t, n(r));
2524
2531
  }
2525
2532
  };
2526
- }, li = (e, t = {}) => ot({
2533
+ }, mi = (e, t = {}) => ft({
2527
2534
  id: "voltro-apikey",
2528
2535
  ...t.prefix ? { prefix: t.prefix } : {},
2529
2536
  resolveKey: (t) => e.resolveByHash(t)
2530
- }), ui = (e) => {
2537
+ }), hi = (e) => {
2531
2538
  let t = e.subject;
2532
2539
  return {
2533
2540
  id: t.id ?? null,
2534
2541
  tenantId: t.tenantId ?? null
2535
2542
  };
2536
- }, di = (e, t = "/v1/api-keys") => {
2543
+ }, gi = (e, t = "/v1/api-keys") => {
2537
2544
  let n = I.Struct({
2538
2545
  id: I.String,
2539
2546
  name: I.String,
@@ -2546,11 +2553,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2546
2553
  createdAt: I.Number
2547
2554
  });
2548
2555
  return [
2549
- Ye({
2556
+ et({
2550
2557
  method: "POST",
2551
2558
  path: `${t}/issue`,
2552
2559
  summary: "Issue an API key (the token is returned ONCE).",
2553
- guards: [Ze(_e)],
2560
+ guards: [nt(ge)],
2554
2561
  input: I.Struct({ body: I.Struct({
2555
2562
  name: I.String,
2556
2563
  scopes: I.optional(I.Array(I.String)),
@@ -2562,7 +2569,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2562
2569
  keyPrefix: I.String
2563
2570
  }),
2564
2571
  handler: async (t, n) => {
2565
- let r = t.body, i = ui(n), a = await e.issue({
2572
+ let r = t.body, i = hi(n), a = await e.issue({
2566
2573
  tenantId: i.tenantId,
2567
2574
  name: r.name,
2568
2575
  ...r.scopes ? { scopes: r.scopes } : {},
@@ -2576,41 +2583,41 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2576
2583
  };
2577
2584
  }
2578
2585
  }),
2579
- Ye({
2586
+ et({
2580
2587
  method: "GET",
2581
2588
  path: t,
2582
2589
  summary: "List the caller tenant's API keys (no secrets).",
2583
- guards: [Ze(_e)],
2590
+ guards: [nt(ge)],
2584
2591
  input: I.Struct({}),
2585
2592
  output: I.Struct({ keys: I.Array(n) }),
2586
- handler: async (t, n) => ({ keys: [...await e.list(ui(n).tenantId)] })
2593
+ handler: async (t, n) => ({ keys: [...await e.list(hi(n).tenantId)] })
2587
2594
  }),
2588
- Ye({
2595
+ et({
2589
2596
  method: "POST",
2590
2597
  path: `${t}/revoke`,
2591
2598
  summary: "Revoke an API key by id.",
2592
- guards: [Ze(_e)],
2599
+ guards: [nt(ge)],
2593
2600
  input: I.Struct({ body: I.Struct({ id: I.String }) }),
2594
2601
  output: I.Struct({ ok: I.Boolean }),
2595
2602
  handler: async (t, n) => ({ ok: await e.revoke(t.body.id) })
2596
2603
  })
2597
2604
  ];
2598
- }, fi = (e) => qe.make(e.name, {
2605
+ }, _i = (e) => Ze.make(e.name, {
2599
2606
  payload: e.payloadSchema,
2600
- success: Ce,
2607
+ success: Se,
2601
2608
  error: e.errorSchema
2602
2609
  }), X = (e, t) => ({
2603
2610
  id: t,
2604
2611
  workflowName: e,
2605
2612
  executionId: t,
2606
2613
  status: "running"
2607
- }), pi = X, mi = (e) => {
2614
+ }), vi = X, yi = (e) => {
2608
2615
  let t = k.failureOption(e), n = t._tag === "Some" ? t.value : k.squash(e);
2609
2616
  return {
2610
2617
  tag: n && typeof n == "object" && "_tag" in n ? String(n._tag) : null,
2611
2618
  message: n?.message ?? String(n)
2612
2619
  };
2613
- }, hi = (e, t, n) => {
2620
+ }, bi = (e, t, n) => {
2614
2621
  if (n === void 0) return {
2615
2622
  id: t,
2616
2623
  workflowName: e,
@@ -2625,7 +2632,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2625
2632
  };
2626
2633
  if (typeof n == "object" && n && n._tag === "Complete") {
2627
2634
  let r = n.exit;
2628
- return Pe.isSuccess(r) ? {
2635
+ return Re.isSuccess(r) ? {
2629
2636
  id: t,
2630
2637
  workflowName: e,
2631
2638
  executionId: t,
@@ -2636,7 +2643,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2636
2643
  workflowName: e,
2637
2644
  executionId: t,
2638
2645
  status: "failed",
2639
- error: mi(r.cause)
2646
+ error: yi(r.cause)
2640
2647
  };
2641
2648
  }
2642
2649
  return {
@@ -2645,15 +2652,15 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2645
2652
  executionId: t,
2646
2653
  status: "running"
2647
2654
  };
2648
- }, gi = (e) => new Promise((t) => setTimeout(t, e)), _i = (e) => {
2655
+ }, xi = (e) => new Promise((t) => setTimeout(t, e)), Si = (e) => {
2649
2656
  let t = new Map(e.workflows.map((e) => [e.definition.name, e.definition])), n = (e) => {
2650
2657
  let n = t.get(e);
2651
2658
  if (!n) throw Error(`Unknown workflow: ${e}`);
2652
2659
  return n;
2653
2660
  }, r = async (t, r) => {
2654
2661
  let i = n(t);
2655
- return hi(t, r, await e.runEffect(i.poll(r)));
2656
- }, i = async () => e.runEffect(st()), a = async (t, r, i) => {
2662
+ return bi(t, r, await e.runEffect(i.poll(r)));
2663
+ }, i = async () => e.runEffect(pt()), a = async (t, r, i) => {
2657
2664
  let a = n(t), o;
2658
2665
  return i?.callerContext !== void 0 && (o = await e.runEffect(a.executionId(r)), await e.rememberStartContext?.(t, o, i.callerContext)), i?.wait ? (await e.runEffect(a.execute(r)), X(t, o ?? await e.runEffect(a.executionId(r)))) : X(t, await e.runEffect(a.execute(r, { discard: !0 })));
2659
2666
  };
@@ -2693,7 +2700,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2693
2700
  let e = await r(i, a);
2694
2701
  if (e.status === "succeeded" || e.status === "failed" || e.status === "cancelled") return e;
2695
2702
  if (o?.timeoutMs !== void 0 && Date.now() - s >= o.timeoutMs) throw Error(`Timed out waiting for workflow '${i}' run '${a}'`);
2696
- await gi(c);
2703
+ await xi(c);
2697
2704
  }
2698
2705
  }),
2699
2706
  cancel: async (t, r) => {
@@ -2731,7 +2738,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2731
2738
  return e.retry(t, n);
2732
2739
  }
2733
2740
  };
2734
- }, vi = (e, t) => ({
2741
+ }, Ci = (e, t) => ({
2735
2742
  ...e,
2736
2743
  start: async (n, r, i) => {
2737
2744
  if (i?.wait) throw Error("ctx.workflows.start(..., { wait: true }) is not allowed inside a mutation transaction; start the workflow and wait after commit.");
@@ -2746,7 +2753,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2746
2753
  run: async () => {
2747
2754
  throw Error("ctx.workflows.run(...) is not allowed inside a mutation transaction; use ctx.workflows.start(...) so the workflow starts after commit.");
2748
2755
  }
2749
- }), yi = (e, t) => ({
2756
+ }), wi = (e, t) => ({
2750
2757
  ...e,
2751
2758
  start: (n, r, i) => e.start(n, r, {
2752
2759
  ...i,
@@ -2760,7 +2767,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2760
2767
  ...i,
2761
2768
  callerContext: t
2762
2769
  })
2763
- }), bi = (e) => {
2770
+ }), Ti = (e) => {
2764
2771
  let t = () => {
2765
2772
  let t = e();
2766
2773
  if (!t) throw Error("Workflow runtime is not ready yet");
@@ -2781,11 +2788,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2781
2788
  listRuns: ((e) => t().listRuns(e)),
2782
2789
  retry: (e, n) => t().retry(e, n)
2783
2790
  };
2784
- }, xi = (e, t) => {
2791
+ }, Ei = (e, t) => {
2785
2792
  let n = {};
2786
2793
  for (let r of e) n[r.definition.name] = (e) => (t ? j.promise(() => t.start(r.definition.name, e)) : r.definition.execute(e, { discard: !0 }).pipe(j.map((e) => X(r.definition.name, e)))).pipe(j.withSpan(`workflow.${r.definition.name}`, { attributes: { "framework.kind": "workflow" } }));
2787
2794
  return n;
2788
- }, Si = (e, t, n) => e.map((e) => e.definition.toLayer(((r, i) => {
2795
+ }, Di = (e, t, n) => e.map((e) => e.definition.toLayer(((r, i) => {
2789
2796
  let a = t.resolveStartContext?.(e.definition.name, i);
2790
2797
  return (a === void 0 ? j.succeed(void 0) : j.promise(() => Promise.resolve(a))).pipe(j.flatMap((a) => {
2791
2798
  let o = e.buildExecute(t.buildContext(a, {
@@ -2796,13 +2803,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2796
2803
  }));
2797
2804
  return (n?.(e, o, a) ?? o)(r, i);
2798
2805
  }));
2799
- }))), Ci = (e) => ({
2806
+ }))), Oi = (e) => ({
2800
2807
  _tag: "workflowEventTrigger",
2801
2808
  ...e
2802
- }), wi = Ci, Ti = (e) => typeof e == "object" && !!e && e._tag === "workflowEventTrigger", Ei = () => {
2809
+ }), ki = Oi, Ai = (e) => typeof e == "object" && !!e && e._tag === "workflowEventTrigger", ji = () => {
2803
2810
  let e = globalThis.crypto;
2804
2811
  return typeof e?.randomUUID == "function" ? e.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
2805
- }, Di = (e) => `${e}_${Ei()}`, Oi = (e) => e.id ?? `${e.event}->${e.workflow}`, ki = E("_voltro_workflow_events", {
2812
+ }, Mi = (e) => `${e}_${ji()}`, Ni = (e) => e.id ?? `${e.event}->${e.workflow}`, Pi = E("_voltro_workflow_events", {
2806
2813
  id: v({ prefix: "wfe" }),
2807
2814
  name: D(),
2808
2815
  payload: S(),
@@ -2810,7 +2817,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2810
2817
  subject: S().nullable(),
2811
2818
  traceId: D().nullable(),
2812
2819
  occurredAt: O().default("now")
2813
- }).index(["name"]).index(["source"]).index(["occurredAt"]).reactive(), Ai = E("_voltro_workflow_event_deliveries", {
2820
+ }).index(["name"]).index(["source"]).index(["occurredAt"]).reactive(), Fi = E("_voltro_workflow_event_deliveries", {
2814
2821
  id: v({ prefix: "wfed" }),
2815
2822
  eventId: D(),
2816
2823
  eventName: D(),
@@ -2828,8 +2835,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2828
2835
  errorMessage: D().nullable(),
2829
2836
  createdAt: O().default("now"),
2830
2837
  completedAt: O().nullable()
2831
- }).index(["eventId"]).index(["eventName"]).index(["triggerId"]).index(["workflowName"]).index(["status"]).reactive(), ji = (e) => {
2832
- let t = e.makeId ?? Di, n = /* @__PURE__ */ new Map();
2838
+ }).index(["eventId"]).index(["eventName"]).index(["triggerId"]).index(["workflowName"]).index(["status"]).reactive(), Ii = (e) => {
2839
+ let t = e.makeId ?? Mi, n = /* @__PURE__ */ new Map();
2833
2840
  for (let t of e.triggers) {
2834
2841
  let e = n.get(t.event);
2835
2842
  e ? e.push(t) : n.set(t.event, [t]);
@@ -2870,7 +2877,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2870
2877
  });
2871
2878
  let p = o(n), m = [];
2872
2879
  for (let o of p) {
2873
- let s = Oi(o), l = o.workflow, d;
2880
+ let s = Ni(o), l = o.workflow, d;
2874
2881
  try {
2875
2882
  let p = o.idempotencyKey?.(f) ?? `${c}:${s}`;
2876
2883
  if (o.filter && !await o.filter(f)) {
@@ -2973,11 +2980,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
2973
2980
  triggered: m
2974
2981
  };
2975
2982
  } };
2976
- }, Mi = M.effect(Ve.HttpClient, j.map(Ve.HttpClient, (e) => e.pipe(Ve.mapRequestEffect((e) => j.currentSpan.pipe(j.map((t) => e.headers.traceparent === void 0 ? He.setHeader(e, "traceparent", Mn({
2983
+ }, Li = M.effect(Ge.HttpClient, j.map(Ge.HttpClient, (e) => e.pipe(Ge.mapRequestEffect((e) => j.currentSpan.pipe(j.map((t) => e.headers.traceparent === void 0 ? Ke.setHeader(e, "traceparent", Ln({
2977
2984
  traceId: t.traceId,
2978
2985
  spanId: t.spanId,
2979
2986
  sampled: t.sampled
2980
- })) : e), j.catchAll(() => j.succeed(e))))))), Ni = "voltro/audit", Pi = "voltro/softDelete", Fi = "voltro/tenant", Ii = (e) => {
2987
+ })) : e), j.catchAll(() => j.succeed(e))))))), Ri = "voltro/audit", zi = "voltro/softDelete", Bi = "voltro/tenant", Vi = (e) => {
2981
2988
  let t = /* @__PURE__ */ new Map();
2982
2989
  for (let n of e) {
2983
2990
  let e = /* @__PURE__ */ new Set();
@@ -3020,26 +3027,26 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3020
3027
  return !1;
3021
3028
  },
3022
3029
  idScheme: (e) => t.get(e)?.idScheme,
3023
- defaultFactories: (e) => t.get(e)?.defaultFactories ?? Li,
3024
- computedFields: (e) => t.get(e)?.computedFields ?? Ri,
3030
+ defaultFactories: (e) => t.get(e)?.defaultFactories ?? Hi,
3031
+ computedFields: (e) => t.get(e)?.computedFields ?? Ui,
3025
3032
  insertSchema: (e) => t.get(e)?.insertSchema,
3026
3033
  validatePatchSchema: (e) => t.get(e)?.validatePatchSchema
3027
3034
  };
3028
- }, Li = /* @__PURE__ */ new Map(), Ri = /* @__PURE__ */ new Map(), zi = Ii([]), Bi = class extends Error {
3035
+ }, Hi = /* @__PURE__ */ new Map(), Ui = /* @__PURE__ */ new Map(), Wi = Vi([]), Gi = class extends Error {
3029
3036
  table;
3030
3037
  _tag = "NoRowFound";
3031
3038
  constructor(e) {
3032
3039
  super(`expected exactly one row in '${e}', found none`), this.table = e, this.name = "NoRowFound";
3033
3040
  }
3034
- }, Vi = class extends Error {
3041
+ }, Ki = class extends Error {
3035
3042
  table;
3036
3043
  expected;
3037
3044
  _tag = "OptimisticLockError";
3038
3045
  constructor(e, t) {
3039
3046
  super(`optimistic lock failed on '${e}': expected version ${t}`), this.table = e, this.expected = t, this.name = "OptimisticLockError";
3040
3047
  }
3041
- }, Hi = (e) => typeof e == "object" && !!e && ("and" in e || "or" in e || "not" in e || "op" in e || "subquery" in e), Ui = (e) => {
3042
- if (e.length === 1 && Hi(e[0])) return e[0];
3048
+ }, qi = (e) => typeof e == "object" && !!e && ("and" in e || "or" in e || "not" in e || "op" in e || "subquery" in e), Ji = (e) => {
3049
+ if (e.length === 1 && qi(e[0])) return e[0];
3043
3050
  let t = e[0];
3044
3051
  if (e.length === 2) return u(t, e[1]);
3045
3052
  let n = e[1], r = e[2];
@@ -3057,11 +3064,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3057
3064
  case "fts": return o(t, r);
3058
3065
  default: return u(t, r);
3059
3066
  }
3060
- }, Wi = (e) => {
3067
+ }, Yi = (e) => {
3061
3068
  let t = m(e);
3062
3069
  if (t === void 0) throw Error(`unknown table '${e}' — is it declared with table()?`);
3063
3070
  return ne(t);
3064
- }, Gi = class e {
3071
+ }, Xi = class e {
3065
3072
  backend;
3066
3073
  scope;
3067
3074
  table;
@@ -3075,7 +3082,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3075
3082
  return new e(this.backend, this.scope, this.table, t, this.skipTenant, this.skipSoftDelete);
3076
3083
  }
3077
3084
  where(...e) {
3078
- return this.clone(this.query.where(Ui(e)));
3085
+ return this.clone(this.query.where(Ji(e)));
3079
3086
  }
3080
3087
  orderBy(e, t = "asc") {
3081
3088
  return this.clone(this.query.orderBy(e, t));
@@ -3122,7 +3129,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3122
3129
  }
3123
3130
  async one() {
3124
3131
  let e = await this.maybeOne();
3125
- if (e === null) throw new Bi(this.table);
3132
+ if (e === null) throw new Gi(this.table);
3126
3133
  return e;
3127
3134
  }
3128
3135
  async count() {
@@ -3135,7 +3142,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3135
3142
  get descriptor() {
3136
3143
  return this.scopedQuery().descriptor;
3137
3144
  }
3138
- }, Ki = class {
3145
+ }, Zi = class {
3139
3146
  backend;
3140
3147
  scope;
3141
3148
  table;
@@ -3146,7 +3153,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3146
3153
  this.backend = e, this.scope = t, this.table = n;
3147
3154
  }
3148
3155
  where(...e) {
3149
- let n = Ui(e);
3156
+ let n = Ji(e);
3150
3157
  return this.predicate = this.predicate ? t(this.predicate, n) : n, this;
3151
3158
  }
3152
3159
  unscoped() {
@@ -3170,13 +3177,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3170
3177
  }
3171
3178
  async set(e) {
3172
3179
  let t = await this.backend.updateMany(this.table, e, { where: this.scopedWhere() });
3173
- if (this.expectedVersion !== void 0 && t === 0) throw new Vi(this.table, this.expectedVersion);
3180
+ if (this.expectedVersion !== void 0 && t === 0) throw new Ki(this.table, this.expectedVersion);
3174
3181
  return t;
3175
3182
  }
3176
3183
  async restore() {
3177
3184
  return this.backend.updateMany(this.table, { deletedAt: null }, { where: this.scopedWhere() });
3178
3185
  }
3179
- }, qi = class {
3186
+ }, Qi = class {
3180
3187
  backend;
3181
3188
  scope;
3182
3189
  table;
@@ -3186,7 +3193,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3186
3193
  this.backend = e, this.scope = t, this.table = n;
3187
3194
  }
3188
3195
  where(...e) {
3189
- let n = Ui(e);
3196
+ let n = Ji(e);
3190
3197
  return this.predicate = this.predicate ? t(this.predicate, n) : n, this;
3191
3198
  }
3192
3199
  unscoped() {
@@ -3207,42 +3214,46 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3207
3214
  async hard() {
3208
3215
  return this.backend.deleteMany(this.table, { where: this.scopedWhere() });
3209
3216
  }
3210
- }, Ji = (e, t) => ({
3211
- select: (n) => new Gi(e, t, n, Wi(n)),
3212
- updateWhere: (n) => new Ki(e, t, n),
3213
- deleteWhere: (n) => new qi(e, t, n)
3214
- }), Yi = class extends I.TaggedError()("TenantScopeViolation", {
3217
+ }, $i = (e, t) => ({
3218
+ select: (n) => new Xi(e, t, n, Yi(n)),
3219
+ updateWhere: (n) => new Zi(e, t, n),
3220
+ deleteWhere: (n) => new Qi(e, t, n)
3221
+ }), ea = class extends I.TaggedError()("TenantScopeViolation", {
3215
3222
  table: I.String,
3216
3223
  reason: I.String
3217
- }) {}, Xi = class extends I.TaggedError()("StoreOperationFailed", {
3224
+ }) {}, ta = class extends I.TaggedError()("StoreOperationFailed", {
3218
3225
  operation: I.String,
3219
3226
  table: I.String,
3220
3227
  cause: I.String
3221
- }) {}, Zi = class extends I.TaggedError()("TableValidationFailed", {
3228
+ }) {}, na = class extends I.TaggedError()("TableValidationFailed", {
3222
3229
  table: I.String,
3223
3230
  summary: I.String,
3224
3231
  issues: I.Array(I.Struct({
3225
3232
  path: I.String,
3226
3233
  message: I.String
3227
3234
  }))
3228
- }) {}, Qi = "id", $i = "cannot insert into tenant-scoped table without an authenticated tenant — subject.tenantId is null. Either authenticate first or pass tenantId explicitly in the row (admin tooling).", ea = (e) => {
3229
- throw new Yi({
3235
+ }) {}, ra = "id", ia = (e, t) => {
3236
+ let n = {};
3237
+ for (let r of t) e[r] !== void 0 && (n[r] = e[r]);
3238
+ return n;
3239
+ }, aa = "cannot insert into tenant-scoped table without an authenticated tenant — subject.tenantId is null. Either authenticate first or pass tenantId explicitly in the row (admin tooling).", oa = (e) => {
3240
+ throw new ea({
3230
3241
  table: e,
3231
- reason: $i
3242
+ reason: aa
3232
3243
  });
3233
- }, ta = (e, n) => {
3244
+ }, sa = (e, n) => {
3234
3245
  let r = n.subject.id, i = n.subject.tenantId, a = (e, t) => {
3235
3246
  let a = { ...t }, o = n.schemaRegistry, s = o.idScheme(e);
3236
- if (s !== void 0 && a[Qi] == null) if (s.kind === "numeric") delete a[Qi];
3247
+ if (s !== void 0 && a[ra] == null) if (s.kind === "numeric") delete a[ra];
3237
3248
  else {
3238
3249
  let t = f(s, e);
3239
- t !== null && (a[Qi] = t);
3250
+ t !== null && (a[ra] = t);
3240
3251
  }
3241
3252
  if (o.hasAudit(e)) {
3242
3253
  let e = /* @__PURE__ */ new Date();
3243
3254
  "createdAt" in a || (a.createdAt = e), "updatedAt" in a || (a.updatedAt = e), r !== null && ("createdBy" in a || (a.createdBy = r), "updatedBy" in a || (a.updatedBy = r));
3244
3255
  }
3245
- o.hasTenant(e) && ("tenantId" in a || (i === null && ea(e), a.tenantId = i));
3256
+ o.hasTenant(e) && ("tenantId" in a || (i === null && oa(e), a.tenantId = i));
3246
3257
  let c = o.defaultFactories(e);
3247
3258
  if (c.size > 0) for (let [e, t] of c) (!(e in a) || a[e] === void 0) && (a[e] = t());
3248
3259
  let l = o.computedFields(e);
@@ -3257,10 +3268,10 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3257
3268
  try {
3258
3269
  return await r();
3259
3270
  } catch (n) {
3260
- let r = Mt(n);
3261
- if (Nt(r)) {
3271
+ let r = Rt(n);
3272
+ if (zt(r)) {
3262
3273
  let n = t.tenantId, i = `${r.dbConstraint ?? ""} ${r.dbColumn ?? ""} ${r.dbMessage ?? ""} ${r.dbCauseChain ?? ""}`.toLowerCase();
3263
- if (i.includes("tenantid") || /\btenants\b/.test(i) || n != null && i.includes(String(n).toLowerCase())) throw new Yi({
3274
+ if (i.includes("tenantid") || /\btenants\b/.test(i) || n != null && i.includes(String(n).toLowerCase())) throw new ea({
3264
3275
  table: e,
3265
3276
  reason: n == null ? "write references a tenant that does not exist" : `tenant '${String(n)}' does not exist — seed the row in \`tenants\`, or fix how the request resolved this tenant (subject.tenantId / the x-tenant header / the dev TENANT fallback)`
3266
3277
  });
@@ -3281,11 +3292,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3281
3292
  if (r === void 0) return t;
3282
3293
  let i = I.decodeUnknownEither(r)(t);
3283
3294
  if (i._tag === "Right") return t;
3284
- let a = lt.formatErrorSync(i.left).map((e) => ({
3295
+ let a = ht.formatErrorSync(i.left).map((e) => ({
3285
3296
  path: e.path.length === 0 ? "<root>" : e.path.join("."),
3286
3297
  message: e.message
3287
3298
  })), o = a[0];
3288
- throw new Zi({
3299
+ throw new na({
3289
3300
  table: e,
3290
3301
  summary: o === void 0 ? "patch validation failed" : `${o.path}: ${o.message}`,
3291
3302
  issues: a
@@ -3298,20 +3309,20 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3298
3309
  if (r === void 0) return t;
3299
3310
  let i = I.decodeUnknownEither(r)(t);
3300
3311
  if (i._tag === "Right") return t;
3301
- let a = lt.formatErrorSync(i.left).map((e) => ({
3312
+ let a = ht.formatErrorSync(i.left).map((e) => ({
3302
3313
  path: e.path.length === 0 ? "<root>" : e.path.join("."),
3303
3314
  message: e.message
3304
3315
  })), o = a[0];
3305
- throw new Zi({
3316
+ throw new na({
3306
3317
  table: e,
3307
3318
  summary: o === void 0 ? "row validation failed" : `${o.path}: ${o.message}`,
3308
3319
  issues: a
3309
3320
  });
3310
3321
  }, v = n.dialect, y = (e, t) => {
3311
3322
  let n = m(e);
3312
- return l(v ? oe(t, n, v) : t, n, Vr());
3323
+ return l(v ? oe(t, n, v) : t, n, Kr());
3313
3324
  }, b = (e, t) => {
3314
- let n = m(e), r = s(t, n, Vr());
3325
+ let n = m(e), r = s(t, n, Kr());
3315
3326
  return v ? c(r, n, v) : r;
3316
3327
  }, S = (e) => {
3317
3328
  let r = e.table, a = e.predicate;
@@ -3336,7 +3347,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3336
3347
  let n = (await e.query({
3337
3348
  table: t,
3338
3349
  predicate: {
3339
- column: Qi,
3350
+ column: ra,
3340
3351
  op: "eq",
3341
3352
  value: r
3342
3353
  },
@@ -3357,7 +3368,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3357
3368
  }), ae = async (e, t) => ne(e, {
3358
3369
  ...t,
3359
3370
  where: re(e, t.where)
3360
- }), se = Ji({
3371
+ }), se = $i({
3361
3372
  query: C,
3362
3373
  updateMany: T,
3363
3374
  deleteMany: ne,
@@ -3383,6 +3394,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3383
3394
  select: se.select,
3384
3395
  update: ((e, t, n) => t === void 0 ? se.updateWhere(e) : ee(e, t, n)),
3385
3396
  delete: ((e, t) => t === void 0 ? se.deleteWhere(e) : te(e, t)),
3397
+ applyDefined: ia,
3386
3398
  hardDelete: async (t, n) => e.delete(t, n),
3387
3399
  updateMany: ie,
3388
3400
  deleteMany: ae,
@@ -3394,34 +3406,34 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3394
3406
  let i = a(t, n), o = await d(t, i, () => e.insertIgnore(t, y(t, _(t, i)), r));
3395
3407
  return b(t, [o])[0];
3396
3408
  },
3397
- transactional: (t) => e.transactional(async (e) => t(ta(e, n))),
3409
+ transactional: (t) => e.transactional(async (e) => t(sa(e, n))),
3398
3410
  ...e.raw ? { raw: e.raw.bind(e) } : {},
3399
3411
  onChange: (t) => e.onChange(t),
3400
3412
  injectExternalChange: (t) => e.injectExternalChange(t),
3401
3413
  ...e.changeScope === void 0 ? {} : { changeScope: e.changeScope }
3402
3414
  };
3403
- }, na = class extends I.TaggedError()("CircuitOpen", {
3415
+ }, ca = class extends I.TaggedError()("CircuitOpen", {
3404
3416
  name: I.String,
3405
3417
  retryAfterMs: I.Number
3406
- }) {}, ra = {
3418
+ }) {}, la = {
3407
3419
  tag: "closed",
3408
3420
  failureCount: 0,
3409
3421
  halfOpenSuccesses: 0,
3410
3422
  openedAt: 0
3411
- }, ia = { make: (e) => j.gen(function* () {
3412
- let t = e.name ?? "circuit", n = Me.toMillis(Me.decode(e.resetTimeout)), r = e.halfOpenSuccessThreshold ?? 1, i = e.isFailure ?? (() => !0), a = yield* F.make(ra), o = j.gen(function* () {
3423
+ }, ua = { make: (e) => j.gen(function* () {
3424
+ let t = e.name ?? "circuit", n = Ie.toMillis(Ie.decode(e.resetTimeout)), r = e.halfOpenSuccessThreshold ?? 1, i = e.isFailure ?? (() => !0), a = yield* F.make(la), o = j.gen(function* () {
3413
3425
  let e = yield* F.get(a);
3414
3426
  if (e.tag === "half-open") {
3415
3427
  let t = e.halfOpenSuccesses + 1;
3416
- yield* F.set(a, t >= r ? ra : {
3428
+ yield* F.set(a, t >= r ? la : {
3417
3429
  ...e,
3418
3430
  halfOpenSuccesses: t
3419
3431
  });
3420
3432
  return;
3421
3433
  }
3422
- e.failureCount !== 0 && (yield* F.set(a, ra));
3434
+ e.failureCount !== 0 && (yield* F.set(a, la));
3423
3435
  }), s = j.gen(function* () {
3424
- let t = yield* ke.currentTimeMillis, n = yield* F.get(a);
3436
+ let t = yield* Ne.currentTimeMillis, n = yield* F.get(a);
3425
3437
  if (n.tag === "half-open" || n.tag === "open") {
3426
3438
  yield* F.set(a, {
3427
3439
  tag: "open",
@@ -3444,7 +3456,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3444
3456
  }), c = j.gen(function* () {
3445
3457
  let e = yield* F.get(a);
3446
3458
  if (e.tag !== "open") return null;
3447
- let t = (yield* ke.currentTimeMillis) - e.openedAt;
3459
+ let t = (yield* Ne.currentTimeMillis) - e.openedAt;
3448
3460
  return t >= n ? (yield* F.set(a, {
3449
3461
  tag: "half-open",
3450
3462
  failureCount: 0,
@@ -3457,7 +3469,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3457
3469
  if (k.isInterruptedOnly(e)) return j.void;
3458
3470
  let t = k.failureOption(e), n = t._tag === "Some" ? t.value : void 0;
3459
3471
  return i(n) ? s : j.void;
3460
- })) : yield* j.fail(new na({
3472
+ })) : yield* j.fail(new ca({
3461
3473
  name: t,
3462
3474
  retryAfterMs: n
3463
3475
  }));
@@ -3466,38 +3478,38 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3466
3478
  value: F.get(a).pipe(j.map((e) => e.tag)),
3467
3479
  enumerable: !0
3468
3480
  }), Object.defineProperty(u, "reset", {
3469
- value: F.set(a, ra),
3481
+ value: F.set(a, la),
3470
3482
  enumerable: !0
3471
3483
  }), u;
3472
- }) }, aa, oa = (e) => {
3473
- aa = e;
3474
- }, sa = () => {
3475
- aa = void 0;
3476
- }, ca = async (e, t = {}) => {
3477
- let n = t.scopes === void 0 ? De(t.id ?? "system") : De(t.id ?? "system", t.scopes), r = t.store ?? aa?.dataStore, i = t.schemaRegistry ?? aa?.schemaRegistry, a = t.dialect ?? aa?.dialect;
3484
+ }) }, da, fa = (e) => {
3485
+ da = e;
3486
+ }, pa = () => {
3487
+ da = void 0;
3488
+ }, ma = async (e, t = {}) => {
3489
+ let n = t.scopes === void 0 ? Ae(t.id ?? "system") : Ae(t.id ?? "system", t.scopes), r = t.store ?? da?.dataStore, i = t.schemaRegistry ?? da?.schemaRegistry, a = t.dialect ?? da?.dialect;
3478
3490
  if (r === void 0 || i === void 0) throw Error("runAsSystem: no data store available — register one at boot via setSystemStoreHandle({ dataStore, schemaRegistry }) or pass { store, schemaRegistry } in the options.");
3479
3491
  return e({
3480
3492
  subject: n,
3481
- store: ta(r, {
3493
+ store: sa(r, {
3482
3494
  subject: n,
3483
3495
  schemaRegistry: i,
3484
3496
  ...a === void 0 ? {} : { dialect: a }
3485
3497
  })
3486
3498
  });
3487
- }, la = class extends Ae.Tag("@voltro/EffectStore")() {}, ua = (e, t) => (n) => n instanceof Yi ? n : new Xi({
3499
+ }, ha = class extends Pe.Tag("@voltro/EffectStore")() {}, ga = (e, t) => (n) => n instanceof ea ? n : new ta({
3488
3500
  operation: e,
3489
3501
  table: t,
3490
3502
  cause: String(n)
3491
- }), da = (e, t, n) => j.tryPromise({
3503
+ }), _a = (e, t, n) => j.tryPromise({
3492
3504
  try: n,
3493
- catch: ua(e, t)
3494
- }), fa = (e) => M.succeed(la, {
3495
- query: (t) => da("query", t.table, () => e.query(t)),
3496
- insert: (t, n) => da("insert", t, () => e.insert(t, n)),
3497
- update: (t, n, r) => da("update", t, () => e.update(t, n, r)),
3498
- delete: (t, n) => da("delete", t, () => e.delete(t, n)),
3499
- hardDelete: (t, n) => da("hardDelete", t, () => e.hardDelete(t, n))
3500
- }), pa = (e) => {
3505
+ catch: ga(e, t)
3506
+ }), va = (e) => M.succeed(ha, {
3507
+ query: (t) => _a("query", t.table, () => e.query(t)),
3508
+ insert: (t, n) => _a("insert", t, () => e.insert(t, n)),
3509
+ update: (t, n, r) => _a("update", t, () => e.update(t, n, r)),
3510
+ delete: (t, n) => _a("delete", t, () => e.delete(t, n)),
3511
+ hardDelete: (t, n) => _a("hardDelete", t, () => e.hardDelete(t, n))
3512
+ }), ya = (e) => {
3501
3513
  let { currentRegion: t, replicaRegions: n, inner: r } = e, i = (e) => {
3502
3514
  if (t === void 0) return {
3503
3515
  sameRegion: [],
@@ -3525,7 +3537,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3525
3537
  return r.loadSnapshot();
3526
3538
  }
3527
3539
  };
3528
- }, ma = (e = process.env) => {
3540
+ }, ba = (e = process.env) => {
3529
3541
  for (let t of [
3530
3542
  "VOLTRO_REGION",
3531
3543
  "AWS_REGION",
@@ -3537,7 +3549,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3537
3549
  let n = e[t];
3538
3550
  if (typeof n == "string" && n.length > 0) return n;
3539
3551
  }
3540
- }, ha = () => {
3552
+ }, xa = () => {
3541
3553
  let e = {
3542
3554
  primary: 0,
3543
3555
  lagByReplica: /* @__PURE__ */ new Map()
@@ -3562,27 +3574,27 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3562
3574
  e.lagByReplica.set(t, n);
3563
3575
  }
3564
3576
  };
3565
- }, ga = Symbol.for("@voltro/ScheduleDefinition"), _a = (e) => typeof e == "object" && !!e && ga in e, va = 30 * 6e4, ya = (e) => {
3577
+ }, Sa = Symbol.for("@voltro/ScheduleDefinition"), Ca = (e) => typeof e == "object" && !!e && Sa in e, wa = 30 * 6e4, Ta = (e) => {
3566
3578
  let t = A.parse(e.cron, e.timezone);
3567
- if (Ne.isLeft(t)) throw Error(`defineSchedule("${e.name}"): invalid cron expression "${e.cron}" (tz="${e.timezone}") — ${String(t.left)}`);
3579
+ if (Le.isLeft(t)) throw Error(`defineSchedule("${e.name}"): invalid cron expression "${e.cron}" (tz="${e.timezone}") — ${String(t.left)}`);
3568
3580
  if (!e.timezone || e.timezone.trim() === "") throw Error(`defineSchedule("${e.name}"): timezone is required (e.g. "UTC", "Europe/Berlin")`);
3569
3581
  if (e.handler === void 0 && e.workflow === void 0) throw Error(`defineSchedule("${e.name}"): define either handler or workflow`);
3570
3582
  return {
3571
3583
  ...e,
3572
3584
  onOverlap: e.onOverlap ?? "skip",
3573
3585
  backfill: e.backfill ?? "skip",
3574
- maxRuntimeMs: e.maxRuntimeMs ?? va,
3575
- [ga]: !0
3586
+ maxRuntimeMs: e.maxRuntimeMs ?? wa,
3587
+ [Sa]: !0
3576
3588
  };
3577
- }, ba = (e) => A.unsafeParse(e.cron, e.timezone), xa = (e, t = /* @__PURE__ */ new Date()) => A.next(ba(e), t), Z = "_voltro_wakeups", Sa = (e) => `${e.tenantId}:${e.kind}:${e.refId}`, Ca = (e) => ({
3589
+ }, Ea = (e) => A.unsafeParse(e.cron, e.timezone), Da = (e, t = /* @__PURE__ */ new Date()) => A.next(Ea(e), t), Z = "_voltro_wakeups", Oa = (e) => `${e.tenantId}:${e.kind}:${e.refId}`, ka = (e) => ({
3578
3590
  tenantId: String(e.tenantId),
3579
3591
  kind: String(e.kind),
3580
3592
  refId: String(e.refId),
3581
3593
  wakeAt: e.wakeAt instanceof Date ? e.wakeAt : new Date(String(e.wakeAt)),
3582
3594
  status: e.status === "fired" ? "fired" : "pending"
3583
- }), wa = async (e, t) => {
3595
+ }), Aa = async (e, t) => {
3584
3596
  await e.upsert(Z, {
3585
- id: Sa(t),
3597
+ id: Oa(t),
3586
3598
  tenantId: t.tenantId,
3587
3599
  kind: t.kind,
3588
3600
  refId: t.refId,
@@ -3592,7 +3604,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3592
3604
  conflictColumns: ["id"],
3593
3605
  update: ["wakeAt", "status"]
3594
3606
  });
3595
- }, Ta = async (e, t) => e.delete(Z, Sa(t)), Ea = async (e, t) => await e.update(Z, Sa(t), { status: "fired" }) !== null, Da = (e, t) => ({ and: [{
3607
+ }, ja = async (e, t) => e.delete(Z, Oa(t)), Ma = async (e, t) => await e.update(Z, Oa(t), { status: "fired" }) !== null, Na = (e, t) => ({ and: [{
3596
3608
  column: "id",
3597
3609
  op: "eq",
3598
3610
  value: e
@@ -3600,16 +3612,16 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3600
3612
  column: "status",
3601
3613
  op: "eq",
3602
3614
  value: t
3603
- }] }), Oa = async (e, t) => await e.updateMany(Z, { status: "fired" }, { where: Da(Sa(t), "pending") }) > 0, ka = async (e, t) => {
3604
- await e.updateMany(Z, { status: "pending" }, { where: Da(Sa(t), "fired") });
3605
- }, Aa = {
3615
+ }] }), Pa = async (e, t) => await e.updateMany(Z, { status: "fired" }, { where: Na(Oa(t), "pending") }) > 0, Fa = async (e, t) => {
3616
+ await e.updateMany(Z, { status: "pending" }, { where: Na(Oa(t), "fired") });
3617
+ }, Ia = {
3606
3618
  column: "status",
3607
3619
  op: "eq",
3608
3620
  value: "pending"
3609
- }, ja = async (e, t) => {
3621
+ }, La = async (e, t) => {
3610
3622
  let n = {
3611
3623
  table: Z,
3612
- predicate: Aa,
3624
+ predicate: Ia,
3613
3625
  order: [{
3614
3626
  column: "wakeAt",
3615
3627
  direction: "asc"
@@ -3618,18 +3630,18 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3618
3630
  skip: void 0,
3619
3631
  projection: void 0
3620
3632
  };
3621
- return (await e.query(n)).map(Ca);
3622
- }, Ma = async (e, t, n = 500) => {
3623
- let r = await ja(e, n), i = t.getTime();
3633
+ return (await e.query(n)).map(ka);
3634
+ }, Ra = async (e, t, n = 500) => {
3635
+ let r = await La(e, n), i = t.getTime();
3624
3636
  return r.filter((e) => e.wakeAt.getTime() <= i);
3625
- }, Na = async (e) => (await ja(e, 1))[0] ?? null, Pa = {
3637
+ }, za = async (e) => (await La(e, 1))[0] ?? null, Ba = {
3626
3638
  column: "status",
3627
3639
  op: "eq",
3628
3640
  value: "fired"
3629
- }, Fa = async (e, t = {}) => {
3641
+ }, Va = async (e, t = {}) => {
3630
3642
  let n = {
3631
3643
  table: Z,
3632
- predicate: Pa,
3644
+ predicate: Ba,
3633
3645
  order: [{
3634
3646
  column: "wakeAt",
3635
3647
  direction: "asc"
@@ -3640,12 +3652,12 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3640
3652
  }, r = await e.query(n), i = t.firedOlderThan?.getTime(), a = 0;
3641
3653
  for (let t of r) i !== void 0 && (t.wakeAt instanceof Date ? t.wakeAt : new Date(String(t.wakeAt))).getTime() >= i || await e.delete(Z, String(t.id)) && a++;
3642
3654
  return a;
3643
- }, Ia = {
3655
+ }, Ha = {
3644
3656
  kind: "single",
3645
3657
  tryClaim: async () => !0
3646
- }, La = "_voltro_schedule_claims", Ra = (e, t, n) => {
3658
+ }, Ua = "_voltro_schedule_claims", Wa = (e, t, n) => {
3647
3659
  let r = async (t) => (await e.query({
3648
- table: La,
3660
+ table: Ua,
3649
3661
  order: [],
3650
3662
  predicate: void 0,
3651
3663
  projection: ["id"],
@@ -3660,7 +3672,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3660
3672
  if (await r(s)) return !1;
3661
3673
  } catch {}
3662
3674
  try {
3663
- return await e.insert(La, {
3675
+ return await e.insert(Ua, {
3664
3676
  id: s,
3665
3677
  scheduleName: i,
3666
3678
  bucket: o,
@@ -3678,12 +3690,12 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3678
3690
  }
3679
3691
  }
3680
3692
  };
3681
- }, za = "_voltro_schedule_runs", Ba = async (e, t) => {
3693
+ }, Ga = "_voltro_schedule_runs", Ka = async (e, t) => {
3682
3694
  let { store: n, coordinator: r, buildContext: i, replicaId: a, log: o, onRunEvent: s, interceptFire: c } = t, l = t.dormancy === "sleep", u = t.dormancyTenantId ?? "default", d = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Set(), p = /* @__PURE__ */ new Map(), m = !1, h = new Map(e.map((e) => [e.name, e])), g = (e, t) => {
3683
- s?.(e, Ha(t));
3695
+ s?.(e, Ja(t));
3684
3696
  }, _ = async (e, t, r, i, s, c) => {
3685
3697
  try {
3686
- let o = `sr_${pe()}`, l = await n.insert(za, {
3698
+ let o = `sr_${pe()}`, l = await n.insert(Ga, {
3687
3699
  id: o,
3688
3700
  name: e.name,
3689
3701
  status: i,
@@ -3708,7 +3720,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3708
3720
  }
3709
3721
  }, v = async (e, t) => {
3710
3722
  try {
3711
- let r = await n.update(za, e, t);
3723
+ let r = await n.update(Ga, e, t);
3712
3724
  r && g("update", r);
3713
3725
  } catch (t) {
3714
3726
  o.warn("schedule: failed to record run finish", {
@@ -3719,7 +3731,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3719
3731
  }, y = async (e) => {
3720
3732
  try {
3721
3733
  let t = await n.query({
3722
- table: za,
3734
+ table: Ga,
3723
3735
  predicate: {
3724
3736
  _tag: "leaf",
3725
3737
  column: "status",
@@ -3784,7 +3796,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3784
3796
  let n = Q(t).includes("exceeded maxRuntimeMs");
3785
3797
  s && await v(s, {
3786
3798
  status: "failed",
3787
- errorTag: n ? "timeout" : Va(t),
3799
+ errorTag: n ? "timeout" : qa(t),
3788
3800
  errorMessage: Q(t),
3789
3801
  completedAt: /* @__PURE__ */ new Date(),
3790
3802
  durationMs: Date.now() - l
@@ -3792,7 +3804,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3792
3804
  name: e.name,
3793
3805
  reason: Q(t),
3794
3806
  timeout: n
3795
- }), Ee({
3807
+ }), Oe({
3796
3808
  error: t,
3797
3809
  source: "schedule",
3798
3810
  name: e.name,
@@ -3841,8 +3853,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3841
3853
  }
3842
3854
  }, C = async (e) => {
3843
3855
  try {
3844
- let t = A.next(ba(e), /* @__PURE__ */ new Date());
3845
- await wa(n, {
3856
+ let t = A.next(Ea(e), /* @__PURE__ */ new Date());
3857
+ await Aa(n, {
3846
3858
  tenantId: u,
3847
3859
  kind: "schedule",
3848
3860
  refId: e.name,
@@ -3856,7 +3868,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3856
3868
  }
3857
3869
  }, w = 2147483647, ee = (e) => {
3858
3870
  if (m) return;
3859
- let n = ba(e), r = A.next(n, /* @__PURE__ */ new Date()), i = () => {
3871
+ let n = Ea(e), r = A.next(n, /* @__PURE__ */ new Date()), i = () => {
3860
3872
  if (m) return;
3861
3873
  let n = r.getTime() - Date.now();
3862
3874
  if (n > w) {
@@ -3878,7 +3890,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3878
3890
  let r;
3879
3891
  try {
3880
3892
  let t = (await n.query({
3881
- table: za,
3893
+ table: Ga,
3882
3894
  order: [{
3883
3895
  column: "scheduledAt",
3884
3896
  direction: "desc"
@@ -3897,7 +3909,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3897
3909
  return;
3898
3910
  }
3899
3911
  if (!r) return;
3900
- let i = ba(e), a = [], s = A.next(i, r), c = Date.now();
3912
+ let i = Ea(e), a = [], s = A.next(i, r), c = Date.now();
3901
3913
  for (; s.getTime() < c && a.length < 1e3;) a.push(s), s = A.next(i, s);
3902
3914
  if (a.length !== 0) if (o.info("schedule: backfill", {
3903
3915
  name: e.name,
@@ -3942,11 +3954,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3942
3954
  d.clear(), o.info("scheduler: stopped");
3943
3955
  }
3944
3956
  };
3945
- }, Q = (e) => e?.message ?? String(e), Va = (e) => e && typeof e == "object" && "_tag" in e ? String(e._tag) : null, Ha = (e) => {
3957
+ }, Q = (e) => e?.message ?? String(e), qa = (e) => e && typeof e == "object" && "_tag" in e ? String(e._tag) : null, Ja = (e) => {
3946
3958
  let t = {};
3947
3959
  for (let [n, r] of Object.entries(e)) t[n] = r instanceof Date ? r.toISOString() : r;
3948
3960
  return t;
3949
- }, Ua = (e, t, n, r) => {
3961
+ }, Ya = (e, t, n, r) => {
3950
3962
  let i = !1, a, o = async () => {
3951
3963
  if (i) return;
3952
3964
  let a = new Date(Math.floor(Date.now() / t) * t), o = !1;
@@ -3976,7 +3988,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
3976
3988
  i || (i = !0, a && clearInterval(a), a = void 0);
3977
3989
  }
3978
3990
  };
3979
- }, Wa = (e) => (t, n, r) => Ua(t, n, r, e), Ga = E("_voltro_schedule_runs", {
3991
+ }, Xa = (e) => (t, n, r) => Ya(t, n, r, e), Za = E("_voltro_schedule_runs", {
3980
3992
  id: v({ prefix: "schrun" }),
3981
3993
  name: D(),
3982
3994
  status: D().oneOf([
@@ -4006,13 +4018,13 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4006
4018
  ]).nullable(),
4007
4019
  replicaId: D().nullable(),
4008
4020
  result: S().nullable()
4009
- }).index(["name", "scheduledAt"]).index(["status"]), Ka = E("_voltro_schedule_claims", {
4021
+ }).index(["name", "scheduledAt"]).index(["status"]), Qa = E("_voltro_schedule_claims", {
4010
4022
  id: v({ prefix: "schclaim" }),
4011
4023
  scheduleName: D(),
4012
4024
  bucket: D(),
4013
4025
  claimedBy: D(),
4014
4026
  claimedAt: O()
4015
- }).index(["scheduleName", "bucket"]).index(["claimedAt"]), qa = E("_voltro_traces", {
4027
+ }).index(["scheduleName", "bucket"]).index(["claimedAt"]), $a = E("_voltro_traces", {
4016
4028
  id: v({ prefix: "span" }),
4017
4029
  traceId: D(),
4018
4030
  spanId: D(),
@@ -4036,7 +4048,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4036
4048
  durationMs: b(),
4037
4049
  attributes: S().nullable(),
4038
4050
  events: S().nullable()
4039
- }).index(["traceId", "startedAt"]).index(["startedAt"]).index(["status"]), Ja = E("_voltro_undo_log", {
4051
+ }).index(["traceId", "startedAt"]).index(["startedAt"]).index(["status"]), eo = E("_voltro_undo_log", {
4040
4052
  id: v({ prefix: "undo" }),
4041
4053
  tag: D(),
4042
4054
  label: D().nullable(),
@@ -4047,25 +4059,25 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4047
4059
  crossesAction: r().default(!1),
4048
4060
  undone: r().default(!1),
4049
4061
  createdAt: O().default("now")
4050
- }).index(["subjectId", "createdAt"]).reactive(), Ya = (e = process.env) => {
4062
+ }).index(["subjectId", "createdAt"]).reactive(), to = (e = process.env) => {
4051
4063
  let t = (e.VOLTRO_UNDO ?? "").toLowerCase();
4052
4064
  return t === "on" || t === "1" || t === "true" ? !0 : t === "off" || t === "0" || t === "false" ? !1 : e.NODE_ENV !== "production";
4053
- }, Xa = (e) => e.startsWith("_voltro"), Za = async (e, t, n) => (await e.query({
4065
+ }, no = (e) => e.startsWith("_voltro"), ro = async (e, t, n) => (await e.query({
4054
4066
  table: t,
4055
4067
  predicate: u("id", n),
4056
4068
  order: []
4057
- }))[0] ?? null, Qa = (e, t) => new Proxy(e, { get(e, n, r) {
4069
+ }))[0] ?? null, io = (e, t) => new Proxy(e, { get(e, n, r) {
4058
4070
  if (n === "insert") return async (n, r) => {
4059
4071
  let i = await e.insert(n, r);
4060
- return Xa(n) || t({
4072
+ return no(n) || t({
4061
4073
  table: n,
4062
4074
  op: "insert",
4063
4075
  next: i
4064
4076
  }), i;
4065
4077
  };
4066
4078
  if (n === "update") return async (n, r, i) => {
4067
- let a = Xa(n) ? null : await Za(e, n, r), o = await e.update(n, r, i);
4068
- return Xa(n) || t({
4079
+ let a = no(n) ? null : await ro(e, n, r), o = await e.update(n, r, i);
4080
+ return no(n) || t({
4069
4081
  table: n,
4070
4082
  op: "update",
4071
4083
  id: r,
@@ -4074,8 +4086,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4074
4086
  }), o;
4075
4087
  };
4076
4088
  if (n === "delete") return async (n, r) => {
4077
- let i = Xa(n) ? null : await Za(e, n, r), a = await e.delete(n, r);
4078
- return !Xa(n) && a && t({
4089
+ let i = no(n) ? null : await ro(e, n, r), a = await e.delete(n, r);
4090
+ return !no(n) && a && t({
4079
4091
  table: n,
4080
4092
  op: "delete",
4081
4093
  id: r,
@@ -4084,10 +4096,10 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4084
4096
  };
4085
4097
  let i = Reflect.get(e, n, r);
4086
4098
  return typeof i == "function" ? i.bind(e) : i;
4087
- } }), $a = (e) => {
4099
+ } }), ao = (e) => {
4088
4100
  let t = [];
4089
4101
  return {
4090
- tx: Qa(e, (e) => t.push(e)),
4102
+ tx: io(e, (e) => t.push(e)),
4091
4103
  persist: async (e, n) => {
4092
4104
  if (t.length === 0 || n.tag.startsWith("__voltro")) return;
4093
4105
  let r = n.subject;
@@ -4103,14 +4115,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4103
4115
  });
4104
4116
  }
4105
4117
  };
4106
- }, eo = (e) => {
4118
+ }, oo = (e) => {
4107
4119
  if (e.id !== void 0) return e.id;
4108
4120
  let t = e.next?.id;
4109
4121
  if (typeof t == "string") return t;
4110
4122
  let n = e.prev?.id;
4111
4123
  return typeof n == "string" ? n : void 0;
4112
- }, to = (e) => {
4113
- let t = eo(e);
4124
+ }, so = (e) => {
4125
+ let t = oo(e);
4114
4126
  switch (e.op) {
4115
4127
  case "insert": return t === void 0 ? null : {
4116
4128
  table: e.table,
@@ -4134,28 +4146,28 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4134
4146
  row: e.prev
4135
4147
  };
4136
4148
  }
4137
- }, no = (e) => {
4138
- if (e.crossesAction) throw new ro(e.invocationId, "action");
4149
+ }, co = (e) => {
4150
+ if (e.crossesAction) throw new lo(e.invocationId, "action");
4139
4151
  let t = [];
4140
4152
  for (let n = e.changes.length - 1; n >= 0; --n) {
4141
- let r = to(e.changes[n]);
4153
+ let r = so(e.changes[n]);
4142
4154
  r !== null && t.push(r);
4143
4155
  }
4144
4156
  return t;
4145
- }, ro = class extends Error {
4157
+ }, lo = class extends Error {
4146
4158
  invocationId;
4147
4159
  boundary;
4148
4160
  _tag = "UndoBoundaryError";
4149
4161
  constructor(e, t) {
4150
4162
  super(t === "action" ? `cannot undo invocation ${e}: it crossed an action (external side effect)` : `cannot undo invocation ${e}: the row changed since (conflict)`), this.invocationId = e, this.boundary = t, this.name = "UndoBoundaryError";
4151
4163
  }
4152
- }, io = (e, t, n = ["updatedAt", "updatedBy"]) => {
4164
+ }, uo = (e, t, n = ["updatedAt", "updatedBy"]) => {
4153
4165
  if (t == null) return e == null;
4154
4166
  if (e == null) return !1;
4155
4167
  let r = new Set(n);
4156
4168
  for (let [n, i] of Object.entries(t)) if (!r.has(n) && !Object.is(e[n], i) && JSON.stringify(e[n]) !== JSON.stringify(i)) return !1;
4157
4169
  return !0;
4158
- }, ao = class {
4170
+ }, fo = class {
4159
4171
  capacity;
4160
4172
  done = [];
4161
4173
  undone = [];
@@ -4191,7 +4203,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4191
4203
  redo: [...this.undone]
4192
4204
  };
4193
4205
  }
4194
- }, oo = (e, t = /* @__PURE__ */ new Set()) => e.op === "insert" ? {
4206
+ }, po = (e, t = /* @__PURE__ */ new Set()) => e.op === "insert" ? {
4195
4207
  table: e.table,
4196
4208
  op: "insert",
4197
4209
  next: e.new ?? null
@@ -4208,7 +4220,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4208
4220
  table: e.table,
4209
4221
  op: "delete",
4210
4222
  prev: e.old ?? null
4211
- }, so = async (e, t) => {
4223
+ }, mo = async (e, t) => {
4212
4224
  switch (t.op) {
4213
4225
  case "delete":
4214
4226
  await e.delete(t.table, t.id);
@@ -4226,21 +4238,21 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4226
4238
  await e.insert(t.table, t.row);
4227
4239
  return;
4228
4240
  }
4229
- }, co = async (e, t) => {
4230
- for (let n of t) await so(e, n);
4231
- }, lo = (e) => e.request?.subject?.id ?? null, uo = (e) => e === !0 || e === 1, fo = async (e, t, n) => (await e.query({
4241
+ }, ho = async (e, t) => {
4242
+ for (let n of t) await mo(e, n);
4243
+ }, go = (e) => e.request?.subject?.id ?? null, _o = (e) => e === !0 || e === 1, vo = async (e, t, n) => (await e.query({
4232
4244
  table: t,
4233
4245
  predicate: u("id", n),
4234
4246
  order: []
4235
- }))[0] ?? null, po = (e) => {
4247
+ }))[0] ?? null, yo = (e) => {
4236
4248
  try {
4237
4249
  let t = JSON.parse(String(e ?? "[]"));
4238
4250
  return Array.isArray(t) ? t : [];
4239
4251
  } catch {
4240
4252
  return [];
4241
4253
  }
4242
- }, mo = (e) => e.id ?? e.next?.id ?? e.prev?.id, ho = async (e, t) => {
4243
- let n = lo(t);
4254
+ }, bo = (e) => e.id ?? e.next?.id ?? e.prev?.id, xo = async (e, t) => {
4255
+ let n = go(t);
4244
4256
  return [...await t.store.query({
4245
4257
  table: "_voltro_undo_log",
4246
4258
  predicate: u("subjectId", n),
@@ -4249,68 +4261,68 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4249
4261
  id: String(e.id),
4250
4262
  tag: String(e.tag ?? ""),
4251
4263
  label: e.label ?? null,
4252
- undone: uo(e.undone),
4253
- crossesAction: uo(e.crossesAction),
4264
+ undone: _o(e.undone),
4265
+ crossesAction: _o(e.crossesAction),
4254
4266
  createdAt: String(e.createdAt ?? "")
4255
4267
  }));
4256
- }, go = async (e, t) => {
4257
- let n = await fo(t.store, "_voltro_undo_log", e.invocationId);
4258
- if (!n) throw new Se({ invocationId: e.invocationId });
4259
- if ((n.subjectId ?? null) !== lo(t)) throw new xe({ invocationId: e.invocationId });
4268
+ }, So = async (e, t) => {
4269
+ let n = await vo(t.store, "_voltro_undo_log", e.invocationId);
4270
+ if (!n) throw new xe({ invocationId: e.invocationId });
4271
+ if ((n.subjectId ?? null) !== go(t)) throw new be({ invocationId: e.invocationId });
4260
4272
  return n;
4261
- }, _o = async (e, t) => {
4262
- let n = await go(e, t);
4263
- if (uo(n.undone)) return { ok: !0 };
4264
- if (uo(n.crossesAction)) throw new be({
4273
+ }, Co = async (e, t) => {
4274
+ let n = await So(e, t);
4275
+ if (_o(n.undone)) return { ok: !0 };
4276
+ if (_o(n.crossesAction)) throw new ye({
4265
4277
  invocationId: e.invocationId,
4266
4278
  reason: "action"
4267
4279
  });
4268
- let r = po(n.changes);
4280
+ let r = yo(n.changes);
4269
4281
  for (let n of r) {
4270
- let r = mo(n);
4271
- if (r !== void 0 && !io(await fo(t.store, n.table, r), n.next ?? null)) throw new be({
4282
+ let r = bo(n);
4283
+ if (r !== void 0 && !uo(await vo(t.store, n.table, r), n.next ?? null)) throw new ye({
4272
4284
  invocationId: e.invocationId,
4273
4285
  reason: "conflict"
4274
4286
  });
4275
4287
  }
4276
4288
  let i = {
4277
4289
  invocationId: e.invocationId,
4278
- subject: lo(t),
4290
+ subject: go(t),
4279
4291
  changes: r,
4280
4292
  crossesAction: !1
4281
4293
  };
4282
- return await co(t.store, no(i)), await t.store.update("_voltro_undo_log", e.invocationId, { undone: !0 }), { ok: !0 };
4283
- }, vo = async (e, t) => {
4284
- let n = await go(e, t);
4285
- if (!uo(n.undone)) return { ok: !0 };
4286
- for (let e of po(n.changes)) {
4287
- let n = mo(e);
4294
+ return await ho(t.store, co(i)), await t.store.update("_voltro_undo_log", e.invocationId, { undone: !0 }), { ok: !0 };
4295
+ }, wo = async (e, t) => {
4296
+ let n = await So(e, t);
4297
+ if (!_o(n.undone)) return { ok: !0 };
4298
+ for (let e of yo(n.changes)) {
4299
+ let n = bo(e);
4288
4300
  e.op === "insert" && e.next ? await t.store.insert(e.table, e.next) : e.op === "update" && n !== void 0 && e.next ? await t.store.update(e.table, n, e.next) : e.op === "delete" && n !== void 0 && await t.store.delete(e.table, n);
4289
4301
  }
4290
4302
  return await t.store.update("_voltro_undo_log", e.invocationId, { undone: !1 }), { ok: !0 };
4291
- }, yo = (e = process.env) => {
4303
+ }, To = (e = process.env) => {
4292
4304
  let t = (e.VOLTRO_TIMELINE ?? "").toLowerCase();
4293
4305
  return t === "off" || t === "0" || t === "false" ? "off" : t === "all" ? "all" : t === "interesting" || t === "on" || t === "1" || t === "true" ? "interesting" : e.NODE_ENV === "production" ? "off" : "interesting";
4294
- }, bo = /pass(word)?|secret|token|api[_-]?key|authorization|cookie|ssn|credit[_-]?card|card[_-]?number|cvv|encrypted/i, xo = "«redacted»", So = (e) => {
4306
+ }, Eo = /pass(word)?|secret|token|api[_-]?key|authorization|cookie|ssn|credit[_-]?card|card[_-]?number|cvv|encrypted/i, Do = "«redacted»", Oo = (e) => {
4295
4307
  if (e == null) return null;
4296
4308
  let t = {};
4297
- for (let [n, r] of Object.entries(e)) t[n] = bo.test(n) ? xo : r;
4309
+ for (let [n, r] of Object.entries(e)) t[n] = Eo.test(n) ? Do : r;
4298
4310
  return t;
4299
- }, Co = (e) => {
4311
+ }, ko = (e) => {
4300
4312
  let t = e?.id;
4301
4313
  return typeof t == "string" ? t : void 0;
4302
- }, wo = (e, t) => {
4314
+ }, Ao = (e, t) => {
4303
4315
  if (t.op === "insert") {
4304
- let n = Co(t.new);
4316
+ let n = ko(t.new);
4305
4317
  return n === void 0 ? e : e.filter((e) => e.id !== n);
4306
4318
  }
4307
4319
  if (t.op === "update") {
4308
4320
  if (t.old == null) return e;
4309
- let n = Co(t.new) ?? Co(t.old);
4321
+ let n = ko(t.new) ?? ko(t.old);
4310
4322
  return e.map((e) => e.id === n ? t.old : e);
4311
4323
  }
4312
4324
  return t.old == null ? e : [...e, t.old];
4313
- }, To = class {
4325
+ }, jo = class {
4314
4326
  mode;
4315
4327
  capacity;
4316
4328
  now;
@@ -4330,8 +4342,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4330
4342
  ts: this.now(),
4331
4343
  table: e.table,
4332
4344
  op: e.op,
4333
- old: So(e.old),
4334
- new: So(e.new),
4345
+ old: Oo(e.old),
4346
+ new: Oo(e.new),
4335
4347
  tenantId: n
4336
4348
  }), this.ring.length > this.capacity && this.ring.shift(), t;
4337
4349
  }
@@ -4344,23 +4356,23 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4344
4356
  }
4345
4357
  replay(e, t, n) {
4346
4358
  let r = this.ring.filter((n) => n.table === e && n.seq > t).sort((e, t) => t.seq - e.seq), i = n;
4347
- for (let e of r) i = wo(i, e);
4359
+ for (let e of r) i = Ao(i, e);
4348
4360
  return i;
4349
4361
  }
4350
- }, Eo, Do = () => (Eo === void 0 && (Eo = new To(yo())), Eo), Oo = (e) => {
4351
- Eo = e;
4352
- }, ko = (e) => {
4353
- let t = Do();
4362
+ }, Mo, No = () => (Mo === void 0 && (Mo = new jo(To())), Mo), Po = (e) => {
4363
+ Mo = e;
4364
+ }, Fo = (e) => {
4365
+ let t = No();
4354
4366
  if (t.enabled) try {
4355
4367
  t.record(e);
4356
4368
  } catch {}
4357
- }, Ao = /* @__PURE__ */ new Set([
4369
+ }, Io = /* @__PURE__ */ new Set([
4358
4370
  "count",
4359
4371
  "sum",
4360
4372
  "avg",
4361
4373
  "min",
4362
4374
  "max"
4363
- ]), jo = (e) => {
4375
+ ]), Lo = (e) => {
4364
4376
  if (e.joins !== void 0 && e.joins.length > 0) return {
4365
4377
  maintainable: !1,
4366
4378
  reason: "joins are not maintainable in v1"
@@ -4382,7 +4394,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4382
4394
  reason: "v1 maintains exactly one aggregation"
4383
4395
  };
4384
4396
  let t = e.aggregations[0];
4385
- return Ao.has(t.op) ? t.op !== "count" && (t.column === void 0 || t.column.length === 0) ? {
4397
+ return Io.has(t.op) ? t.op !== "count" && (t.column === void 0 || t.column.length === 0) ? {
4386
4398
  maintainable: !1,
4387
4399
  reason: `op '${t.op}' requires a column`
4388
4400
  } : {
@@ -4396,7 +4408,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4396
4408
  maintainable: !1,
4397
4409
  reason: `op '${t.op}' is not maintainable`
4398
4410
  };
4399
- }, Mo = "\0", $ = (e, t) => t === void 0 || t.length === 0 ? "" : t.map((t) => JSON.stringify(e[t] ?? null)).join(Mo), No = (e, t) => t === void 0 ? 0 : Number(e[t] ?? 0), Po = (e, t) => {
4411
+ }, Ro = "\0", $ = (e, t) => t === void 0 || t.length === 0 ? "" : t.map((t) => JSON.stringify(e[t] ?? null)).join(Ro), zo = (e, t) => t === void 0 ? 0 : Number(e[t] ?? 0), Bo = (e, t) => {
4400
4412
  switch (e.op) {
4401
4413
  case "count": return t.count;
4402
4414
  case "sum": return t.sum ?? 0;
@@ -4404,10 +4416,10 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4404
4416
  case "min":
4405
4417
  case "max": return t.count > 0 ? t.extreme ?? null : null;
4406
4418
  }
4407
- }, Fo = (e, t) => {
4419
+ }, Vo = (e, t) => {
4408
4420
  let n = /* @__PURE__ */ new Map();
4409
4421
  for (let r of t) {
4410
- let t = $(r, e.groupBy), i = n.get(t), a = No(r, e.column);
4422
+ let t = $(r, e.groupBy), i = n.get(t), a = zo(r, e.column);
4411
4423
  if (i === void 0) n.set(t, {
4412
4424
  count: 1,
4413
4425
  ...e.op === "sum" || e.op === "avg" ? { sum: a } : {},
@@ -4423,10 +4435,10 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4423
4435
  }
4424
4436
  }
4425
4437
  return n;
4426
- }, Io = (e, t) => [...t.entries()].map(([t, n]) => ({
4438
+ }, Ho = (e, t) => [...t.entries()].map(([t, n]) => ({
4427
4439
  groupKey: t,
4428
- value: Po(e, n)
4429
- })), Lo = (e, t, n) => {
4440
+ value: Bo(e, n)
4441
+ })), Uo = (e, t, n) => {
4430
4442
  let r = new Map(t), i = /* @__PURE__ */ new Set(), a = (t) => {
4431
4443
  let n = $(t, e.groupBy), a = r.get(n);
4432
4444
  if (a === void 0) return;
@@ -4435,7 +4447,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4435
4447
  r.delete(n);
4436
4448
  return;
4437
4449
  }
4438
- let s = No(t, e.column);
4450
+ let s = zo(t, e.column);
4439
4451
  e.op === "min" || e.op === "max" ? (a.extreme !== void 0 && s === a.extreme && i.add(n), r.set(n, {
4440
4452
  count: o,
4441
4453
  ...a.extreme === void 0 ? {} : { extreme: a.extreme }
@@ -4444,7 +4456,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4444
4456
  ...e.op === "sum" || e.op === "avg" ? { sum: (a.sum ?? 0) - s } : {}
4445
4457
  });
4446
4458
  }, o = (t) => {
4447
- let n = $(t, e.groupBy), i = r.get(n), a = No(t, e.column);
4459
+ let n = $(t, e.groupBy), i = r.get(n), a = zo(t, e.column);
4448
4460
  if (i === void 0) {
4449
4461
  r.set(n, {
4450
4462
  count: 1,
@@ -4464,15 +4476,15 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4464
4476
  state: r,
4465
4477
  rescanGroups: [...i]
4466
4478
  };
4467
- }, Ro = (e, t, n, r) => {
4479
+ }, Wo = (e, t, n, r) => {
4468
4480
  if (n.length === 0) return t;
4469
- let i = new Set(n), a = Fo(e, r.filter((t) => i.has($(t, e.groupBy)))), o = new Map(t);
4481
+ let i = new Set(n), a = Vo(e, r.filter((t) => i.has($(t, e.groupBy)))), o = new Map(t);
4470
4482
  for (let e of i) {
4471
4483
  let t = a.get(e);
4472
4484
  t === void 0 ? o.delete(e) : o.set(e, t);
4473
4485
  }
4474
4486
  return o;
4475
- }, zo = class {
4487
+ }, Go = class {
4476
4488
  shape;
4477
4489
  state = /* @__PURE__ */ new Map();
4478
4490
  groups = /* @__PURE__ */ new Map();
@@ -4480,7 +4492,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4480
4492
  this.shape = e;
4481
4493
  }
4482
4494
  seed(e) {
4483
- this.state = Fo(this.shape, e), this.groups.clear();
4495
+ this.state = Vo(this.shape, e), this.groups.clear();
4484
4496
  for (let t of e) {
4485
4497
  let e = $(t, this.shape.groupBy);
4486
4498
  this.groups.has(e) || this.groups.set(e, this.groupValues(t));
@@ -4492,14 +4504,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4492
4504
  let e = $(t, this.shape.groupBy);
4493
4505
  this.groups.has(e) || this.groups.set(e, this.groupValues(t));
4494
4506
  }
4495
- let n = Lo(this.shape, this.state, e);
4507
+ let n = Uo(this.shape, this.state, e);
4496
4508
  this.state = n.state;
4497
4509
  for (let e of this.groups.keys()) this.state.has(e) || this.groups.delete(e);
4498
4510
  return n.rescanGroups;
4499
4511
  }
4500
4512
  resolveRescan(e, t) {
4501
4513
  if (e.length === 0) return;
4502
- this.state = Ro(this.shape, this.state, e, t);
4514
+ this.state = Wo(this.shape, this.state, e, t);
4503
4515
  let n = new Set(e);
4504
4516
  for (let e of t) {
4505
4517
  let t = $(e, this.shape.groupBy);
@@ -4508,7 +4520,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4508
4520
  for (let e of n) this.state.has(e) || this.groups.delete(e);
4509
4521
  }
4510
4522
  materialize() {
4511
- return Io(this.shape, this.state).map((e) => ({
4523
+ return Ho(this.shape, this.state).map((e) => ({
4512
4524
  groupKey: e.groupKey,
4513
4525
  group: this.groups.get(e.groupKey) ?? {},
4514
4526
  value: e.value
@@ -4521,16 +4533,16 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4521
4533
  for (let r of t) n[r] = e[r];
4522
4534
  return n;
4523
4535
  }
4524
- }, Bo = "admin:full", Vo = class extends I.TaggedError()("AccessDenied", {
4536
+ }, Ko = "admin:full", qo = class extends I.TaggedError()("AccessDenied", {
4525
4537
  action: I.String,
4526
4538
  resourceType: I.String,
4527
4539
  resourceId: I.String
4528
- }) {}, Ho = /* @__PURE__ */ new Map(), Uo = (e) => {
4540
+ }) {}, Jo = /* @__PURE__ */ new Map(), Yo = (e) => {
4529
4541
  if (typeof e.resourceType != "string" || e.resourceType.length === 0) throw Error("defineResourcePolicy: a non-empty `resourceType` is required");
4530
4542
  if (e.actions === void 0 || Object.keys(e.actions).length === 0) throw Error(`resource policy '${e.resourceType}': at least one action is required`);
4531
- if (Ho.has(e.resourceType)) throw Error(`resource policy '${e.resourceType}' is already registered — types must be unique`);
4532
- return Ho.set(e.resourceType, e), e;
4533
- }, Wo = (e) => Ho.get(e), Go = () => [...Ho.values()], Ko = () => Ho.clear(), qo = () => Go().map((e) => {
4543
+ if (Jo.has(e.resourceType)) throw Error(`resource policy '${e.resourceType}' is already registered — types must be unique`);
4544
+ return Jo.set(e.resourceType, e), e;
4545
+ }, Xo = (e) => Jo.get(e), Zo = () => [...Jo.values()], Qo = () => Jo.clear(), $o = () => Zo().map((e) => {
4534
4546
  let t = /* @__PURE__ */ new Set();
4535
4547
  for (let n of Object.values(e.actions)) for (let e of n) t.add(e);
4536
4548
  for (let [n, r] of Object.entries(e.implies ?? {})) {
@@ -4543,7 +4555,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4543
4555
  relations: [...t],
4544
4556
  implies: e.implies ?? {}
4545
4557
  };
4546
- }), Jo = (e, t) => {
4558
+ }), es = (e, t) => {
4547
4559
  let n = new Set(e);
4548
4560
  if (t === void 0) return n;
4549
4561
  let r = [...e];
@@ -4552,27 +4564,27 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4552
4564
  for (let i of t[e] ?? []) n.has(i) || (n.add(i), r.push(i));
4553
4565
  }
4554
4566
  return n;
4555
- }, Yo = (e, t, n, r) => e.id === null ? /* @__PURE__ */ new Set() : Jo(n.filter((n) => n.subjectId === e.id && n.resourceType === t.type && n.resourceId === t.id).map((e) => e.relation), r.implies), Xo = (e, t, n, r) => {
4567
+ }, ts = (e, t, n, r) => e.id === null ? /* @__PURE__ */ new Set() : es(n.filter((n) => n.subjectId === e.id && n.resourceType === t.type && n.resourceId === t.id).map((e) => e.relation), r.implies), ns = (e, t, n, r) => {
4556
4568
  if (e.scopes?.includes("admin:full")) return !0;
4557
4569
  if (e.id === null || n.tenantId != null && e.tenantId !== n.tenantId) return !1;
4558
4570
  let i = r.policy.actions[t];
4559
4571
  if (i === void 0 || i.length === 0) return !1;
4560
- let a = Yo(e, n, r.tuples, r.policy);
4572
+ let a = ts(e, n, r.tuples, r.policy);
4561
4573
  return i.some((e) => a.has(e));
4562
- }, Zo = (e, t, n, r) => {
4563
- if (!Xo(e, t, n, r)) throw new Vo({
4574
+ }, rs = (e, t, n, r) => {
4575
+ if (!ns(e, t, n, r)) throw new qo({
4564
4576
  action: t,
4565
4577
  resourceType: n.type,
4566
4578
  resourceId: n.id
4567
4579
  });
4568
- }, Qo = (e, t, n, r, i) => r.filter((r) => Xo(e, t, {
4580
+ }, is = (e, t, n, r, i) => r.filter((r) => ns(e, t, {
4569
4581
  type: n,
4570
4582
  id: r.id,
4571
4583
  ...r.tenantId === void 0 ? {} : { tenantId: r.tenantId }
4572
- }, i)), $o = (e, t) => {
4584
+ }, i)), as = (e, t) => {
4573
4585
  let n = new Set(t.map((e) => e.id));
4574
4586
  return e.filter((e) => !n.has(e.id)).map((e) => e.id);
4575
- }, es = E("_voltro_rebac_tuples", {
4587
+ }, os = E("_voltro_rebac_tuples", {
4576
4588
  id: v({ prefix: "rbct" }),
4577
4589
  subjectId: D(),
4578
4590
  relation: D(),
@@ -4584,7 +4596,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4584
4596
  "subjectId",
4585
4597
  "resourceType",
4586
4598
  "resourceId"
4587
- ]).reactive(), ts = async (e, n, r, i) => n === null ? [] : (await e.query({
4599
+ ]).reactive(), ss = async (e, n, r, i) => n === null ? [] : (await e.query({
4588
4600
  table: "_voltro_rebac_tuples",
4589
4601
  predicate: t(u("subjectId", n), u("resourceType", r), u("resourceId", i)),
4590
4602
  order: [],
@@ -4596,16 +4608,16 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4596
4608
  relation: e.relation,
4597
4609
  resourceType: e.resourceType,
4598
4610
  resourceId: e.resourceId
4599
- })), ns = (e) => ({
4611
+ })), cs = (e) => ({
4600
4612
  id: e.id,
4601
4613
  tenantId: e.tenantId,
4602
4614
  ...e.scopes === void 0 ? {} : { scopes: e.scopes }
4603
- }), rs = (e, t) => {
4604
- let n = t.getPolicy ?? Wo;
4615
+ }), ls = (e, t) => {
4616
+ let n = t.getPolicy ?? Xo;
4605
4617
  return (r, i) => {
4606
4618
  let a = e[i.tag];
4607
4619
  if (a === void 0) return r;
4608
- let o = n(a.resourceType), s = (e) => j.fail(new Vo({
4620
+ let o = n(a.resourceType), s = (e) => j.fail(new qo({
4609
4621
  action: a.action,
4610
4622
  resourceType: a.resourceType,
4611
4623
  resourceId: e
@@ -4613,17 +4625,17 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4613
4625
  if (o === void 0) return s("");
4614
4626
  let c = a.resourceId(i.input);
4615
4627
  if (c === null || c === "") return s("");
4616
- let l = ns(i.subject), u = {
4628
+ let l = cs(i.subject), u = {
4617
4629
  type: a.resourceType,
4618
4630
  id: c,
4619
4631
  tenantId: i.subject.tenantId
4620
4632
  };
4621
- return j.flatMap(j.promise(async () => t.loadTuples(l.id, a.resourceType, c)), (e) => Xo(l, a.action, u, {
4633
+ return j.flatMap(j.promise(async () => t.loadTuples(l.id, a.resourceType, c)), (e) => ns(l, a.action, u, {
4622
4634
  policy: o,
4623
4635
  tuples: e
4624
4636
  }) ? r : s(c));
4625
4637
  };
4626
- }, is = async (e, n, r) => n === null ? [] : (await e.query({
4638
+ }, us = async (e, n, r) => n === null ? [] : (await e.query({
4627
4639
  table: "_voltro_rebac_tuples",
4628
4640
  predicate: t(u("subjectId", n), u("resourceType", r)),
4629
4641
  order: [],
@@ -4635,18 +4647,18 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4635
4647
  relation: e.relation,
4636
4648
  resourceType: e.resourceType,
4637
4649
  resourceId: e.resourceId
4638
- })), as = (e) => {
4639
- let t = e.getPolicy ?? Wo;
4650
+ })), ds = (e) => {
4651
+ let t = e.getPolicy ?? Xo;
4640
4652
  return async (n, r, i, a) => {
4641
4653
  let o = t(r);
4642
4654
  if (o === void 0) return [];
4643
- let s = ns(n);
4644
- return Qo(s, i, r, a, {
4655
+ let s = cs(n);
4656
+ return is(s, i, r, a, {
4645
4657
  policy: o,
4646
4658
  tuples: await e.loadSubjectTuples(s.id, r)
4647
4659
  });
4648
4660
  };
4649
- }, os = (e) => {
4661
+ }, fs = (e) => {
4650
4662
  if (typeof e.name != "string" || e.name.length === 0) throw Error("defineReaction: a non-empty `name` is required");
4651
4663
  if (e.watch === void 0 || typeof e.watch.table != "string" || e.watch.table.length === 0) throw Error(`reaction '${e.name}': watch.table is required`);
4652
4664
  if (e.act === void 0 || e.act.kind !== "agent" && e.act.kind !== "workflow") throw Error(`reaction '${e.name}': act must be { kind: 'agent' | 'workflow', … }`);
@@ -4654,14 +4666,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4654
4666
  if (e.guards.rateLimit !== void 0 && (e.guards.rateLimit.limit <= 0 || e.guards.rateLimit.windowMs <= 0)) throw Error(`reaction '${e.name}': guards.rateLimit needs positive limit + windowMs`);
4655
4667
  if (e.guards.costBudgetUsd !== void 0 && e.guards.costBudgetUsd < 0) throw Error(`reaction '${e.name}': guards.costBudgetUsd must be >= 0`);
4656
4668
  return e;
4657
- }, ss = (e, t) => e === void 0 ? !0 : Array.isArray(e) ? e.includes(t) : e === t, cs = (e) => e.new?.tenantId ?? e.old?.tenantId ?? null, ls = class {
4669
+ }, ps = (e, t) => e === void 0 ? !0 : Array.isArray(e) ? e.includes(t) : e === t, ms = (e) => e.new?.tenantId ?? e.old?.tenantId ?? null, hs = class {
4658
4670
  hits = /* @__PURE__ */ new Map();
4659
4671
  allow(e, t, n, r) {
4660
4672
  let i = r - n, a = (this.hits.get(e) ?? []).filter((e) => e > i);
4661
4673
  return a.length >= t ? (this.hits.set(e, a), !1) : (a.push(r), this.hits.set(e, a), !0);
4662
4674
  }
4663
- }, us = async (e, t, n) => {
4664
- if (t.table !== e.watch.table || !ss(e.watch.on, t.op)) return "skipped-op";
4675
+ }, gs = async (e, t, n) => {
4676
+ if (t.table !== e.watch.table || !ps(e.watch.on, t.op)) return "skipped-op";
4665
4677
  if (e.when !== void 0 && !e.when(t)) return "skipped-when";
4666
4678
  let r = `${e.name}:${e.guards.dedupeKey(t)}`;
4667
4679
  if (await n.dedupe.has(r)) return "skipped-dedupe";
@@ -4670,26 +4682,26 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4670
4682
  let t = n.now?.() ?? Date.now();
4671
4683
  if (!n.rateLimiter.allow(e.name, i.limit, i.windowMs, t)) return "skipped-ratelimit";
4672
4684
  }
4673
- let a = cs(t);
4685
+ let a = ms(t);
4674
4686
  return e.guards.costBudgetUsd !== void 0 && n.checkBudget !== void 0 && !await n.checkBudget(a, e.guards.costBudgetUsd) ? "skipped-budget" : (await n.runAct(e.act, t, {
4675
4687
  id: a,
4676
4688
  via: "agent"
4677
4689
  }), await n.dedupe.add(r), "acted");
4678
- }, ds = E("_voltro_wakeups", {
4690
+ }, _s = E("_voltro_wakeups", {
4679
4691
  id: v({ prefix: "wakeup" }),
4680
4692
  tenantId: D(),
4681
4693
  kind: D(),
4682
4694
  refId: D(),
4683
4695
  wakeAt: O(),
4684
4696
  status: D()
4685
- }).index(["status", "wakeAt"]).index(["tenantId"]), fs = async (e) => {
4686
- let t = e.now?.() ?? /* @__PURE__ */ new Date(), n = await Ma(e.store, t, e.batchLimit ?? 100);
4697
+ }).index(["status", "wakeAt"]).index(["tenantId"]), vs = async (e) => {
4698
+ let t = e.now?.() ?? /* @__PURE__ */ new Date(), n = await Ra(e.store, t, e.batchLimit ?? 100);
4687
4699
  if (n.length === 0) return 0;
4688
4700
  let r = 0;
4689
- for (let t of n) if (await Oa(e.store, t)) try {
4701
+ for (let t of n) if (await Pa(e.store, t)) try {
4690
4702
  await e.adapter.wake(t), r++;
4691
4703
  } catch (n) {
4692
- await ka(e.store, t), e.log?.warn("wake: adapter failed — released for retry", {
4704
+ await Fa(e.store, t), e.log?.warn("wake: adapter failed — released for retry", {
4693
4705
  tenantId: t.tenantId,
4694
4706
  kind: t.kind,
4695
4707
  refId: t.refId,
@@ -4697,11 +4709,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4697
4709
  });
4698
4710
  }
4699
4711
  return r > 0 && e.log?.info("wake: woke due deployments", { count: r }), r;
4700
- }, ps = (e, t = 1e3) => {
4712
+ }, ys = (e, t = 1e3) => {
4701
4713
  let n = !1, r, i = async () => {
4702
4714
  if (!n) {
4703
4715
  try {
4704
- await fs(e);
4716
+ await vs(e);
4705
4717
  } catch (t) {
4706
4718
  e.log?.warn("wake: tick failed", { reason: t instanceof Error ? t.message : String(t) });
4707
4719
  }
@@ -4711,10 +4723,10 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4711
4723
  return i(), { stop: () => {
4712
4724
  n = !0, r !== void 0 && clearTimeout(r);
4713
4725
  } };
4714
- }, ms = (e) => ({ wake: async () => {
4726
+ }, bs = (e) => ({ wake: async () => {
4715
4727
  await e.start();
4716
- } }), hs = (e) => new Promise((t) => setTimeout(t, e)), gs = (e) => {
4717
- let t = e.fetchImpl ?? fetch, n = e.now ?? Date.now, r = e.sleep ?? hs, i = e.spawnImpl ?? ut, a = e.startTimeoutMs ?? 3e4, o = e.healthPollMs ?? 200, s = e.stopSignal ?? "SIGTERM", c = e.stopGraceMs ?? 1e4, l, u, d = e.healthCheck ?? ((e) => e.ok), f = async () => {
4728
+ } }), xs = (e) => new Promise((t) => setTimeout(t, e)), Ss = (e) => {
4729
+ let t = e.fetchImpl ?? fetch, n = e.now ?? Date.now, r = e.sleep ?? xs, i = e.spawnImpl ?? gt, a = e.startTimeoutMs ?? 3e4, o = e.healthPollMs ?? 200, s = e.stopSignal ?? "SIGTERM", c = e.stopGraceMs ?? 1e4, l, u, d = e.healthCheck ?? ((e) => e.ok), f = async () => {
4718
4730
  try {
4719
4731
  let n = await t(e.healthUrl);
4720
4732
  return d(n);
@@ -4768,11 +4780,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4768
4780
  },
4769
4781
  stop: m
4770
4782
  };
4771
- }, _s = async (e) => {
4783
+ }, Cs = async (e) => {
4772
4784
  if (e.signals.connectedClients() > 0 || e.signals.inFlightRequests() > 0 || e.signals.activeWorkflowExecutions() > 0) return !1;
4773
- let t = (e.now?.() ?? /* @__PURE__ */ new Date()).getTime() + (e.wakeLookaheadMs ?? 3e4), n = await Na(e.store);
4785
+ let t = (e.now?.() ?? /* @__PURE__ */ new Date()).getTime() + (e.wakeLookaheadMs ?? 3e4), n = await za(e.store);
4774
4786
  return !(n !== null && n.wakeAt.getTime() <= t);
4775
- }, vs = (e, t = Date.now) => {
4787
+ }, ws = (e, t = Date.now) => {
4776
4788
  let n;
4777
4789
  return {
4778
4790
  update: (r) => {
@@ -4784,7 +4796,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4784
4796
  n = void 0;
4785
4797
  }
4786
4798
  };
4787
- }, ys = () => {
4799
+ }, Ts = () => {
4788
4800
  let e = 0, t = 0;
4789
4801
  return {
4790
4802
  onRequestStart: () => {
@@ -4802,8 +4814,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4802
4814
  inFlightRequests: () => e,
4803
4815
  openConnections: () => t
4804
4816
  };
4805
- }, bs = (e) => ({ run: async (t) => (e.onActivity?.(), await e.ensureAwake(), t()) }), xs = (e, t, n, r) => new Promise((i, a) => {
4806
- let o = ze.request({
4817
+ }, Es = (e) => ({ run: async (t) => (e.onActivity?.(), await e.ensureAwake(), t()) }), Ds = (e, t, n, r) => new Promise((i, a) => {
4818
+ let o = Ue.request({
4807
4819
  host: n,
4808
4820
  port: r,
4809
4821
  method: e.method,
@@ -4813,8 +4825,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4813
4825
  t.writeHead(e.statusCode ?? 502, e.headers), e.pipe(t), e.on("end", i), e.on("error", a);
4814
4826
  });
4815
4827
  o.on("error", a), e.pipe(o);
4816
- }), Ss = (e, t, n, r, i) => new Promise((a, o) => {
4817
- let s = ze.request({
4828
+ }), Os = (e, t, n, r, i) => new Promise((a, o) => {
4829
+ let s = Ue.request({
4818
4830
  host: r,
4819
4831
  port: i,
4820
4832
  method: e.method,
@@ -4828,21 +4840,21 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4828
4840
  };
4829
4841
  t.on("close", s), r.on("close", s), r.on("error", o);
4830
4842
  }), s.on("error", o), s.end();
4831
- }), Cs = (e) => {
4832
- let t = bs({
4843
+ }), ks = (e) => {
4844
+ let t = Es({
4833
4845
  ensureAwake: () => e.supervisor.start(),
4834
4846
  ...e.onActivity === void 0 ? {} : { onActivity: e.onActivity }
4835
- }), n = e.activity, r = ze.createServer((r, i) => {
4836
- n?.onRequestStart(), i.on("close", () => n?.onRequestEnd()), t.run(() => xs(r, i, e.targetHost, e.targetPort)).catch((t) => {
4847
+ }), n = e.activity, r = Ue.createServer((r, i) => {
4848
+ n?.onRequestStart(), i.on("close", () => n?.onRequestEnd()), t.run(() => Ds(r, i, e.targetHost, e.targetPort)).catch((t) => {
4837
4849
  e.log?.warn("wake-router: proxy failed", { reason: t instanceof Error ? t.message : String(t) }), i.headersSent || i.writeHead(502), i.end("wake/proxy failed");
4838
4850
  });
4839
4851
  });
4840
4852
  return r.on("upgrade", (r, i, a) => {
4841
- n?.onConnect(), i.on("close", () => n?.onDisconnect()), t.run(() => Ss(r, i, a, e.targetHost, e.targetPort)).catch((t) => {
4853
+ n?.onConnect(), i.on("close", () => n?.onDisconnect()), t.run(() => Os(r, i, a, e.targetHost, e.targetPort)).catch((t) => {
4842
4854
  e.log?.warn("wake-router: upgrade proxy failed", { reason: t instanceof Error ? t.message : String(t) }), i.destroy();
4843
4855
  });
4844
4856
  }), r;
4845
- }, ws = async (e) => {
4857
+ }, As = async (e) => {
4846
4858
  try {
4847
4859
  return (await e.query({
4848
4860
  table: "_voltro_workflow_runs",
@@ -4859,15 +4871,15 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4859
4871
  } catch {
4860
4872
  return 0;
4861
4873
  }
4862
- }, Ts = async (e) => {
4863
- let t = ms(e.supervisor), n = await fs({
4874
+ }, js = async (e) => {
4875
+ let t = bs(e.supervisor), n = await vs({
4864
4876
  store: e.store,
4865
4877
  adapter: t,
4866
4878
  ...e.now === void 0 ? {} : { now: e.now },
4867
4879
  ...e.log === void 0 ? {} : { log: e.log }
4868
4880
  });
4869
4881
  n > 0 && e.idleGate.reset();
4870
- let r = await _s({
4882
+ let r = await Cs({
4871
4883
  store: e.store,
4872
4884
  signals: e.signals,
4873
4885
  ...e.wakeLookaheadMs === void 0 ? {} : { wakeLookaheadMs: e.wakeLookaheadMs },
@@ -4877,12 +4889,12 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4877
4889
  woke: n,
4878
4890
  stopped: i
4879
4891
  };
4880
- }, Es = async (e) => {
4881
- let t = vs(e.idleGraceMs ?? 6e4), n = e.tickMs ?? 1e3, r = ys(), i = 0, a = e.signals === void 0, o = e.signals ?? {
4892
+ }, Ms = async (e) => {
4893
+ let t = ws(e.idleGraceMs ?? 6e4), n = e.tickMs ?? 1e3, r = Ts(), i = 0, a = e.signals === void 0, o = e.signals ?? {
4882
4894
  connectedClients: () => r.openConnections(),
4883
4895
  inFlightRequests: () => r.inFlightRequests(),
4884
4896
  activeWorkflowExecutions: () => i
4885
- }, s = Cs({
4897
+ }, s = ks({
4886
4898
  supervisor: e.supervisor,
4887
4899
  targetHost: e.targetHost,
4888
4900
  targetPort: e.targetPort,
@@ -4901,7 +4913,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4901
4913
  let l = !1, u, d = e.firedRetentionMs ?? 10 * 6e4, f = 0, p = async () => {
4902
4914
  if (!l) {
4903
4915
  try {
4904
- if (a && (i = await ws(e.store)), await Ts({
4916
+ if (a && (i = await As(e.store)), await js({
4905
4917
  store: e.store,
4906
4918
  supervisor: e.supervisor,
4907
4919
  signals: o,
@@ -4909,7 +4921,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4909
4921
  ...e.wakeLookaheadMs === void 0 ? {} : { wakeLookaheadMs: e.wakeLookaheadMs },
4910
4922
  ...e.log === void 0 ? {} : { log: e.log }
4911
4923
  }), f++ % 60 == 0) {
4912
- let t = await Fa(e.store, { firedOlderThan: new Date(Date.now() - d) });
4924
+ let t = await Va(e.store, { firedOlderThan: new Date(Date.now() - d) });
4913
4925
  t > 0 && e.log?.info("orchestrator: pruned fired wakeups", { count: t });
4914
4926
  }
4915
4927
  } catch (t) {
@@ -4924,14 +4936,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4924
4936
  l = !0, u !== void 0 && clearTimeout(u), await new Promise((e) => s.close(() => e()));
4925
4937
  }
4926
4938
  };
4927
- }, Ds = (e) => e, Os = class extends I.TaggedError()("AnalyticsError", {
4939
+ }, Ns = (e) => e, Ps = class extends I.TaggedError()("AnalyticsError", {
4928
4940
  provider: I.String,
4929
4941
  operation: I.String,
4930
4942
  cause: I.String
4931
- }) {}, ks = class extends I.TaggedError()("AnalyticsCapabilityNotSupported", {
4943
+ }) {}, Fs = class extends I.TaggedError()("AnalyticsCapabilityNotSupported", {
4932
4944
  provider: I.String,
4933
4945
  capability: I.String
4934
- }) {}, As = class extends Ae.Tag("@voltro/AnalyticsSink")() {}, js = (e, t) => ({
4946
+ }) {}, Is = class extends Pe.Tag("@voltro/AnalyticsSink")() {}, Ls = (e, t) => ({
4935
4947
  info: e.info,
4936
4948
  track: (n) => e.track(n.tenantId === void 0 ? {
4937
4949
  ...n,
@@ -4950,20 +4962,20 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4950
4962
  tenantId: t
4951
4963
  } : n),
4952
4964
  ...e.mirror === void 0 ? {} : { mirror: e.mirror }
4953
- }), Ms = () => j.gen(function* () {
4954
- let e = yield* As, t = yield* j.serviceOption(ye), n = P.match(t, {
4965
+ }), Rs = () => j.gen(function* () {
4966
+ let e = yield* Is, t = yield* j.serviceOption(ve), n = P.match(t, {
4955
4967
  onNone: () => null,
4956
4968
  onSome: (e) => e.tenantId ?? null
4957
4969
  });
4958
- return n === null ? e : js(e, n);
4959
- }), Ns = "noop", Ps = () => {
4960
- let e = (e) => j.fail(new ks({
4961
- provider: Ns,
4970
+ return n === null ? e : Ls(e, n);
4971
+ }), zs = "noop", Bs = () => {
4972
+ let e = (e) => j.fail(new Fs({
4973
+ provider: zs,
4962
4974
  capability: e
4963
4975
  }));
4964
4976
  return {
4965
4977
  info: {
4966
- provider: Ns,
4978
+ provider: zs,
4967
4979
  capabilities: {
4968
4980
  track: !0,
4969
4981
  aggregate: !1,
@@ -4977,8 +4989,8 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4977
4989
  timeseries: () => e("timeseries"),
4978
4990
  topN: () => e("topN")
4979
4991
  };
4980
- }, Fs = (e) => {
4981
- if (e.length === 0) return Ps();
4992
+ }, Vs = (e) => {
4993
+ if (e.length === 0) return Bs();
4982
4994
  if (e.length === 1) return e[0];
4983
4995
  let t = {
4984
4996
  provider: "compose",
@@ -4995,7 +5007,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
4995
5007
  discard: !0
4996
5008
  }), r = (t, n) => {
4997
5009
  let r = e.find((e) => e.info.capabilities[t]);
4998
- return r === void 0 ? j.fail(new ks({
5010
+ return r === void 0 ? j.fail(new Fs({
4999
5011
  provider: "compose",
5000
5012
  capability: t
5001
5013
  })) : n(r);
@@ -5018,11 +5030,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5018
5030
  topN: (e) => r("topN", (t) => t.topN(e)),
5019
5031
  ...a === void 0 ? {} : { mirror: a }
5020
5032
  };
5021
- }, Is = (e) => {
5033
+ }, Hs = (e) => {
5022
5034
  let t = e.filter((e) => e.dispose !== void 0);
5023
5035
  return {
5024
5036
  kind: "compose",
5025
- build: (t) => Fs(e.map((e) => e.build(t))),
5037
+ build: (t) => Vs(e.map((e) => e.build(t))),
5026
5038
  tables: e.flatMap((e) => e.tables ?? []),
5027
5039
  initialize: (t) => j.forEach(e, (e) => e.initialize ? e.initialize(t) : j.void, {
5028
5040
  concurrency: 1,
@@ -5033,15 +5045,15 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5033
5045
  discard: !0
5034
5046
  }) } : {}
5035
5047
  };
5036
- }, Ls = {
5048
+ }, Us = {
5037
5049
  kind: "noop",
5038
- build: () => Ps()
5039
- }, Rs = {
5050
+ build: () => Bs()
5051
+ }, Ws = {
5040
5052
  tables: [],
5041
5053
  detach: () => {}
5042
- }, zs = (e) => {
5054
+ }, Gs = (e) => {
5043
5055
  let { store: t, sink: n, log: r } = e, i = n.mirror;
5044
- if (i === void 0 || i.tables.length === 0) return Rs;
5056
+ if (i === void 0 || i.tables.length === 0) return Ws;
5045
5057
  let a = e.run ?? ((e) => j.runPromise(e)), o = i.primaryKey ?? "id", s = new Set(i.tables), c = (e) => {
5046
5058
  if (e.op === "delete") {
5047
5059
  let t = e.old;
@@ -5065,11 +5077,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5065
5077
  tables: i.tables,
5066
5078
  detach: l
5067
5079
  };
5068
- }, Bs = (e) => {
5080
+ }, Ks = (e) => {
5069
5081
  let t = typeof e.refresh == "string" ? { interval: e.refresh } : e.refresh, n = e.strategy ?? "replace";
5070
5082
  if (n === "merge" && (e.mergeKey === void 0 || e.mergeKey.length === 0)) throw Error(`defineAggregate("${e.name}"): strategy: 'merge' requires mergeKey — the property on each row to upsert by`);
5071
5083
  if (e.incremental !== void 0) {
5072
- let t = jo({
5084
+ let t = Lo({
5073
5085
  aggregations: [{
5074
5086
  op: e.incremental.op,
5075
5087
  ...e.incremental.column === void 0 ? {} : { column: e.incremental.column }
@@ -5091,35 +5103,38 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5091
5103
  build: e.build,
5092
5104
  ...e.incremental === void 0 ? {} : { incremental: e.incremental }
5093
5105
  };
5094
- }, Vs = (e) => typeof e == "object" && !!e && e._voltroAggregate === !0, Hs = class extends I.TaggedError()("AggregateStale", {
5106
+ }, qs = (e) => typeof e == "object" && !!e && e._voltroAggregate === !0, Js = class extends I.TaggedError()("AggregateStale", {
5095
5107
  name: I.String,
5096
5108
  ageMs: I.Number,
5097
5109
  maxAgeMs: I.Number
5098
- }) {}, Us = class extends I.TaggedError()("AggregateNotFound", { name: I.String }) {}, Ws = class extends I.TaggedError()("AggregateError", {
5110
+ }) {}, Ys = class extends I.TaggedError()("AggregateNotFound", { name: I.String }) {}, Xs = class extends I.TaggedError()("AggregateError", {
5099
5111
  name: I.String,
5100
5112
  operation: I.String,
5101
5113
  cause: I.String
5102
- }) {}, Gs = class extends Ae.Tag("@voltro/AggregateRegistry")() {}, Ks = (e) => j.gen(function* () {
5103
- return (yield* Gs).getHandle(e);
5104
- }), qs = (e, n, r) => {
5114
+ }) {}, Zs = class extends Pe.Tag("@voltro/AggregateRegistry")() {}, Qs = (e) => j.gen(function* () {
5115
+ return (yield* Zs).getHandle(e);
5116
+ }), $s = (e, n, r) => {
5105
5117
  if (e.crossTenant || !n.has(e.table) || r == null) return e;
5106
5118
  let i = u("tenantId", r);
5107
5119
  return {
5108
5120
  ...e,
5109
5121
  predicate: e.predicate ? t(e.predicate, i) : i
5110
5122
  };
5111
- }, Js = (e, n) => {
5123
+ }, ec = (e, n) => {
5112
5124
  if (e.includeDeleted || !n.has(e.table)) return e;
5113
5125
  let r = x("deletedAt");
5114
5126
  return {
5115
5127
  ...e,
5116
5128
  predicate: e.predicate ? t(e.predicate, r) : r
5117
5129
  };
5118
- }, Ys = (e) => j.runPromiseExit(e).then((e) => {
5119
- if (Pe.isSuccess(e)) return e.value;
5130
+ }, tc = (e) => j.runPromiseExit(e).then((e) => {
5131
+ if (Re.isSuccess(e)) return e.value;
5120
5132
  let t = k.failureOption(e.cause);
5121
5133
  throw P.isSome(t) ? t.value : k.squash(e.cause);
5122
- }), Xs = (e, t) => e.pipe(j.provideService(ye, t)), Zs = async (e) => {
5134
+ }), nc = (e, t) => e.pipe(j.provideService(ve, t)), rc = (e, t) => {
5135
+ let n = Ce(t, e.guards);
5136
+ if (n) throw n;
5137
+ }, ic = async (e) => {
5123
5138
  let t = `${e.kind}.${e.name}`, n = Date.now(), r = "ok";
5124
5139
  try {
5125
5140
  if (e.interceptor) {
@@ -5134,7 +5149,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5134
5149
  traceId: e.requestContext.traceId,
5135
5150
  ...e.requestContext.spanId === void 0 ? {} : { spanId: e.requestContext.spanId }
5136
5151
  }), r = await j.runPromiseExit(n);
5137
- if (Pe.isSuccess(r)) return r.value;
5152
+ if (Re.isSuccess(r)) return r.value;
5138
5153
  throw k.squash(r.cause);
5139
5154
  }
5140
5155
  return await e.runExecutor();
@@ -5148,27 +5163,27 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5148
5163
  status: r
5149
5164
  });
5150
5165
  }
5151
- }, Qs = /* @__PURE__ */ new Set([1213, 1205]), $s = /* @__PURE__ */ new Set([
5166
+ }, ac = /* @__PURE__ */ new Set([1213, 1205]), oc = /* @__PURE__ */ new Set([
5152
5167
  "ER_LOCK_DEADLOCK",
5153
5168
  "ER_LOCK_WAIT_TIMEOUT",
5154
5169
  "40001",
5155
5170
  "40P01"
5156
- ]), ec = (e) => {
5171
+ ]), sc = (e) => {
5157
5172
  let t = e;
5158
5173
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
5159
5174
  let e = t;
5160
- if (typeof e.errno == "number" && Qs.has(e.errno) || typeof e.code == "string" && $s.has(e.code) || typeof e.sqlState == "string" && $s.has(e.sqlState)) return !0;
5175
+ if (typeof e.errno == "number" && ac.has(e.errno) || typeof e.code == "string" && oc.has(e.code) || typeof e.sqlState == "string" && oc.has(e.sqlState)) return !0;
5161
5176
  t = e.cause;
5162
5177
  }
5163
5178
  return !1;
5164
- }, tc = 3, nc = (e) => new Promise((t) => setTimeout(t, e)), rc = async (e) => {
5179
+ }, cc = 3, lc = (e) => new Promise((t) => setTimeout(t, e)), uc = async (e) => {
5165
5180
  for (let t = 1;; t++) try {
5166
5181
  return await e();
5167
5182
  } catch (e) {
5168
- if (t >= tc || !ec(e)) throw e;
5169
- await nc(t * 20 + Math.floor(Math.random() * 30));
5183
+ if (t >= cc || !sc(e)) throw e;
5184
+ await lc(t * 20 + Math.floor(Math.random() * 30));
5170
5185
  }
5171
- }, ic = (e) => (t, n, r) => Zs({
5186
+ }, dc = (e) => (t, n, r) => ic({
5172
5187
  name: t.descriptor.name,
5173
5188
  kind: "mutation",
5174
5189
  input: n,
@@ -5176,10 +5191,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5176
5191
  ...e.interceptor ? { interceptor: e.interceptor } : {},
5177
5192
  ...e.recordMetric ? { recordMetric: e.recordMetric } : {},
5178
5193
  runExecutor: async () => {
5179
- let i = [], a = await rc(async () => (i.length = 0, e.store.transactional(async (a) => {
5194
+ rc(t.descriptor, r.subject);
5195
+ let i = [], a = await uc(async () => (i.length = 0, e.store.transactional(async (a) => {
5180
5196
  let o = e.undoCapture?.(a), s = o ? o.tx : a, c = e.buildContext(r, s, { afterCommit: (e) => {
5181
5197
  i.push(e);
5182
- } }), l = t.executor(n, c), u = j.isEffect(l) ? await e.runEffect(Xs(l, r.subject), c.store) : await l;
5198
+ } }), l = t.executor(n, c), u = j.isEffect(l) ? await e.runEffect(nc(l, r.subject), c.store) : await l;
5183
5199
  return o && await o.persist(c.store, {
5184
5200
  tag: t.descriptor.name,
5185
5201
  subject: r.subject,
@@ -5189,25 +5205,27 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5189
5205
  for (let e of i) await e();
5190
5206
  return a;
5191
5207
  }
5192
- }), ac = (e) => e && typeof e == "object" && "descriptor" in e ? e.descriptor : e, oc = (e) => typeof e == "object" && !!e && !Array.isArray(e) && "table" in e && "order" in e, sc = (e) => {
5208
+ }), fc = (e) => e && typeof e == "object" && "descriptor" in e ? e.descriptor : e, pc = (e) => typeof e == "object" && !!e && !Array.isArray(e) && "table" in e && "order" in e, mc = (e) => {
5193
5209
  let t = e.descriptor.source;
5194
5210
  return t == null ? [] : typeof t == "string" ? [t] : [...t];
5195
- }, cc = (e) => (t, n) => (r) => {
5211
+ }, hc = (e) => (t, n) => (r) => {
5196
5212
  let i = e.buildContext(r), a = async () => {
5197
5213
  let i = e.buildContext(r), a = t.executor(n, i);
5198
- return j.isEffect(a) ? j.runPromise(e.provideEffect(Xs(a, r.subject), i.store)) : ac(await Promise.resolve(a));
5214
+ return j.isEffect(a) ? j.runPromise(e.provideEffect(nc(a, r.subject), i.store)) : fc(await Promise.resolve(a));
5199
5215
  }, o = (n) => {
5200
- let i = ac(n);
5201
- return oc(i) ? e.finalize(i, r) : {
5216
+ let i = fc(n);
5217
+ return pc(i) ? e.finalize(i, r) : {
5202
5218
  __voltroComputed: !0,
5203
5219
  value: i,
5204
- dependentTables: sc(t),
5220
+ dependentTables: mc(t),
5205
5221
  tenantId: r.subject?.tenantId ?? null,
5206
5222
  recompute: a
5207
5223
  };
5208
5224
  }, s = () => {
5209
- let a = t.executor(n, i);
5210
- return j.isEffect(a) ? e.provideEffect(Xs(a, r.subject), i.store).pipe(j.map(o)) : a instanceof Promise ? j.promise(() => a).pipe(j.map(o)) : o(a);
5225
+ let a = Ce(r.subject, t.descriptor.guards);
5226
+ if (a) return j.fail(a);
5227
+ let s = t.executor(n, i);
5228
+ return j.isEffect(s) ? e.provideEffect(nc(s, r.subject), i.store).pipe(j.map(o)) : s instanceof Promise ? j.promise(() => s).pipe(j.map(o)) : o(s);
5211
5229
  };
5212
5230
  if (!e.interceptor) return s();
5213
5231
  let c = j.suspend(() => {
@@ -5222,7 +5240,7 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5222
5240
  traceId: r.traceId,
5223
5241
  ...r.spanId === void 0 ? {} : { spanId: r.spanId }
5224
5242
  });
5225
- }, lc = (e) => (t, n, r) => Zs({
5243
+ }, gc = (e) => (t, n, r) => ic({
5226
5244
  name: t.descriptor.name,
5227
5245
  kind: "action",
5228
5246
  input: n,
@@ -5230,15 +5248,16 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5230
5248
  ...e.interceptor ? { interceptor: e.interceptor } : {},
5231
5249
  ...e.recordMetric ? { recordMetric: e.recordMetric } : {},
5232
5250
  runExecutor: async () => {
5251
+ rc(t.descriptor, r.subject);
5233
5252
  let i = e.buildContext(r), a = t.executor(n, i);
5234
- return j.isEffect(a) ? e.runEffect(Xs(a, r.subject), i.store) : a;
5253
+ return j.isEffect(a) ? e.runEffect(nc(a, r.subject), i.store) : a;
5235
5254
  }
5236
- }), uc = (e) => e instanceof Date ? e.toISOString() : typeof e == "string" && e.length > 0 ? e : null, dc = (e) => typeof e == "string" && e.length > 0 ? e : null, fc = [
5255
+ }), _c = (e) => e instanceof Date ? e.toISOString() : typeof e == "string" && e.length > 0 ? e : null, vc = (e) => typeof e == "string" && e.length > 0 ? e : null, yc = [
5237
5256
  "updatedAt",
5238
5257
  "createdAt",
5239
5258
  "updatedBy",
5240
5259
  "createdBy"
5241
- ], pc = (e) => fc.some((t) => t in e), mc = (e, t, n) => {
5260
+ ], bc = (e) => yc.some((t) => t in e), xc = (e, t, n) => {
5242
5261
  let r = {
5243
5262
  table: t.table,
5244
5263
  id: t.id,
@@ -5253,14 +5272,14 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5253
5272
  found: !1
5254
5273
  };
5255
5274
  let i = t.column === void 0 ? void 0 : e[t.column];
5256
- if (!pc(e)) return {
5275
+ if (!bc(e)) return {
5257
5276
  ...r,
5258
5277
  value: i,
5259
5278
  lastWrite: null,
5260
5279
  attribution: "none",
5261
5280
  found: !0
5262
5281
  };
5263
- let a = dc(e.updatedBy) ?? dc(e.createdBy), o = uc(e.updatedAt) ?? uc(e.createdAt);
5282
+ let a = vc(e.updatedBy) ?? vc(e.createdBy), o = _c(e.updatedAt) ?? _c(e.createdAt);
5264
5283
  return {
5265
5284
  ...r,
5266
5285
  value: i,
@@ -5272,12 +5291,12 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5272
5291
  attribution: "audit",
5273
5292
  found: !0
5274
5293
  };
5275
- }, hc = (e, t) => {
5294
+ }, Sc = (e, t) => {
5276
5295
  let n = e.map((e) => {
5277
5296
  let n = e.newValue ?? e.value, r = t.column !== void 0 && n && typeof n == "object" ? n[t.column] : e.newValue ?? e.value;
5278
5297
  return {
5279
- actor: { id: dc(e.actor) ?? dc(e.changedBy) },
5280
- at: uc(e.at) ?? uc(e.changedAt),
5298
+ actor: { id: vc(e.actor) ?? vc(e.changedBy) },
5299
+ at: _c(e.at) ?? _c(e.changedAt),
5281
5300
  ...e.traceId === void 0 ? {} : { traceId: e.traceId },
5282
5301
  value: r
5283
5302
  };
@@ -5292,12 +5311,12 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5292
5311
  history: n,
5293
5312
  found: n.length > 0
5294
5313
  };
5295
- }, gc = (e) => {
5314
+ }, Cc = (e) => {
5296
5315
  let t = e.new?.id;
5297
5316
  if (typeof t == "string") return t;
5298
5317
  let n = e.old?.id;
5299
5318
  return typeof n == "string" ? n : void 0;
5300
- }, _c = (e) => {
5319
+ }, wc = (e) => {
5301
5320
  let t = {};
5302
5321
  if (e.op === "insert") for (let [n, r] of Object.entries(e.new ?? {})) t[n] = {
5303
5322
  from: void 0,
@@ -5317,11 +5336,11 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5317
5336
  return {
5318
5337
  table: e.table,
5319
5338
  op: e.op,
5320
- id: gc(e),
5339
+ id: Cc(e),
5321
5340
  fields: t
5322
5341
  };
5323
- }, vc = (e) => {
5324
- let t = e.map(_c);
5342
+ }, Tc = (e) => {
5343
+ let t = e.map(wc);
5325
5344
  return {
5326
5345
  rows: t,
5327
5346
  summary: {
@@ -5330,21 +5349,21 @@ var q = /* @__PURE__ */ new Map(), En = (e, t) => {
5330
5349
  deletes: t.filter((e) => e.op === "delete").length
5331
5350
  }
5332
5351
  };
5333
- }, yc = class extends Error {
5352
+ }, Ec = class extends Error {
5334
5353
  constructor() {
5335
5354
  super("voltro:preview-rollback"), this.name = "PreviewRollback";
5336
5355
  }
5337
- }, bc = async (e, t) => {
5356
+ }, Dc = async (e, t) => {
5338
5357
  let n, r = !1;
5339
5358
  try {
5340
5359
  await e.transactional(async (e) => {
5341
- throw n = await t(e), r = !0, new yc();
5360
+ throw n = await t(e), r = !0, new Ec();
5342
5361
  });
5343
5362
  } catch (e) {
5344
- if (!(e instanceof yc)) throw e;
5363
+ if (!(e instanceof Ec)) throw e;
5345
5364
  }
5346
5365
  if (!r) throw Error("preview: handler did not complete");
5347
5366
  return n;
5348
- }, xc = "framework-runtime";
5367
+ }, Oc = "framework-runtime";
5349
5368
  //#endregion
5350
- export { $r as API_KEYS_TABLE, Vo as AccessDenied, Ws as AggregateError, zo as AggregateMaintainer, Us as AggregateNotFound, Gs as AggregateRegistry, Hs as AggregateStale, ks as AnalyticsCapabilityNotSupported, Os as AnalyticsError, As as AnalyticsSink, ia as CircuitBreaker, na as CircuitOpen, dr as DEFAULT_MAX_RPC_BODY_BYTES, qi as DeleteBuilder, mn as Dispatcher, la as EffectStore, At as InMemoryDataStore, vt as IndexedMatcher, dt as LinearScanMatcher, Ie as MetricBoundaries, Ns as NOOP_ANALYTICS_PROVIDER, Bi as NoRowFound, Vi as OptimisticLockError, Bo as REBAC_ADMIN_SCOPE, xc as RUNTIME_NAME, ls as ReactionRateLimiter, qn as ReplicatedDataStore, Gi as SelectBuilder, Xi as StoreOperationFailed, xt as SubscriptionRegistry, Zi as TableValidationFailed, Yi as TenantScopeViolation, To as TimelineRecorder, ro as UndoBoundaryError, ao as UndoStack, Ki as UpdateBuilder, Ni as VOLTRO_AUDIT_MIXIN_ID, Pi as VOLTRO_SOFT_DELETE_MIXIN_ID, Fi as VOLTRO_TENANT_MIXIN_ID, On as _connectionStreamCount, kn as _resetConnectionSubjectsForTest, es as _voltroRebacTuplesTable, Ka as _voltroScheduleClaimsTable, Ga as _voltroScheduleRunsTable, qa as _voltroTracesTable, Ja as _voltroUndoLogTable, ds as _voltroWakeupsTable, Ai as _voltroWorkflowEventDeliveriesTable, ki as _voltroWorkflowEventsTable, di as apiKeyManagementRoutes, Lo as applyDelta, so as applyInverse, co as applyInverses, Js as applySoftDeleteScope, qs as applyTenantScope, _o as applyUndoInvocation, Zo as assertCan, zs as attachAnalyticsMirror, pr as awaitServerListening, xn as bindConnectionSubject, ur as bindMutation, nr as bindStream, tr as bindSubscription, $n as bindSubscriptionUntyped, Fo as buildIvmState, vc as buildPreview, rs as buildRebacInterceptor, as as buildRebacReadFilter, Vn as buildSubjectKey, vr as buildTracingLayer, Nr as cachedBackend, Xo as can, Ta as cancelWakeup, jo as classifyShape, Ko as clearResourcePolicies, i as clearRetentions, sa as clearSystemStoreHandle, ba as compileCron, Is as composeAnalytics, Fs as composeAnalyticsSinks, An as connectionSubjectsSnapshot, ws as countRunningWorkflows, cn as counter, Kn as currentRoutingContext, Ln as currentTraceContext, ci as dataStoreApiKeyStore, Gr as dataStoreIdempotencyStore, Xr as dataStoreKvStore, Bs as defineAggregate, wi as defineEventTrigger, os as defineReaction, Uo as defineResourcePolicy, ya as defineSchedule, Ds as defineSubscriber, Ir as deriveKey, _c as diffChange, Ma as dueWakeups, Yo as effectiveRelations, zi as emptySchemaRegistry, Dr as envSecretsBackend, Pn as externalSpanFromTraceparent, Mt as extractDbCause, bt as fingerprintFor, Mn as formatTraceparent, oo as forwardChangeFromCdc, li as frameworkApiKeyStrategy, ln as gauge, ti as generateApiKeyToken, Sn as getConnectionSubject, Vr as getFieldCipher, Wo as getResourcePolicy, Do as getTimelineRecorder, $ as groupKeyOf, un as histogramMetric, hc as historyProvenance, Pr as httpSecretsBackend, ct as inspectWorkflow, Dn as interruptConnectionStreams, to as invertChange, Vs as isAggregateDefinition, Nt as isForeignKeyViolation, _s as isIdleNow, sr as isInfraError, io as isSafeToApply, _a as isScheduleDefinition, Ti as isWorkflowEventTriggerDefinition, Po as ivmValue, mc as lastWriteProvenance, Go as listResourcePolicies, C as listRetentions, ts as loadResourceTuples, is as loadSubjectTuples, pa as localityAwareSelector, lc as makeActionRunner, Ra as makeAdvisoryLockCoordinator, Lr as makeAesCipher, ii as makeApiKeyService, Zr as makeAsyncKv, Er as makeBufferingSpanProcessor, Wa as makeCoordinatedScheduler, fa as makeEffectStoreLayer, ji as makeEventsFacade, Rr as makeFieldCipher, Ji as makeFluentStore, vs as makeIdleGate, bi as makeLazyWorkflowFacade, ic as makeMutationRunner, vi as makePostCommitWorkflowFacade, ms as makeProcessAdapter, cc as makeQueryDescriptorProducer, ys as makeRouterActivity, Ii as makeSchemaRegistry, $a as makeUndoCapture, bs as makeWakeGate, Cs as makeWakeProxyServer, _i as makeWorkflowFacade, yi as makeWorkflowFacadeWithCallerContext, xi as makeWorkflowHandlers, Si as makeWorkflowLayers, pi as makeWorkflowRunHandle, Ea as markWakeupFired, Io as materializeIvm, ai as memoryApiKeyStore, ha as memoryReplicationAdapter, Bn as memoryRywPositionStore, xa as nextFiring, Na as nextWakeup, gs as nodeProcessSupervisor, Ps as noopAnalytics, Ls as noopAnalyticsSpec, Qr as noopKv, wn as onBindConnectionSubject, Nn as parseTraceparent, Rn as powerOfTwoSelector, bc as previewInRollback, Fa as pruneWakeups, qo as rebacPolicyGraph, nn as recordSample, sn as recordSubscriptionActive, an as recordSubscriptionDelivery, ko as recordTimelineEvent, So as redactRow, Hn as redisRywPositionStore, vo as redoUndoInvocation, En as registerConnectionStream, re as registerRetention, wa as registerWakeup, ka as releaseWakeup, zn as replicaHealth, Ar as resetSecretsBackend, ma as resolveCurrentRegion, Pt as resolveDependentTables, Ro as resolveRescan, jr as resolveSecret, Mr as resolveSecretSync, Fr as resolveSecretsBackend, yo as resolveTimelineMode, ae as retentionTtlMsFromEnv, wo as reverseEventOverRows, $o as revokedIds, ca as runAsSystem, Ts as runOrchestratorTick, Ys as runProvidedEffect, us as runReaction, Es as runSingleNodeOrchestrator, ps as runWakeLoop, Gn as runWithRoutingContext, In as runWithTraceContext, Ua as scheduleCoordinated, Br as setFieldCipher, kr as setSecretsBackend, oa as setSystemStoreHandle, Oo as setTimelineRecorderForTest, ei as sha256Hex, Ia as singleCoordinator, fn as snapshotMetrics, pn as snapshotMetricsSync, fr as startRpcServer, Ba as startScheduler, se as sweepRetention, no as synthesizeInverse, Mi as tracingHttpClientLayer, Ci as triggerWorkflow, Oa as tryClaimWakeup, Cn as unbindConnectionSubject, Ya as undoCaptureEnabled, ho as undoLogExecutor, Ks as useAggregate, Ms as useAnalytics, Qo as visibleRows, fs as wakeDueOnce, fi as workflowToRpc, Qa as wrapCaptureStore, ta as wrapStoreWithMixinBehaviour };
5369
+ export { ii as API_KEYS_TABLE, qo as AccessDenied, Xs as AggregateError, Go as AggregateMaintainer, Ys as AggregateNotFound, Zs as AggregateRegistry, Js as AggregateStale, Fs as AnalyticsCapabilityNotSupported, Ps as AnalyticsError, Is as AnalyticsSink, ua as CircuitBreaker, ca as CircuitOpen, gr as DEFAULT_MAX_RPC_BODY_BYTES, Qi as DeleteBuilder, yn as Dispatcher, ha as EffectStore, It as InMemoryDataStore, wt as IndexedMatcher, _t as LinearScanMatcher, Be as MetricBoundaries, zs as NOOP_ANALYTICS_PROVIDER, Gi as NoRowFound, Ki as OptimisticLockError, Ko as REBAC_ADMIN_SCOPE, Oc as RUNTIME_NAME, hs as ReactionRateLimiter, Qn as ReplicatedDataStore, Xi as SelectBuilder, ta as StoreOperationFailed, Dt as SubscriptionRegistry, na as TableValidationFailed, ea as TenantScopeViolation, jo as TimelineRecorder, lo as UndoBoundaryError, fo as UndoStack, Zi as UpdateBuilder, Ri as VOLTRO_AUDIT_MIXIN_ID, zi as VOLTRO_SOFT_DELETE_MIXIN_ID, Bi as VOLTRO_TENANT_MIXIN_ID, Nn as _connectionStreamCount, Pn as _resetConnectionSubjectsForTest, os as _voltroRebacTuplesTable, Qa as _voltroScheduleClaimsTable, Za as _voltroScheduleRunsTable, $a as _voltroTracesTable, eo as _voltroUndoLogTable, _s as _voltroWakeupsTable, Fi as _voltroWorkflowEventDeliveriesTable, Pi as _voltroWorkflowEventsTable, gi as apiKeyManagementRoutes, ia as applyDefined, Uo as applyDelta, mo as applyInverse, ho as applyInverses, ec as applySoftDeleteScope, $s as applyTenantScope, Co as applyUndoInvocation, rs as assertCan, Gs as attachAnalyticsMirror, vr as awaitServerListening, En as bindConnectionSubject, hr as bindMutation, sr as bindStream, or as bindSubscription, ir as bindSubscriptionUntyped, Vo as buildIvmState, Tc as buildPreview, ls as buildRebacInterceptor, ds as buildRebacReadFilter, Kn as buildSubjectKey, Cr as buildTracingLayer, Rr as cachedBackend, ns as can, ja as cancelWakeup, Lo as classifyShape, Qo as clearResourcePolicies, i as clearRetentions, pa as clearSystemStoreHandle, Ea as compileCron, Hs as composeAnalytics, Vs as composeAnalyticsSinks, Fn as connectionSubjectsSnapshot, As as countRunningWorkflows, pn as counter, Zn as currentRoutingContext, Hn as currentTraceContext, pi as dataStoreApiKeyStore, Xr as dataStoreIdempotencyStore, ti as dataStoreKvStore, Ks as defineAggregate, ki as defineEventTrigger, fs as defineReaction, Yo as defineResourcePolicy, Ta as defineSchedule, Ns as defineSubscriber, Vr as deriveKey, wc as diffChange, Ra as dueWakeups, ts as effectiveRelations, Wi as emptySchemaRegistry, Mr as envSecretsBackend, zn as externalSpanFromTraceparent, Rt as extractDbCause, Et as fingerprintFor, Ln as formatTraceparent, po as forwardChangeFromCdc, mi as frameworkApiKeyStrategy, mn as gauge, oi as generateApiKeyToken, Dn as getConnectionSubject, Kr as getFieldCipher, Xo as getResourcePolicy, No as getTimelineRecorder, $ as groupKeyOf, hn as histogramMetric, Sc as historyProvenance, zr as httpSecretsBackend, mt as inspectWorkflow, Mn as interruptConnectionStreams, so as invertChange, qs as isAggregateDefinition, zt as isForeignKeyViolation, Cs as isIdleNow, fr as isInfraError, uo as isSafeToApply, Ca as isScheduleDefinition, Ai as isWorkflowEventTriggerDefinition, Bo as ivmValue, xc as lastWriteProvenance, Zo as listResourcePolicies, C as listRetentions, ss as loadResourceTuples, us as loadSubjectTuples, ya as localityAwareSelector, gc as makeActionRunner, Wa as makeAdvisoryLockCoordinator, Hr as makeAesCipher, li as makeApiKeyService, Bt as makeAppAccess, ni as makeAsyncKv, jr as makeBufferingSpanProcessor, Xa as makeCoordinatedScheduler, va as makeEffectStoreLayer, Ii as makeEventsFacade, Ur as makeFieldCipher, $i as makeFluentStore, ws as makeIdleGate, Ti as makeLazyWorkflowFacade, dc as makeMutationRunner, Ci as makePostCommitWorkflowFacade, bs as makeProcessAdapter, hc as makeQueryDescriptorProducer, Ts as makeRouterActivity, Vi as makeSchemaRegistry, ao as makeUndoCapture, Es as makeWakeGate, ks as makeWakeProxyServer, Si as makeWorkflowFacade, wi as makeWorkflowFacadeWithCallerContext, Ei as makeWorkflowHandlers, Di as makeWorkflowLayers, vi as makeWorkflowRunHandle, Ma as markWakeupFired, Ho as materializeIvm, ui as memoryApiKeyStore, xa as memoryReplicationAdapter, Gn as memoryRywPositionStore, Da as nextFiring, za as nextWakeup, Ss as nodeProcessSupervisor, Bs as noopAnalytics, Us as noopAnalyticsSpec, ri as noopKv, kn as onBindConnectionSubject, Rn as parseTraceparent, Un as powerOfTwoSelector, Dc as previewInRollback, Va as pruneWakeups, $o as rebacPolicyGraph, cn as recordSample, fn as recordSubscriptionActive, un as recordSubscriptionDelivery, Fo as recordTimelineEvent, Oo as redactRow, qn as redisRywPositionStore, wo as redoUndoInvocation, jn as registerConnectionStream, re as registerRetention, Aa as registerWakeup, Fa as releaseWakeup, Wn as replicaHealth, Fr as resetSecretsBackend, ba as resolveCurrentRegion, Vt as resolveDependentTables, Wo as resolveRescan, Ir as resolveSecret, Lr as resolveSecretSync, Br as resolveSecretsBackend, To as resolveTimelineMode, ae as retentionTtlMsFromEnv, Ao as reverseEventOverRows, as as revokedIds, ma as runAsSystem, js as runOrchestratorTick, tc as runProvidedEffect, gs as runReaction, Ms as runSingleNodeOrchestrator, ys as runWakeLoop, Xn as runWithRoutingContext, Vn as runWithTraceContext, Ya as scheduleCoordinated, Gr as setFieldCipher, Pr as setSecretsBackend, fa as setSystemStoreHandle, Po as setTimelineRecorderForTest, ai as sha256Hex, Ha as singleCoordinator, _n as snapshotMetrics, vn as snapshotMetricsSync, _r as startRpcServer, Ka as startScheduler, se as sweepRetention, co as synthesizeInverse, Li as tracingHttpClientLayer, Oi as triggerWorkflow, Pa as tryClaimWakeup, On as unbindConnectionSubject, to as undoCaptureEnabled, xo as undoLogExecutor, Qs as useAggregate, Rs as useAnalytics, is as visibleRows, vs as wakeDueOnce, _i as workflowToRpc, io as wrapCaptureStore, sa as wrapStoreWithMixinBehaviour };