@voltro/runtime 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,26 +2,26 @@ import { Cause as e, Clock as t, Context as n, Cron as r, Deferred as i, Duratio
2
2
  import { ENCRYPTED_PREFIX as S, and as C, attachEagerLoads as w, attributionFields as T, boolean as E, clearRetentions as ee, collectSubqueries as D, contains as te, decryptFieldsOnRead as ne, deserializeArraysOnRead as re, encryptFieldsForWrite as ie, eq as O, evaluatePredicate as k, generateId as A, getRelations as ae, getTable as j, gt as oe, gte as se, hasEagerLoads as ce, id as M, inSet as le, integer as N, isEncrypted as ue, isNull as de, isTableReactive as fe, json as P, listRetentions as pe, lt as me, lte as he, missingConflictColumns as ge, missingRequiredColumns as _e, neq as ve, or as ye, planVersionedUpdate as be, queryFor as xe, raiseChangeListenerCeiling as Se, registerRetention as Ce, requireTable as we, retentionTtlMsFromEnv as Te, runWithWriteAttribution as Ee, serializeArraysForWrite as De, serverOnlyColumns as Oe, settleVersionedUpdate as ke, stampGeneratedId as Ae, startsWith as je, sweepRetention as Me, table as F, text as I, timestamp as L, walkLeaves as Ne } from "@voltro/database";
3
3
  import { createCipheriv as Pe, createDecipheriv as Fe, createHash as Ie, randomBytes as Le, randomUUID as Re, scryptSync as ze } from "node:crypto";
4
4
  import { EventEmitter as Be } from "node:events";
5
- import { ADMIN_SCOPE as Ve, APIKEY_ISSUE_ORG_SCOPE as He, APIKEY_ISSUE_OTHER_SCOPE as Ue, APIKEY_ISSUE_SELF_SCOPE as We, ConnectionHandshakeFailed as R, ConnectionInfo as Ge, ConnectionKindMismatch as Ke, ConnectionNotDeclared as qe, ConnectionSubjectRequired as Je, EventKeyInvalid as Ye, EventPayloadInvalid as Xe, EventPayloadTooLarge as Ze, MAX_EVENT_ENVELOPE_BYTES as Qe, ScopeError as $e, SubjectService as z, UndoConflict as et, UndoForbidden as tt, UndoNotFound as nt, WorkflowRunHandleSchema as rt, beginIdempotent as it, checkGuardsEffect as at, diffRows as ot, effectiveScopes as st, eventRoute as ct, failIdempotent as lt, finishIdempotent as ut, hasEffectiveScope as dt, isIdKeyed as ft, parseEventRoute as pt, publishServerError as mt, requireScope as ht, setPolicyGuardResolver as gt, systemSubject as _t, tsMs as vt, wsMutationIdempotencyScope as yt } from "@voltro/protocol";
6
- import { createLogger as B } from "@voltro/logger";
7
- import * as bt from "node:http";
8
- import { createServer as xt } from "node:http";
9
- import { HttpClient as V, HttpClientError as St, HttpClientRequest as Ct, HttpLayerRouter as H, HttpServer as wt, HttpServerRequest as Tt, HttpServerResponse as U } from "@effect/platform";
10
- import { NodeContext as Et, NodeHttpServer as Dt } from "@effect/platform-node";
11
- import { Rpc as Ot, RpcSerialization as kt, RpcServer as At } from "@effect/rpc";
12
- import { defineRestRoute as jt, dispatchSharedPath as Mt, requireAnyScope as Nt, requireScope as Pt } from "@voltro/protocol/rest";
13
- import { AsyncLocalStorage as Ft } from "node:async_hooks";
14
- import { ArrayFormatter as It, TreeFormatter as Lt } from "effect/ParseResult";
15
- import { SpanKind as Rt, SpanStatusCode as zt } from "@opentelemetry/api";
16
- import { Kv as Bt, KvError as Vt, KvStore as Ht, layerConnections as Ut, layerMemory as Wt, layerRedis as Gt } from "@voltro/kv";
17
- import { apiKeyStrategy as Kt } from "@voltro/protocol/apikey";
18
- import { getCurrentWorkflowExecutionId as qt, inspectWorkflow as Jt } from "@voltro/workflow";
19
- import { spawn as Yt } from "node:child_process";
5
+ import { ADMIN_SCOPE as Ve, APIKEY_ISSUE_ORG_SCOPE as He, APIKEY_ISSUE_OTHER_SCOPE as Ue, APIKEY_ISSUE_SELF_SCOPE as We, ConnectionHandshakeFailed as R, ConnectionInfo as Ge, ConnectionKindMismatch as Ke, ConnectionNotDeclared as qe, ConnectionSubjectRequired as Je, EventKeyInvalid as Ye, EventPayloadInvalid as Xe, EventPayloadTooLarge as Ze, MAX_EVENT_ENVELOPE_BYTES as Qe, ScopeError as $e, SubjectService as et, UndoConflict as tt, UndoForbidden as nt, UndoNotFound as rt, WorkflowRunHandleSchema as it, beginIdempotent as at, checkGuardsEffect as ot, diffRows as st, effectiveScopes as ct, eventRoute as lt, failIdempotent as ut, finishIdempotent as dt, hasEffectiveScope as ft, isIdKeyed as pt, parseEventRoute as mt, publishServerError as ht, requireScope as gt, setPolicyGuardResolver as _t, systemSubject as vt, tsMs as yt, wsMutationIdempotencyScope as bt } from "@voltro/protocol";
6
+ import { createLogger as z } from "@voltro/logger";
7
+ import * as xt from "node:http";
8
+ import { createServer as St } from "node:http";
9
+ import { HttpClient as Ct, HttpClientError as wt, HttpClientRequest as Tt, HttpLayerRouter as B, HttpServer as Et, HttpServerRequest as Dt, HttpServerResponse as V } from "@effect/platform";
10
+ import { NodeContext as Ot, NodeHttpServer as kt } from "@effect/platform-node";
11
+ import { Rpc as At, RpcSerialization as jt, RpcServer as Mt } from "@effect/rpc";
12
+ import { defineRestRoute as Nt, dispatchSharedPath as Pt, requireAnyScope as Ft, requireScope as It } from "@voltro/protocol/rest";
13
+ import { AsyncLocalStorage as Lt } from "node:async_hooks";
14
+ import { ArrayFormatter as Rt, TreeFormatter as zt } from "effect/ParseResult";
15
+ import { SpanKind as Bt, SpanStatusCode as Vt } from "@opentelemetry/api";
16
+ import { Kv as Ht, KvError as Ut, KvStore as Wt, layerConnections as Gt, layerMemory as Kt, layerRedis as qt } from "@voltro/kv";
17
+ import { apiKeyStrategy as Jt } from "@voltro/protocol/apikey";
18
+ import { getCurrentWorkflowExecutionId as Yt, inspectWorkflow as Xt } from "@voltro/workflow";
19
+ import { spawn as Zt } from "node:child_process";
20
20
  //#region src/handlerBody.ts
21
- var Xt = (e) => {
21
+ var Qt = (e) => {
22
22
  if (o.isEffect(e)) return o.runPromise(e);
23
23
  if (e instanceof Promise) return e;
24
- }, Zt = class {
24
+ }, $t = class {
25
25
  byTable = /* @__PURE__ */ new Map();
26
26
  register(e) {
27
27
  let t = this.byTable.get(e.table);
@@ -62,7 +62,7 @@ var Xt = (e) => {
62
62
  });
63
63
  return { perTable: e };
64
64
  }
65
- }, Qt = (e) => {
65
+ }, en = (e) => {
66
66
  let t = [];
67
67
  for (let n of Ne(e)) n.conjunctive && n.path === void 0 && (n.op === "eq" && t.push({
68
68
  column: n.column,
@@ -72,7 +72,7 @@ var Xt = (e) => {
72
72
  values: n.value
73
73
  }));
74
74
  return t;
75
- }, $t = (e) => {
75
+ }, tn = (e) => {
76
76
  let t = [];
77
77
  for (let n of Ne(e)) n.conjunctive && n.path === void 0 && (n.op === "gt" || n.op === "gte" || n.op === "lt" || n.op === "lte") && t.push({
78
78
  column: n.column,
@@ -80,10 +80,10 @@ var Xt = (e) => {
80
80
  threshold: n.value
81
81
  });
82
82
  return t;
83
- }, en = (e, t) => {
83
+ }, nn = (e, t) => {
84
84
  for (let n of Ne(e)) if (n.conjunctive && n.path === void 0 && n.op === "eq" && n.column === t) return n.value;
85
85
  return null;
86
- }, tn = (e, t) => {
86
+ }, rn = (e, t) => {
87
87
  let n = [];
88
88
  for (let r of e) {
89
89
  let e = t(r);
@@ -91,8 +91,8 @@ var Xt = (e) => {
91
91
  n.push(`${typeof e}:${String(e)}`);
92
92
  }
93
93
  return n.join("|");
94
- }, nn = (e, t) => e === null || t === null ? null : e === t ? 0 : typeof e == typeof t ? e > t ? 1 : -1 : null, rn = (e, t, n) => {
95
- let r = nn(e, n);
94
+ }, an = (e, t) => e === null || t === null ? null : e === t ? 0 : typeof e == typeof t ? e > t ? 1 : -1 : null, on = (e, t, n) => {
95
+ let r = an(e, n);
96
96
  if (r === null) return !1;
97
97
  switch (t) {
98
98
  case "gt": return r > 0;
@@ -100,7 +100,7 @@ var Xt = (e) => {
100
100
  case "lt": return r < 0;
101
101
  case "lte": return r <= 0;
102
102
  }
103
- }, an = class {
103
+ }, sn = class {
104
104
  columnByTable = /* @__PURE__ */ new Map();
105
105
  rangeByTable = /* @__PURE__ */ new Map();
106
106
  tupleByTable = /* @__PURE__ */ new Map();
@@ -108,9 +108,9 @@ var Xt = (e) => {
108
108
  subscriptions = /* @__PURE__ */ new Map();
109
109
  register(e) {
110
110
  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());
111
- let t = Qt(e.predicate), n = $t(e.predicate);
111
+ let t = en(e.predicate), n = tn(e.predicate);
112
112
  if (e.usingIndex !== void 0) {
113
- let r = e.usingIndex, i = tn(r.fields, (t) => en(e.predicate, t));
113
+ let r = e.usingIndex, i = rn(r.fields, (t) => nn(e.predicate, t));
114
114
  if (i !== null) {
115
115
  let a = `${r.name}|${i}`, o = this.tupleByTable.get(e.table), s = o.get(a);
116
116
  s || (s = /* @__PURE__ */ new Set(), o.set(a, s)), s.add(e.id), this.subscriptions.set(e.id, {
@@ -255,7 +255,7 @@ var Xt = (e) => {
255
255
  }
256
256
  }
257
257
  for (let [e, a] of i) {
258
- let i = tn(a, (e) => t[e]);
258
+ let i = rn(a, (e) => t[e]);
259
259
  if (i === null) continue;
260
260
  let o = r.get(`${e}|${i}`);
261
261
  if (o) for (let e of o) n.add(e);
@@ -269,7 +269,7 @@ var Xt = (e) => {
269
269
  let a = this.rangeByTable.get(e);
270
270
  if (a) for (let [e, r] of a) {
271
271
  let i = t[e];
272
- if (i !== null) for (let [e, t] of r) for (let r of t) rn(i, e, r.threshold) && n.add(r.subId);
272
+ if (i !== null) for (let [e, t] of r) for (let r of t) on(i, e, r.threshold) && n.add(r.subId);
273
273
  }
274
274
  return n;
275
275
  }
@@ -278,7 +278,7 @@ var Xt = (e) => {
278
278
  let e = t[n.column];
279
279
  if (n.kind === "eq") {
280
280
  if (e !== n.value) return !1;
281
- } else if (!rn(e, n.op, n.threshold)) return !1;
281
+ } else if (!on(e, n.op, n.threshold)) return !1;
282
282
  }
283
283
  return !0;
284
284
  }
@@ -300,23 +300,23 @@ var Xt = (e) => {
300
300
  }
301
301
  return i;
302
302
  }
303
- }, on = (e) => {
303
+ }, cn = (e) => {
304
304
  if (e == null) return null;
305
- if (Array.isArray(e)) return e.map(on);
305
+ if (Array.isArray(e)) return e.map(cn);
306
306
  if (typeof e == "object") {
307
307
  let t = e, n = Object.keys(t).sort(), r = {};
308
- for (let e of n) r[e] = on(t[e]);
308
+ for (let e of n) r[e] = cn(t[e]);
309
309
  return r;
310
310
  }
311
311
  return e;
312
- }, sn = (e, t, n) => {
313
- let r = on({
312
+ }, ln = (e, t, n) => {
313
+ let r = cn({
314
314
  table: e,
315
315
  predicate: t,
316
316
  indexHint: n ?? null
317
317
  });
318
318
  return Ie("sha256").update(JSON.stringify(r)).digest("hex").slice(0, 16);
319
- }, cn = class {
319
+ }, un = class {
320
320
  matcher;
321
321
  byFingerprint = /* @__PURE__ */ new Map();
322
322
  byClient = /* @__PURE__ */ new Map();
@@ -335,7 +335,7 @@ var Xt = (e) => {
335
335
  } catch {}
336
336
  }
337
337
  subscribe(e, t, n, r) {
338
- let i = sn(t, n, r?.name), a = this.byFingerprint.get(i);
338
+ let i = ln(t, n, r?.name), a = this.byFingerprint.get(i);
339
339
  return a ? (a.subscribers.add(e), this.byClient.set(e, i), this.notifyChange(), {
340
340
  fingerprint: i,
341
341
  deduplicated: !0
@@ -393,7 +393,7 @@ var Xt = (e) => {
393
393
  });
394
394
  return e;
395
395
  }
396
- }, ln = (e, t) => t.length === 0 ? e : [...e].sort((e, n) => {
396
+ }, dn = (e, t) => t.length === 0 ? e : [...e].sort((e, n) => {
397
397
  for (let r of t) {
398
398
  let t = e[r.column], i = n[r.column];
399
399
  if (t === i) continue;
@@ -403,7 +403,7 @@ var Xt = (e) => {
403
403
  return r.direction === "asc" ? a : -a;
404
404
  }
405
405
  return 0;
406
- }), un = (e, t, n) => {
406
+ }), fn = (e, t, n) => {
407
407
  let r = t.split("."), i = r[0], a = r.slice(1), o = (e) => typeof e == "object" && !!e && !Array.isArray(e), s = e[i], c;
408
408
  if (a.length === 0) c = o(s) && o(n) ? {
409
409
  ...s,
@@ -421,11 +421,11 @@ var Xt = (e) => {
421
421
  ...e,
422
422
  [i]: c
423
423
  };
424
- }, dn = (e, t, n) => !e || k(e, t, n), fn = (e, t) => {
424
+ }, pn = (e, t, n) => !e || k(e, t, n), H = (e, t) => {
425
425
  let n = /* @__PURE__ */ new Map();
426
426
  if (!e) return n;
427
427
  for (let r of D(e)) {
428
- let e = t.get(r.descriptor.table) ?? /* @__PURE__ */ new Map(), i = fn(r.descriptor.predicate, t), a = pn(r.descriptor, e, t, i);
428
+ let e = t.get(r.descriptor.table) ?? /* @__PURE__ */ new Map(), i = H(r.descriptor.predicate, t), a = mn(r.descriptor, e, t, i);
429
429
  if (r.kind === "exists") n.set(r.descriptor, a.length);
430
430
  else {
431
431
  let e = r.descriptor.projection, t = /* @__PURE__ */ new Set();
@@ -440,15 +440,15 @@ var Xt = (e) => {
440
440
  }
441
441
  }
442
442
  return n;
443
- }, pn = (e, t, n = /* @__PURE__ */ new Map(), r = null) => {
444
- let i = r ?? fn(e.predicate, n), a = [...t.values()].filter((t) => dn(e.predicate, t, i));
443
+ }, mn = (e, t, n = /* @__PURE__ */ new Map(), r = null) => {
444
+ let i = r ?? H(e.predicate, n), a = [...t.values()].filter((t) => pn(e.predicate, t, i));
445
445
  if (e.aggregations && e.aggregations.length > 0) {
446
- let t = mn(a, e.aggregations, e.groupBy);
446
+ let t = hn(a, e.aggregations, e.groupBy);
447
447
  if (!e.having) return t;
448
- let r = fn(e.having, n);
449
- return t.filter((t) => dn(e.having, t, r));
448
+ let r = H(e.having, n);
449
+ return t.filter((t) => pn(e.having, t, r));
450
450
  }
451
- let o = ln(a, e.order), s = e.skip ? o.slice(e.skip) : o, c = e.take === void 0 ? s : s.slice(0, e.take);
451
+ let o = dn(a, e.order), s = e.skip ? o.slice(e.skip) : o, c = e.take === void 0 ? s : s.slice(0, e.take);
452
452
  if (!e.projection) return c;
453
453
  let l = e.projection;
454
454
  return c.map((e) => {
@@ -456,7 +456,7 @@ var Xt = (e) => {
456
456
  for (let n of l) t[n] = e[n];
457
457
  return t;
458
458
  });
459
- }, mn = (e, t, n) => {
459
+ }, hn = (e, t, n) => {
460
460
  let r = /* @__PURE__ */ new Map();
461
461
  for (let t of e) {
462
462
  let e = {};
@@ -474,11 +474,11 @@ var Xt = (e) => {
474
474
  let i = [];
475
475
  for (let e of r.values()) {
476
476
  let n = { ...e.keyVals };
477
- for (let r of t) n[r.alias] = hn(r, e.rows);
477
+ for (let r of t) n[r.alias] = gn(r, e.rows);
478
478
  i.push(n);
479
479
  }
480
480
  return i;
481
- }, hn = (e, t) => {
481
+ }, gn = (e, t) => {
482
482
  switch (e.op) {
483
483
  case "count": return e.column === void 0 ? t.length : t.reduce((t, n) => t + +(n[e.column] !== null && n[e.column] !== void 0), 0);
484
484
  case "count-distinct": {
@@ -522,7 +522,7 @@ var Xt = (e) => {
522
522
  }
523
523
  default: throw Error(`computeAggregates: unknown op '${e.op}'`);
524
524
  }
525
- }, gn = "\0", _n = (e, t) => e === null ? t : `${e}${gn}${t}`, vn = class e {
525
+ }, _n = "\0", vn = (e, t) => e === null ? t : `${e}${_n}${t}`, yn = class e {
526
526
  #e;
527
527
  #t;
528
528
  #n(e) {
@@ -544,7 +544,7 @@ var Xt = (e) => {
544
544
  let n = t.id;
545
545
  n && e.set(n, t);
546
546
  }
547
- this.#e.set(_n(t, n), e);
547
+ this.#e.set(vn(t, n), e);
548
548
  }
549
549
  }
550
550
  withNamespace(t) {
@@ -555,11 +555,11 @@ var Xt = (e) => {
555
555
  }, t);
556
556
  }
557
557
  #o(e) {
558
- return _n(this.#i, e);
558
+ return vn(this.#i, e);
559
559
  }
560
560
  #s() {
561
- let e = /* @__PURE__ */ new Map(), t = this.#i === null ? null : `${this.#i}${gn}`;
562
- for (let [n, r] of this.#e) t === null ? n.includes(gn) || e.set(n, r) : n.startsWith(t) && e.set(n.slice(t.length), r);
561
+ let e = /* @__PURE__ */ new Map(), t = this.#i === null ? null : `${this.#i}${_n}`;
562
+ for (let [n, r] of this.#e) t === null ? n.includes(_n) || e.set(n, r) : n.startsWith(t) && e.set(n.slice(t.length), r);
563
563
  return e;
564
564
  }
565
565
  #c(e) {
@@ -567,7 +567,7 @@ var Xt = (e) => {
567
567
  return n || (n = /* @__PURE__ */ new Map(), this.#e.set(t, n)), n;
568
568
  }
569
569
  async query(e) {
570
- let t = pn(e, this.#e.get(this.#o(e.table)) ?? /* @__PURE__ */ new Map(), this.#s());
570
+ let t = mn(e, this.#e.get(this.#o(e.table)) ?? /* @__PURE__ */ new Map(), this.#s());
571
571
  return ce(e) ? w(t, e.eager, we(e.table), (e) => this.query(e)) : t;
572
572
  }
573
573
  async insert(e, t) {
@@ -598,7 +598,7 @@ var Xt = (e) => {
598
598
  if (!i) return null;
599
599
  let a = i.get(t);
600
600
  if (!a) return null;
601
- let o = un(a, n, r);
601
+ let o = fn(a, n, r);
602
602
  return i.set(t, o), this.#n({
603
603
  table: e,
604
604
  op: "update",
@@ -640,7 +640,7 @@ var Xt = (e) => {
640
640
  async updateMany(e, t, n) {
641
641
  let r = this.#e.get(this.#o(e));
642
642
  if (!r) return 0;
643
- let i = fn(n.where, this.#s()), a = 0;
643
+ let i = H(n.where, this.#s()), a = 0;
644
644
  for (let [o, s] of r) {
645
645
  if (!k(n.where, s, i)) continue;
646
646
  let c = {
@@ -659,7 +659,7 @@ var Xt = (e) => {
659
659
  async deleteMany(e, t) {
660
660
  let n = this.#e.get(this.#o(e));
661
661
  if (!n) return 0;
662
- let r = fn(t.where, this.#s()), i = [];
662
+ let r = H(t.where, this.#s()), i = [];
663
663
  for (let [e, a] of n) k(t.where, a, r) && i.push([e, a]);
664
664
  for (let [t, r] of i) n.delete(t), this.#n({
665
665
  table: e,
@@ -698,7 +698,7 @@ var Xt = (e) => {
698
698
  }
699
699
  }
700
700
  async transactional(e) {
701
- let t = new yn(this.#d());
701
+ let t = new bn(this.#d());
702
702
  try {
703
703
  let n = await e(t);
704
704
  return t.commit(), n;
@@ -734,7 +734,7 @@ var Xt = (e) => {
734
734
  allocateNumericId: (e) => this.#l(e)
735
735
  };
736
736
  }
737
- }, yn = class {
737
+ }, bn = class {
738
738
  parent;
739
739
  overlay = /* @__PURE__ */ new Map();
740
740
  tombstones = /* @__PURE__ */ new Map();
@@ -764,7 +764,7 @@ var Xt = (e) => {
764
764
  return t || (t = /* @__PURE__ */ new Map(), this.overlay.set(e, t)), t;
765
765
  }
766
766
  async query(e) {
767
- let t = this.buildTablesView(e), n = pn(e, this.materialise(e.table), t);
767
+ let t = this.buildTablesView(e), n = mn(e, this.materialise(e.table), t);
768
768
  return ce(e) ? w(n, e.eager, we(e.table), (e) => this.query(e)) : n;
769
769
  }
770
770
  async insert(e, t) {
@@ -804,7 +804,7 @@ var Xt = (e) => {
804
804
  async patchJson(e, t, n, r) {
805
805
  let i = this.materialise(e).get(t);
806
806
  if (!i) return null;
807
- let a = un(i, n, r);
807
+ let a = fn(i, n, r);
808
808
  return this.getOrCreateOverlay(e).set(t, a), this.events.push({
809
809
  table: e,
810
810
  op: "update",
@@ -825,7 +825,7 @@ var Xt = (e) => {
825
825
  }), !0;
826
826
  }
827
827
  async updateMany(e, t, n) {
828
- let r = this.materialise(e), i = fn(n.where, this.buildTablesViewForPred(n.where)), a = 0;
828
+ let r = this.materialise(e), i = H(n.where, this.buildTablesViewForPred(n.where)), a = 0;
829
829
  for (let [o, s] of r) {
830
830
  if (!k(n.where, s, i)) continue;
831
831
  let r = {
@@ -842,7 +842,7 @@ var Xt = (e) => {
842
842
  return a;
843
843
  }
844
844
  async deleteMany(e, t) {
845
- let n = this.materialise(e), r = fn(t.where, this.buildTablesViewForPred(t.where)), i = 0, a = this.tombstones.get(e);
845
+ let n = this.materialise(e), r = H(t.where, this.buildTablesViewForPred(t.where)), i = 0, a = this.tombstones.get(e);
846
846
  for (let [o, s] of n) k(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({
847
847
  table: e,
848
848
  op: "delete",
@@ -905,7 +905,7 @@ var Xt = (e) => {
905
905
  discard() {
906
906
  this.settled || (this.settled = !0, this.overlay.clear(), this.tombstones.clear(), this.events.length = 0);
907
907
  }
908
- }, bn = (e) => {
908
+ }, xn = (e) => {
909
909
  let t = {}, n = [], r = e;
910
910
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
911
911
  let e = r;
@@ -916,26 +916,26 @@ var Xt = (e) => {
916
916
  (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = e.cause;
917
917
  }
918
918
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
919
- }, xn = (e) => {
919
+ }, Sn = (e) => {
920
920
  let t = e.dbCode;
921
921
  return t === "23503" || e.dbErrno === 1452 || t === 547 || t === "SQLITE_CONSTRAINT_FOREIGNKEY";
922
- }, Sn = (e) => {
922
+ }, Cn = (e) => {
923
923
  let t = e.dbCode, n = e.dbErrno;
924
924
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
925
- }, Cn = (e) => ({
926
- has: (t) => dt(e, t),
927
- hasAny: (t) => t.some((t) => dt(e, t)),
928
- require: (t) => ht(e, t),
925
+ }, wn = (e) => ({
926
+ has: (t) => ft(e, t),
927
+ hasAny: (t) => t.some((t) => ft(e, t)),
928
+ require: (t) => gt(e, t),
929
929
  get scopes() {
930
- return st(e);
930
+ return ct(e);
931
931
  }
932
- }), wn = (e) => {
932
+ }), Tn = (e) => {
933
933
  let t = /* @__PURE__ */ new Set();
934
- return Tn(e, t), t;
935
- }, Tn = (e, t) => {
936
- if (t.add(e.table), e.eager !== void 0 && En(e.table, e.eager, t), e.setOp !== void 0) for (let n of e.setOp.queries) Tn(n, t);
937
- if (e.ctes !== void 0) for (let n of e.ctes) Tn(n.descriptor, t);
938
- }, En = (e, t, n) => {
934
+ return En(e, t), t;
935
+ }, En = (e, t) => {
936
+ if (t.add(e.table), e.eager !== void 0 && Dn(e.table, e.eager, t), e.setOp !== void 0) for (let n of e.setOp.queries) En(n, t);
937
+ if (e.ctes !== void 0) for (let n of e.ctes) En(n.descriptor, t);
938
+ }, Dn = (e, t, n) => {
939
939
  let r = ae(e);
940
940
  if (r !== void 0) for (let [e, i] of Object.entries(t)) {
941
941
  let t = r[e];
@@ -943,24 +943,24 @@ var Xt = (e) => {
943
943
  let a = i === !0 ? {} : i;
944
944
  if (t.kind === "manyToMany") {
945
945
  let e = t.through().tableName, r = t.target().tableName;
946
- n.add(e), n.add(r), a.with !== void 0 && En(r, a.with, n);
946
+ n.add(e), n.add(r), a.with !== void 0 && Dn(r, a.with, n);
947
947
  } else {
948
948
  let e = t.target().tableName;
949
- n.add(e), a.with !== void 0 && En(e, a.with, n);
949
+ n.add(e), a.with !== void 0 && Dn(e, a.with, n);
950
950
  }
951
951
  }
952
- }, Dn = (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-")), On = /* @__PURE__ */ new Set(["*"]), kn = (e, t) => {
952
+ }, On = (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-")), kn = /* @__PURE__ */ new Set(["*"]), An = (e, t) => {
953
953
  if (e !== void 0) {
954
954
  if ("not" in e) {
955
- kn(e.not, t);
955
+ An(e.not, t);
956
956
  return;
957
957
  }
958
958
  if ("and" in e) {
959
- for (let n of e.and) kn(n, t);
959
+ for (let n of e.and) An(n, t);
960
960
  return;
961
961
  }
962
962
  if ("or" in e) {
963
- for (let n of e.or) kn(n, t);
963
+ for (let n of e.or) An(n, t);
964
964
  return;
965
965
  }
966
966
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -969,11 +969,11 @@ var Xt = (e) => {
969
969
  }
970
970
  e.op === "exists" || e.op === "not-exists" || t.add(e.column);
971
971
  }
972
- }, W = (e, t, n) => {
972
+ }, U = (e, t, n) => {
973
973
  let r = e.get(t);
974
974
  r === void 0 && (r = /* @__PURE__ */ new Set(), e.set(t, r));
975
975
  for (let e of n) r.add(e);
976
- }, An = (e, t, n) => {
976
+ }, jn = (e, t, n) => {
977
977
  let r = ae(e);
978
978
  if (r !== void 0) for (let [i, a] of Object.entries(t)) {
979
979
  let t = r[i];
@@ -981,50 +981,50 @@ var Xt = (e) => {
981
981
  let o = a === !0 ? {} : a;
982
982
  if (t.kind === "manyToMany") {
983
983
  let r = t.through(), i = t.target();
984
- W(n, r.tableName, [t.sourceKey, t.targetKey]), W(n, e, ["id"]), W(n, i.tableName, ["id"]), jn(i.tableName, o, n), o.with !== void 0 && An(i.tableName, o.with, n);
984
+ U(n, r.tableName, [t.sourceKey, t.targetKey]), U(n, e, ["id"]), U(n, i.tableName, ["id"]), Mn(i.tableName, o, n), o.with !== void 0 && jn(i.tableName, o.with, n);
985
985
  continue;
986
986
  }
987
987
  let s = t.target();
988
- 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"]), jn(s.tableName, o, n), o.with !== void 0 && An(s.tableName, o.with, n);
988
+ 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"]), Mn(s.tableName, o, n), o.with !== void 0 && jn(s.tableName, o.with, n);
989
989
  }
990
- }, jn = (e, t, n) => {
990
+ }, Mn = (e, t, n) => {
991
991
  if (t.where !== void 0) {
992
992
  let r = /* @__PURE__ */ new Set();
993
- kn(t.where, r), W(n, e, r);
993
+ An(t.where, r), U(n, e, r);
994
994
  }
995
- t.orderBy !== void 0 && W(n, e, t.orderBy.map((e) => e.column));
995
+ t.orderBy !== void 0 && U(n, e, t.orderBy.map((e) => e.column));
996
996
  let r = j(e);
997
- r === void 0 ? W(n, e, ["*"]) : W(n, e, Object.keys(r.fields));
998
- }, Mn = (e) => {
997
+ r === void 0 ? U(n, e, ["*"]) : U(n, e, Object.keys(r.fields));
998
+ }, Nn = (e) => {
999
999
  let t = /* @__PURE__ */ new Map();
1000
- if (Dn(e)) {
1001
- for (let n of wn(e)) W(t, n, ["*"]);
1000
+ if (On(e)) {
1001
+ for (let n of Tn(e)) U(t, n, ["*"]);
1002
1002
  return t;
1003
1003
  }
1004
1004
  let n = /* @__PURE__ */ new Set();
1005
1005
  if (e.projection !== void 0) for (let t of e.projection) n.add(t);
1006
1006
  else n.add("*");
1007
- kn(e.predicate, n);
1007
+ An(e.predicate, n);
1008
1008
  for (let t of e.order) n.add(t.column);
1009
- return W(t, e.table, n), e.eager !== void 0 && An(e.table, e.eager, t), t;
1010
- }, Nn = (e) => {
1011
- if (e.op === "insert" || e.op === "delete" || e.old === null || e.new === null) return On;
1009
+ return U(t, e.table, n), e.eager !== void 0 && jn(e.table, e.eager, t), t;
1010
+ }, Pn = (e) => {
1011
+ if (e.op === "insert" || e.op === "delete" || e.old === null || e.new === null) return kn;
1012
1012
  let t = /* @__PURE__ */ new Set(), n = e.old, r = e.new, i = /* @__PURE__ */ new Set([...Object.keys(n), ...Object.keys(r)]);
1013
1013
  for (let e of i) Object.is(n[e], r[e]) || t.add(e);
1014
1014
  return t;
1015
- }, Pn = (e, t) => {
1015
+ }, Fn = (e, t) => {
1016
1016
  let n = t.get(e.table);
1017
1017
  if (n === void 0) return !1;
1018
1018
  if (n.has("*")) return !0;
1019
- let r = Nn(e);
1019
+ let r = Pn(e);
1020
1020
  if (r.has("*")) return !0;
1021
1021
  for (let e of r) if (n.has(e)) return !0;
1022
1022
  return !1;
1023
- }, Fn = p.exponential({
1023
+ }, W = p.exponential({
1024
1024
  start: .001,
1025
1025
  factor: 2,
1026
1026
  count: 16
1027
- }), In = f.counter("voltro_rpc_requests_total", { description: "Total RPC handler invocations." }), Ln = f.counter("voltro_rpc_errors_total", { description: "RPC handler invocations that errored." }), Rn = f.histogram("voltro_rpc_duration_seconds", Fn, "RPC handler duration in seconds."), zn = f.counter("voltro_http_requests_total", { description: "Total HTTP route invocations." }), Bn = f.histogram("voltro_http_duration_seconds", Fn, "HTTP route duration in seconds."), Vn = f.histogram("voltro_plugin_hook_duration_seconds", Fn, "Plugin interceptor duration in seconds."), Hn = f.counter("voltro_plugin_hook_errors_total", { description: "Plugin interceptor invocations that errored." }), Un = f.counter("voltro_subscription_deliveries_total", { description: "Total subscription deliveries (snapshot + delta)." }), Wn = f.histogram("voltro_subscription_delivery_seconds", Fn, "Subscription delivery produce→push latency in seconds."), Gn = f.gauge("voltro_subscriptions_active", { description: "Currently-open subscriptions." }), Kn = f.counter("voltro_schedule_runs_total", { description: "Schedule firings by name + outcome." }), qn = f.histogram("voltro_schedule_duration_seconds", Fn, "Schedule handler duration in seconds."), Jn = f.gauge("voltro_schedule_last_success_timestamp_seconds", { description: "UNIX time of the last successful firing, per schedule." }), Yn = f.counter("voltro_workflow_runs_total", { description: "Workflow run terminal outcomes by name + status." }), Xn = f.histogram("voltro_workflow_duration_seconds", Fn, "Workflow run duration in seconds."), Zn = f.gauge("voltro_workflow_last_success_timestamp_seconds", { description: "UNIX time of the last successful run, per workflow." }), Qn = f.counter("voltro_event_published_total", { description: "Events published, by event name." }), $n = f.counter("voltro_event_deliveries_total", { description: "Event deliveries handed to a subscriber, by event name." }), er = f.counter("voltro_event_dropped_total", { description: "Event deliveries a subscriber provably lost, by event name + reason." }), tr = f.gauge("voltro_event_subscribers", { description: "Currently-attached event subscribers, by event name." }), nr = /* @__PURE__ */ new Map(), rr = (e, t, n) => {
1027
+ }), In = f.counter("voltro_rpc_requests_total", { description: "Total RPC handler invocations." }), Ln = f.counter("voltro_rpc_errors_total", { description: "RPC handler invocations that errored." }), Rn = f.histogram("voltro_rpc_duration_seconds", W, "RPC handler duration in seconds."), zn = f.counter("voltro_http_requests_total", { description: "Total HTTP route invocations." }), Bn = f.histogram("voltro_http_duration_seconds", W, "HTTP route duration in seconds."), Vn = f.histogram("voltro_plugin_hook_duration_seconds", W, "Plugin interceptor duration in seconds."), Hn = f.counter("voltro_plugin_hook_errors_total", { description: "Plugin interceptor invocations that errored." }), Un = f.counter("voltro_subscription_deliveries_total", { description: "Total subscription deliveries (snapshot + delta)." }), Wn = f.histogram("voltro_subscription_delivery_seconds", W, "Subscription delivery produce→push latency in seconds."), Gn = f.gauge("voltro_subscriptions_active", { description: "Currently-open subscriptions." }), Kn = f.counter("voltro_schedule_runs_total", { description: "Schedule firings by name + outcome." }), qn = f.histogram("voltro_schedule_duration_seconds", W, "Schedule handler duration in seconds."), Jn = f.gauge("voltro_schedule_last_success_timestamp_seconds", { description: "UNIX time of the last successful firing, per schedule." }), Yn = f.counter("voltro_workflow_runs_total", { description: "Workflow run terminal outcomes by name + status." }), Xn = f.histogram("voltro_workflow_duration_seconds", W, "Workflow run duration in seconds."), Zn = f.gauge("voltro_workflow_last_success_timestamp_seconds", { description: "UNIX time of the last successful run, per workflow." }), Qn = f.counter("voltro_event_published_total", { description: "Events published, by event name." }), $n = f.counter("voltro_event_deliveries_total", { description: "Event deliveries handed to a subscriber, by event name." }), er = f.counter("voltro_event_dropped_total", { description: "Event deliveries a subscriber provably lost, by event name + reason." }), tr = f.gauge("voltro_event_subscribers", { description: "Currently-attached event subscribers, by event name." }), nr = /* @__PURE__ */ new Map(), rr = (e, t, n) => {
1028
1028
  let r = nr.get(t);
1029
1029
  if (r !== void 0) return r;
1030
1030
  let i = e;
@@ -1055,7 +1055,7 @@ var Xt = (e) => {
1055
1055
  }, gr = (e) => {
1056
1056
  let t = f.increment(Yn).pipe(o.tagMetrics("workflow", e.name), o.tagMetrics("status", e.status)), n = f.update(Xn, e.durationMs / 1e3).pipe(o.tagMetrics("workflow", e.name)), r = e.status === "succeeded" && e.completedAtSec !== void 0 ? f.set(Zn, e.completedAtSec).pipe(o.tagMetrics("workflow", e.name)) : o.void;
1057
1057
  o.runSync(o.zipRight(t, o.zipRight(n, r)));
1058
- }, _r = (e, t) => f.counter(e, t === void 0 ? {} : { description: t }), vr = (e, t) => f.gauge(e, t === void 0 ? {} : { description: t }), yr = (e, t = Fn, n) => f.histogram(e, t, n), br = (e) => {
1058
+ }, _r = (e, t) => f.counter(e, t === void 0 ? {} : { description: t }), vr = (e, t) => f.gauge(e, t === void 0 ? {} : { description: t }), yr = (e, t = W, n) => f.histogram(e, t, n), br = (e) => {
1059
1059
  let t = {};
1060
1060
  for (let n of e) t[n.key] = n.value;
1061
1061
  return t;
@@ -1128,7 +1128,7 @@ var Xt = (e) => {
1128
1128
  ...t,
1129
1129
  predicate: n
1130
1130
  };
1131
- }, G = B({ scope: "voltro:dispatcher" }), Pr = (e) => Array.isArray(e) ? e.length : e == null ? 0 : 1, Fr = (e) => typeof e == "object" && !!e && e._tag === "ScopeError", Ir = class {
1131
+ }, G = z({ scope: "voltro:dispatcher" }), Pr = (e) => Array.isArray(e) ? e.length : e == null ? 0 : 1, Fr = (e) => typeof e == "object" && !!e && e._tag === "ScopeError", Ir = class {
1132
1132
  deps;
1133
1133
  subscriptionRegistry;
1134
1134
  matcher;
@@ -1138,12 +1138,12 @@ var Xt = (e) => {
1138
1138
  computedSubs = /* @__PURE__ */ new Map();
1139
1139
  computedByTable = /* @__PURE__ */ new Map();
1140
1140
  constructor(e) {
1141
- this.deps = e, this.matcher = new an(), this.subscriptionRegistry = new cn(this.matcher), this.unsubscribeChange = e.store.onChange((e) => {
1141
+ this.deps = e, this.matcher = new sn(), this.subscriptionRegistry = new un(this.matcher), this.unsubscribeChange = e.store.onChange((e) => {
1142
1142
  this.handleChange(e);
1143
1143
  });
1144
1144
  }
1145
1145
  async subscribe(e, t, n, r, i, a, o, s) {
1146
- let c = `sub_${Re()}`, l = i ?? `subscription.${e.table}`, u = wn(e), d = Mn(e);
1146
+ let c = `sub_${Re()}`, l = i ?? `subscription.${e.table}`, u = Tn(e), d = Nn(e);
1147
1147
  e.predicate !== void 0 && this.subscriptionRegistry.subscribe(c, e.table, e.predicate, r);
1148
1148
  for (let e of u) {
1149
1149
  let t = this.dependentByTable.get(e);
@@ -1356,7 +1356,7 @@ var Xt = (e) => {
1356
1356
  G.trace("missing subscription", { subscriberId: n });
1357
1357
  continue;
1358
1358
  }
1359
- if (!t && !Pn(e, r.relevantFields)) {
1359
+ if (!t && !Fn(e, r.relevantFields)) {
1360
1360
  s++;
1361
1361
  continue;
1362
1362
  }
@@ -1381,7 +1381,7 @@ var Xt = (e) => {
1381
1381
  }
1382
1382
  t = Nr(e, r.baseDescriptor);
1383
1383
  }
1384
- let a = JSON.stringify(on(t)), s = c.get(a);
1384
+ let a = JSON.stringify(cn(t)), s = c.get(a);
1385
1385
  s === void 0 && (s = this.deps.store.query(t), c.set(a, s));
1386
1386
  let u = await s, d = r.lastDelivered;
1387
1387
  if (Rr(u, d)) {
@@ -1391,11 +1391,11 @@ var Xt = (e) => {
1391
1391
  });
1392
1392
  continue;
1393
1393
  }
1394
- if (r.lastDelivered = u, this.deps.cache !== void 0 && r.cacheBinding !== void 0 && this.deps.cache.put(r.cacheBinding, Array.from(r.dependentTables), u), ft(d) && ft(u)) {
1394
+ if (r.lastDelivered = u, this.deps.cache !== void 0 && r.cacheBinding !== void 0 && this.deps.cache.put(r.cacheBinding, Array.from(r.dependentTables), u), pt(d) && pt(u)) {
1395
1395
  let e = l.get(a);
1396
1396
  e === void 0 && (e = /* @__PURE__ */ new Map(), l.set(a, e));
1397
1397
  let t = e.get(d);
1398
- t === void 0 && (t = ot(d, u), e.set(d, t)), r.emit({
1398
+ t === void 0 && (t = st(d, u), e.set(d, t)), r.emit({
1399
1399
  _tag: "delta",
1400
1400
  revision: o,
1401
1401
  emittedAt: o,
@@ -1500,7 +1500,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
1500
1500
  spanId: t.spanId,
1501
1501
  sampled: t.sampled
1502
1502
  });
1503
- }, ii = new Ft(), ai = (e, t) => ii.run(e, t), oi = () => ii.getStore(), si = (e) => /^[0-9a-f]{64}$/i.test(e) ? Buffer.from(e, "hex") : ze(e, "voltro:field-encryption:v1", 32), ci = (e) => {
1503
+ }, ii = new Lt(), ai = (e, t) => ii.run(e, t), oi = () => ii.getStore(), si = (e) => /^[0-9a-f]{64}$/i.test(e) ? Buffer.from(e, "hex") : ze(e, "voltro:field-encryption:v1", 32), ci = (e) => {
1504
1504
  if (e.length !== 32) throw Error(`field cipher key must be 32 bytes, got ${e.length}`);
1505
1505
  return {
1506
1506
  encrypt: (t) => {
@@ -1525,7 +1525,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
1525
1525
  let t = q();
1526
1526
  if (!t) throw Error(`decryptField: ${fi}`);
1527
1527
  return t.decrypt(e);
1528
- }, hi = new Ft(), gi = /* @__PURE__ */ new Set(), _i = /* @__PURE__ */ new Set(), vi = "\0", yi = process.env.VOLTRO_OBSERVE_GRAPH === "1", bi = () => {
1528
+ }, hi = new Lt(), gi = /* @__PURE__ */ new Set(), _i = /* @__PURE__ */ new Set(), vi = "\0", yi = process.env.VOLTRO_OBSERVE_GRAPH === "1", bi = () => {
1529
1529
  yi = !0;
1530
1530
  }, xi = () => yi, Si = (e, t) => yi ? (_i.add(e.tag), hi.run(e, t)) : t(), Ci = (e, t) => {
1531
1531
  if (!yi) return;
@@ -1823,8 +1823,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
1823
1823
  try {
1824
1824
  return await r();
1825
1825
  } catch (t) {
1826
- let r = bn(t);
1827
- if (xn(r)) {
1826
+ let r = xn(t);
1827
+ if (Sn(r)) {
1828
1828
  let t = n.tenantId, i = `${r.dbConstraint ?? ""} ${r.dbColumn ?? ""} ${r.dbMessage ?? ""} ${r.dbCauseChain ?? ""}`.toLowerCase();
1829
1829
  if (i.includes("tenantid") || /\btenants\b/.test(i) || t != null && i.includes(String(t).toLowerCase())) throw new Ii({
1830
1830
  table: e,
@@ -1847,7 +1847,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
1847
1847
  if (r === void 0) return n;
1848
1848
  let i = y.decodeUnknownEither(r)(n);
1849
1849
  if (i._tag === "Right") return n;
1850
- let a = It.formatErrorSync(i.left).map((e) => ({
1850
+ let a = Rt.formatErrorSync(i.left).map((e) => ({
1851
1851
  path: e.path.length === 0 ? "<root>" : e.path.join("."),
1852
1852
  message: e.message
1853
1853
  })), o = a[0];
@@ -1886,7 +1886,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
1886
1886
  if (i === void 0) return n;
1887
1887
  let a = y.decodeUnknownEither(i)(n);
1888
1888
  if (a._tag === "Right") return n;
1889
- let o = It.formatErrorSync(a.left).map((e) => ({
1889
+ let o = Rt.formatErrorSync(a.left).map((e) => ({
1890
1890
  path: e.path.length === 0 ? "<root>" : e.path.join("."),
1891
1891
  message: e.message
1892
1892
  })), s = o[0];
@@ -1898,7 +1898,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
1898
1898
  }, m = t.dialect, h = (e, t) => {
1899
1899
  let n = j(e);
1900
1900
  return ie(m ? De(t, n, m) : t, n, q());
1901
- }, g = process.env.VOLTRO_FIELD_DECRYPT_ON_ERROR === "null" ? "null" : "throw", _ = B({ scope: "store.fieldEncryption" }), v = /* @__PURE__ */ new Set(), b = (e) => {
1901
+ }, g = process.env.VOLTRO_FIELD_DECRYPT_ON_ERROR === "null" ? "null" : "throw", _ = z({ scope: "store.fieldEncryption" }), v = /* @__PURE__ */ new Set(), b = (e) => {
1902
1902
  let t = `${e.table}.${e.column}`;
1903
1903
  v.has(t) || (v.add(t), _.warn("encrypted column degraded to null — could not decrypt with the active key", {
1904
1904
  table: e.table,
@@ -2281,7 +2281,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2281
2281
  return o.size;
2282
2282
  }
2283
2283
  };
2284
- }, Zi = B({ scope: "voltro:replication" }), Qi = new Ft(), $i = (e, t) => Qi.run(e, t), ea = () => Qi.getStore(), ta = class {
2284
+ }, Zi = z({ scope: "voltro:replication" }), Qi = new Lt(), $i = (e, t) => Qi.run(e, t), ea = () => Qi.getStore(), ta = class {
2285
2285
  primary;
2286
2286
  replicas;
2287
2287
  adapter;
@@ -2501,7 +2501,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2501
2501
  emitRouting(e) {
2502
2502
  this.recordRouting?.(e);
2503
2503
  }
2504
- }, na = (e) => new Promise((t) => setTimeout(t, e)), ra = (e) => {
2504
+ }, na = (e) => new Promise((t) => setTimeout(t, e)), ra = (e, t, n) => {
2505
+ if (t === void 0) return e;
2506
+ let r = t * 1e3 - Date.now();
2507
+ return r <= 0 ? n : b.interruptWhen(e, o.sleep(a.millis(r)));
2508
+ }, ia = (e) => {
2505
2509
  let t = e.indexOf(".");
2506
2510
  if (t <= 0) return;
2507
2511
  let n = e.slice(0, t), r = e.slice(t + 1);
@@ -2515,25 +2519,25 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2515
2519
  kind: n
2516
2520
  };
2517
2521
  }
2518
- }, ia = (e, t) => {
2519
- let n = ra(e);
2522
+ }, aa = (e, t) => {
2523
+ let n = ia(e);
2520
2524
  return n === void 0 ? t() : Si(n, t);
2521
- }, aa = (e, t, n, r) => e === "subject" ? `${t}:s:${n}` : e === "global" ? `${t}:global` : r.tenantId == null ? void 0 : `${t}:t:${r.tenantId}`, oa = (e, t) => o.async((n) => {
2525
+ }, oa = (e, t, n, r) => e === "subject" ? `${t}:s:${n}` : e === "global" ? `${t}:global` : r.tenantId == null ? void 0 : `${t}:t:${r.tenantId}`, sa = (e, t) => o.async((n) => {
2522
2526
  let r = Ee(t, () => o.runFork(e));
2523
2527
  return r.addObserver((e) => {
2524
2528
  n(e);
2525
2529
  }), o.asVoid(l.interrupt(r));
2526
- }), sa = (e, t, n) => ({
2530
+ }), ca = (e, t, n) => ({
2527
2531
  subject: e,
2528
2532
  traceId: t?.traceId ?? Re(),
2529
2533
  ...t?.spanId === void 0 ? {} : { spanId: t.spanId },
2530
2534
  ...n === void 0 ? {} : { clientId: n }
2531
- }), ca = o.currentSpan.pipe(o.catchAll(() => o.succeed(void 0))), la = (e) => ({
2535
+ }), la = o.currentSpan.pipe(o.catchAll(() => o.succeed(void 0))), ua = (e) => ({
2532
2536
  traceId: e.traceId,
2533
2537
  ...e.spanId === void 0 ? {} : { spanId: e.spanId }
2534
- }), ua = (e, t, n) => {
2538
+ }), da = (e, t, n) => {
2535
2539
  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));
2536
- }, da = (e) => {
2540
+ }, fa = (e) => {
2537
2541
  if (Dr() !== void 0) return async () => {
2538
2542
  let t = await o.runPromise(o.either(kr(e, (e) => {
2539
2543
  console.error("[voltro] row filter failed to load — subscription", e);
@@ -2541,13 +2545,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2541
2545
  if (t._tag === "Left") throw t.left;
2542
2546
  return t.right;
2543
2547
  };
2544
- }, fa = (e, t, n, r, i, a, s, c) => b.asyncScoped((l) => o.gen(function* () {
2548
+ }, pa = (e, t, n, r, i, a, s, c) => b.asyncScoped((l) => o.gen(function* () {
2545
2549
  let u = yield* o.tryPromise(() => t.subscribe(e, (e) => {
2546
2550
  l.single(e);
2547
2551
  }, n, r, i, a, s, c)).pipe(o.matchCause({
2548
- onFailure: (e) => (Sa(`subscription.${i}`, n.traceId, e), {
2552
+ onFailure: (e) => (Ca(`subscription.${i}`, n.traceId, e), {
2549
2553
  ok: !1,
2550
- error: Ea(e)
2554
+ error: Da(e)
2551
2555
  }),
2552
2556
  onSuccess: (e) => ({
2553
2557
  ok: !0,
@@ -2568,20 +2572,20 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2568
2572
  });
2569
2573
  yield* o.addFinalizer(() => o.sync(() => e()));
2570
2574
  }
2571
- })), pa = /* @__PURE__ */ new Set(), ma = () => {
2572
- pa.clear();
2573
- }, ha = (e) => {
2574
- pa.has(e) || (pa.add(e), process.stderr.write(`[voltro] ${e}: \`cache:\` is declared but NOT applied — this query's handler returns a computed value, and the snapshot cache only wraps a store read. Every subscriber re-runs the handler. Either return a query descriptor (so the read can be cached), or drop \`cache:\` so the declaration matches what happens.\n`));
2575
- }, ga = (e, t, n, r) => b.asyncScoped((i) => o.gen(function* () {
2575
+ })), ma = /* @__PURE__ */ new Set(), ha = () => {
2576
+ ma.clear();
2577
+ }, ga = (e) => {
2578
+ ma.has(e) || (ma.add(e), process.stderr.write(`[voltro] ${e}: \`cache:\` is declared but NOT applied — this query's handler returns a computed value, and the snapshot cache only wraps a store read. Every subscriber re-runs the handler. Either return a query descriptor (so the read can be cached), or drop \`cache:\` so the declaration matches what happens.\n`));
2579
+ }, _a = (e, t, n, r) => b.asyncScoped((i) => o.gen(function* () {
2576
2580
  let a = yield* o.tryPromise(() => t.subscribeComputed(e, (e) => {
2577
2581
  i.single(e._tag === "snapshot" ? {
2578
2582
  ...e,
2579
2583
  computed: !0
2580
2584
  } : e);
2581
2585
  }, n, r)).pipe(o.matchCause({
2582
- onFailure: (e) => (Sa(`subscription.${r}`, n.traceId, e), {
2586
+ onFailure: (e) => (Ca(`subscription.${r}`, n.traceId, e), {
2583
2587
  ok: !1,
2584
- error: Ea(e)
2588
+ error: Da(e)
2585
2589
  }),
2586
2590
  onSuccess: (e) => ({
2587
2591
  ok: !0,
@@ -2602,16 +2606,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2602
2606
  });
2603
2607
  yield* o.addFinalizer(() => o.sync(() => e()));
2604
2608
  }
2605
- })), _a = (e, t, n = "rpc.subscription", r, i, a, s) => b.unwrap(o.gen(function* () {
2606
- let c = yield* z, l = yield* Ge, u = yield* ca;
2607
- ua(u, n, c);
2608
- let d = sa(c, u, l.clientId), f = Yi(c.id, l.clientId), p = $i({ subjectKey: f }, () => ai({
2609
+ })), va = (e, t, n = "rpc.subscription", r, i, a, s) => b.unwrap(o.gen(function* () {
2610
+ let c = yield* et, l = yield* Ge, u = yield* la;
2611
+ da(u, n, c);
2612
+ let d = ca(c, u, l.clientId), f = Yi(c.id, l.clientId), p = $i({ subjectKey: f }, () => ai({
2609
2613
  traceId: d.traceId,
2610
2614
  ...d.spanId === void 0 ? {} : { spanId: d.spanId }
2611
- }, () => ia(n, () => e(d)))), m = o.isEffect(p) ? yield* p.pipe(o.matchCause({
2612
- onFailure: (e) => (Sa(`subscription.${n}`, d.traceId, e), {
2615
+ }, () => aa(n, () => e(d)))), m = o.isEffect(p) ? yield* p.pipe(o.matchCause({
2616
+ onFailure: (e) => (Ca(`subscription.${n}`, d.traceId, e), {
2613
2617
  ok: !1,
2614
- error: Ea(e)
2618
+ error: Da(e)
2615
2619
  }),
2616
2620
  onSuccess: (e) => ({
2617
2621
  ok: !0,
@@ -2626,44 +2630,44 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2626
2630
  error: m.error
2627
2631
  });
2628
2632
  let h = m.value;
2629
- if (zr(h)) return i !== void 0 && ha(n), ga(h, t, d, n);
2630
- let g = h, _ = r?.(g), v = i === void 0 ? void 0 : aa(i.scope, i.baseKey, f, c);
2631
- return fa(g, t, d, _, n, i === void 0 || v === void 0 ? void 0 : {
2633
+ if (zr(h)) return i !== void 0 && ga(n), _a(h, t, d, n);
2634
+ let g = h, _ = r?.(g), v = i === void 0 ? void 0 : oa(i.scope, i.baseKey, f, c);
2635
+ return ra(pa(g, t, d, _, n, i === void 0 || v === void 0 ? void 0 : {
2632
2636
  key: v,
2633
2637
  ttlMs: i.ttlMs,
2634
2638
  swrMs: i.swrMs
2635
- }, a?.(c), s?.(c) ?? da(c));
2636
- }).pipe(o.withSpan(n, { attributes: { "framework.kind": "subscription" } }))), va = (e, t = "rpc.stream") => b.unwrap(o.gen(function* () {
2637
- let n = yield* z, r = yield* Ge, a = yield* ca;
2638
- ua(a, t, n);
2639
- let s = sa(n, a, r.clientId), c = ia(t, () => e(s)), l = o.isEffect(c) ? yield* c.pipe(o.orDie) : c;
2640
- if (s.clientId === void 0) return l;
2641
- let u = s.clientId;
2639
+ }, a?.(c), s?.(c) ?? fa(c)), l.credentialExpiresAt, b.empty);
2640
+ }).pipe(o.withSpan(n, { attributes: { "framework.kind": "subscription" } }))), ya = (e, t = "rpc.stream", n, r) => b.unwrap(o.gen(function* () {
2641
+ let a = yield* et, s = yield* Ge, c = yield* la;
2642
+ da(c, t, a);
2643
+ let l = ca(a, c, s.clientId), u = aa(t, () => e(l)), d = o.isEffect(u) ? yield* u.pipe(o.orDie) : u, f = n === void 0 || n.length === 0 ? void 0 : () => ot(a, n, r), p = ra(f === void 0 ? d : b.unwrap(f().pipe(o.map((e) => e ? b.fail(e) : b.flatMap(d, (e) => b.unwrap(f().pipe(o.map((t) => t ? b.fail(t) : b.make(e)))))))), s.credentialExpiresAt, b.empty);
2644
+ if (l.clientId === void 0) return p;
2645
+ let m = l.clientId;
2642
2646
  return b.unwrapScoped(o.gen(function* () {
2643
- let e = yield* i.make(), t = Yr(u, () => {
2647
+ let e = yield* i.make(), t = Yr(m, () => {
2644
2648
  i.unsafeDone(e, o.void);
2645
2649
  });
2646
- return yield* o.addFinalizer(() => o.sync(() => t())), l.pipe(b.interruptWhen(i.await(e)));
2650
+ return yield* o.addFinalizer(() => o.sync(() => t())), p.pipe(b.interruptWhen(i.await(e)));
2647
2651
  }));
2648
- }).pipe(o.withSpan(t, { attributes: { "framework.kind": "stream" } }))), ya = B({ scope: "voltro:rpc" }), ba = B({ scope: "voltro:http" }), xa = B({ scope: "voltro:shutdown" }), Sa = (t, n, r) => {
2652
+ }).pipe(o.withSpan(t, { attributes: { "framework.kind": "stream" } }))), ba = z({ scope: "voltro:rpc" }), xa = z({ scope: "voltro:http" }), Sa = z({ scope: "voltro:shutdown" }), Ca = (t, n, r) => {
2649
2653
  if (e.isInterruptedOnly(r)) return;
2650
- let i = e.squash(r), a = i?._tag, o = i instanceof Error ? i.message : i?.message ?? String(i), s = e.dieOption(r)._tag === "Some", c = bn(i), l = {
2654
+ let i = e.squash(r), a = i?._tag, o = i instanceof Error ? i.message : i?.message ?? String(i), s = e.dieOption(r)._tag === "Some", c = xn(i), l = {
2651
2655
  traceId: n,
2652
2656
  ...a === void 0 ? {} : { errorTag: a },
2653
2657
  ...c
2654
2658
  }, u = o === "Failed to execute statement" && typeof c.dbMessage == "string" ? c.dbMessage : o;
2655
- s ? ya.error(`${t} failed: ${u}`, l) : ya.warn(`${t} failed: ${u}`, l);
2656
- }, Ca = /* @__PURE__ */ new Set([
2659
+ s ? ba.error(`${t} failed: ${u}`, l) : ba.warn(`${t} failed: ${u}`, l);
2660
+ }, wa = /* @__PURE__ */ new Set([
2657
2661
  "SqlError",
2658
2662
  "ResultLengthMismatch",
2659
2663
  "FieldDecryptionError"
2660
- ]), wa = (e) => typeof e == "object" && !!e && typeof e._tag == "string" && Ca.has(e._tag), Ta = (e) => ({
2664
+ ]), Ta = (e) => typeof e == "object" && !!e && typeof e._tag == "string" && wa.has(e._tag), Ea = (e) => ({
2661
2665
  _tag: "InternalError",
2662
2666
  message: "internal server error",
2663
2667
  traceId: e
2664
- }), Ea = (t) => {
2668
+ }), Da = (t) => {
2665
2669
  let n = e.squash(t);
2666
- if (n && typeof n == "object" && n._tag === "UnknownException" && (n = n.error ?? n.cause ?? n), wa(n)) return {
2670
+ if (n && typeof n == "object" && n._tag === "UnknownException" && (n = n.error ?? n.cause ?? n), Ta(n)) return {
2667
2671
  _tag: "InternalError",
2668
2672
  message: "internal server error"
2669
2673
  };
@@ -2675,7 +2679,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2675
2679
  ...typeof a == "string" ? { _tag: a } : {},
2676
2680
  message: typeof o == "string" ? o : String(n)
2677
2681
  };
2678
- }, Da = (e) => {
2682
+ }, Oa = (e) => {
2679
2683
  if (e === void 0) return;
2680
2684
  let t = y.encodeUnknownSync(e), n = y.decodeUnknownSync(e);
2681
2685
  return {
@@ -2694,23 +2698,23 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2694
2698
  }
2695
2699
  }
2696
2700
  };
2697
- }, Oa = (e) => ({
2701
+ }, ka = (e) => ({
2698
2702
  _tag: "MutationInFlight",
2699
2703
  message: "a request with this idempotency key is already in flight",
2700
2704
  traceId: e
2701
- }), ka = (e, t, n = "rpc.mutation", r, i) => o.gen(function* () {
2702
- let a = yield* z, s = yield* Ge, c = yield* ca;
2703
- ua(c, n, a);
2704
- let l = sa(a, c, s.clientId), u = i && s.idempotencyKey ? {
2705
+ }), Aa = (e, t, n = "rpc.mutation", r, i) => o.gen(function* () {
2706
+ let a = yield* et, s = yield* Ge, c = yield* la;
2707
+ da(c, n, a);
2708
+ let l = ca(a, c, s.clientId), u = i && s.idempotencyKey ? {
2705
2709
  store: i.store,
2706
2710
  ttlMs: i.ttlMs,
2707
2711
  key: s.idempotencyKey,
2708
- scope: yt(a.tenantId, Wi(a), n)
2712
+ scope: bt(a.tenantId, Wi(a), n)
2709
2713
  } : null;
2710
2714
  if (u) {
2711
- let e = yield* o.promise(() => it(u.store, u.scope, u.key, u.ttlMs, Date.now()));
2715
+ let e = yield* o.promise(() => at(u.store, u.scope, u.key, u.ttlMs, Date.now()));
2712
2716
  if (e.kind === "replay") return r ? r.decode(e.response.body) : e.response.body;
2713
- if (e.kind === "conflict") return yield* o.die(Oa(l.traceId));
2717
+ if (e.kind === "conflict") return yield* o.die(ka(l.traceId));
2714
2718
  }
2715
2719
  let d = Yi(a.id, s.clientId), f = {
2716
2720
  traceId: l.traceId,
@@ -2719,40 +2723,40 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2719
2723
  }, p = $i({ subjectKey: d }, () => ai({
2720
2724
  traceId: l.traceId,
2721
2725
  ...l.spanId === void 0 ? {} : { spanId: l.spanId }
2722
- }, () => Ee(f, () => ia(n, () => e(t, l))))), m = o.isEffect(p) ? oa(p, f) : o.tryPromise({
2726
+ }, () => Ee(f, () => aa(n, () => e(t, l))))), m = o.isEffect(p) ? sa(p, f) : o.tryPromise({
2723
2727
  try: () => Promise.resolve(p),
2724
2728
  catch: (e) => e
2725
2729
  });
2726
- return yield* (u ? m.pipe(o.tap((e) => o.promise(() => ut(u.store, u.scope, u.key, {
2730
+ return yield* (u ? m.pipe(o.tap((e) => o.promise(() => dt(u.store, u.scope, u.key, {
2727
2731
  status: 200,
2728
2732
  body: r ? r.encode(e) : e
2729
- }, Date.now())).pipe(o.ignore)), o.tapErrorCause(() => o.promise(() => lt(u.store, u.scope, u.key)).pipe(o.ignore))) : m).pipe(o.tapErrorCause((e) => o.sync(() => Sa(n, l.traceId, e))), o.catchIf(wa, () => o.die(Ta(l.traceId))), o.annotateLogs(la(l)));
2730
- }).pipe(o.withSpan(n, { attributes: { "framework.kind": "mutation" } })), Aa = 8 * 1024 * 1024, ja = (t) => {
2731
- let n = t.port ?? 4e3, r = t.host, i = t.path ?? "/ws", a = xt(), s = (e) => Tt.HttpServerRequest.pipe(o.flatMap((e) => o.gen(function* () {
2732
- if (!t.inspectRoute) return U.text("inspect route not configured", { status: 404 });
2733
+ }, Date.now())).pipe(o.ignore)), o.tapErrorCause(() => o.promise(() => ut(u.store, u.scope, u.key)).pipe(o.ignore))) : m).pipe(o.tapErrorCause((e) => o.sync(() => Ca(n, l.traceId, e))), o.catchIf(Ta, () => o.die(Ea(l.traceId))), o.annotateLogs(ua(l)));
2734
+ }).pipe(o.withSpan(n, { attributes: { "framework.kind": "mutation" } })), ja = 8 * 1024 * 1024, Ma = (t) => {
2735
+ let n = t.port ?? 4e3, r = t.host, i = t.path ?? "/ws", a = St(), s = (e) => Dt.HttpServerRequest.pipe(o.flatMap((e) => o.gen(function* () {
2736
+ if (!t.inspectRoute) return V.text("inspect route not configured", { status: 404 });
2733
2737
  let n = {};
2734
2738
  for (let [t, r] of Object.entries(e.headers)) r !== void 0 && (n[t.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
2735
2739
  let r;
2736
2740
  e.method !== "GET" && e.method !== "HEAD" && e.method !== "OPTIONS" && (r = yield* e.text.pipe(o.orElseSucceed(() => "")));
2737
2741
  let i = t.inspectRoute.handle(e.url, n, e.method, r), a = i instanceof Promise ? yield* o.promise(() => i) : i;
2738
- return a === null ? U.text("inspect route not found", { status: 404 }) : U.text(a.body, {
2742
+ return a === null ? V.text("inspect route not found", { status: 404 }) : V.text(a.body, {
2739
2743
  status: a.status,
2740
2744
  contentType: a.contentType,
2741
2745
  headers: a.headers ?? {}
2742
2746
  });
2743
- }))), c = () => Tt.HttpServerRequest.pipe(o.flatMap((e) => {
2747
+ }))), c = () => Dt.HttpServerRequest.pipe(o.flatMap((e) => {
2744
2748
  let n = t.inspectStream;
2745
- if (!n) return o.succeed(U.text("inspect stream not configured", { status: 404 }));
2749
+ if (!n) return o.succeed(V.text("inspect stream not configured", { status: 404 }));
2746
2750
  let r = {};
2747
2751
  for (let [t, n] of Object.entries(e.headers)) n !== void 0 && (r[t.toLowerCase()] = Array.isArray(n) ? n.join(", ") : n);
2748
2752
  let i = n.corsHeaders(r.origin);
2749
- if (n.isDisabled()) return o.succeed(U.text(JSON.stringify({ error: "inspect disabled (VOLTRO_INSPECT=off)" }), {
2753
+ if (n.isDisabled()) return o.succeed(V.text(JSON.stringify({ error: "inspect disabled (VOLTRO_INSPECT=off)" }), {
2750
2754
  status: 503,
2751
2755
  contentType: "application/json; charset=utf-8",
2752
2756
  headers: i
2753
2757
  }));
2754
2758
  let a = n.authorize(r);
2755
- if (!a.ok) return o.succeed(U.text(JSON.stringify({
2759
+ if (!a.ok) return o.succeed(V.text(JSON.stringify({
2756
2760
  error: "unauthorized",
2757
2761
  reason: a.reason
2758
2762
  }), {
@@ -2775,7 +2779,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2775
2779
  clearInterval(r), t();
2776
2780
  }));
2777
2781
  }));
2778
- return o.succeed(U.stream(h, {
2782
+ return o.succeed(V.stream(h, {
2779
2783
  status: 200,
2780
2784
  headers: {
2781
2785
  "content-type": "text/event-stream; charset=utf-8",
@@ -2785,23 +2789,23 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2785
2789
  ...i
2786
2790
  }
2787
2791
  }));
2788
- })), d = H.add("*", "/_voltro/inspect/*", Tt.HttpServerRequest.pipe(o.flatMap((e) => o.gen(function* () {
2789
- if (!t.inspectRoute) return U.text("inspect route not configured", { status: 404 });
2792
+ })), d = B.add("*", "/_voltro/inspect/*", Dt.HttpServerRequest.pipe(o.flatMap((e) => o.gen(function* () {
2793
+ if (!t.inspectRoute) return V.text("inspect route not configured", { status: 404 });
2790
2794
  let n = {};
2791
2795
  for (let [t, r] of Object.entries(e.headers)) r !== void 0 && (n[t.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
2792
2796
  let r;
2793
2797
  e.method !== "GET" && e.method !== "HEAD" && e.method !== "OPTIONS" && (r = yield* e.text.pipe(o.orElseSucceed(() => "")));
2794
2798
  let i = t.inspectRoute.handle(e.url, n, e.method, r), a = i instanceof Promise ? yield* o.promise(() => i) : i;
2795
- return a === null ? U.text("inspect route not found", { status: 404 }) : U.text(a.body, {
2799
+ return a === null ? V.text("inspect route not found", { status: 404 }) : V.text(a.body, {
2796
2800
  status: a.status,
2797
2801
  contentType: a.contentType,
2798
2802
  headers: a.headers ?? {}
2799
2803
  });
2800
2804
  })))), f = u.empty;
2801
- t.inspectRoute !== void 0 && (f = t.inspectStream === void 0 ? u.mergeAll(H.add("*", "/_voltro/inspect", s(!0)), d) : u.mergeAll(H.add("GET", "/_voltro/inspect/stream", c()), H.add("*", "/_voltro/inspect", s(!0)), d));
2805
+ t.inspectRoute !== void 0 && (f = t.inspectStream === void 0 ? u.mergeAll(B.add("*", "/_voltro/inspect", s(!0)), d) : u.mergeAll(B.add("GET", "/_voltro/inspect/stream", c()), B.add("*", "/_voltro/inspect", s(!0)), d));
2802
2806
  let p = u.empty;
2803
2807
  if (t.webhookRoutes !== void 0 && t.webhookRoutes.size > 0) {
2804
- let e = (e) => Tt.HttpServerRequest.pipe(o.flatMap((t) => o.gen(function* () {
2808
+ let e = (e) => Dt.HttpServerRequest.pipe(o.flatMap((t) => o.gen(function* () {
2805
2809
  let n = {};
2806
2810
  for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
2807
2811
  let r = t.method !== "GET" && t.method !== "HEAD" ? yield* t.text.pipe(o.orElseSucceed(() => "")) : "", i = new TextEncoder().encode(r), a = t.url.split("?")[0], s = ri(n.traceparent), c = yield* o.promise(() => e.handle({
@@ -2816,16 +2820,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2816
2820
  },
2817
2821
  ...s ? { parent: s } : {}
2818
2822
  }));
2819
- return U.text(c.body, {
2823
+ return V.text(c.body, {
2820
2824
  status: c.status,
2821
2825
  contentType: c.contentType
2822
2826
  });
2823
- }))), n = Array.from(t.webhookRoutes.entries()).map(([t, n]) => H.add("*", t, e(n)));
2827
+ }))), n = Array.from(t.webhookRoutes.entries()).map(([t, n]) => B.add("*", t, e(n)));
2824
2828
  p = u.mergeAll(...n);
2825
2829
  }
2826
2830
  let m = u.empty;
2827
2831
  if (t.httpRoutes !== void 0 && t.httpRoutes.length > 0) {
2828
- let n = (n) => Tt.HttpServerRequest.pipe(o.flatMap((e) => o.gen(function* () {
2832
+ let n = (n) => Dt.HttpServerRequest.pipe(o.flatMap((e) => o.gen(function* () {
2829
2833
  let r = {};
2830
2834
  for (let [t, n] of Object.entries(e.headers)) n !== void 0 && (r[t.toLowerCase()] = Array.isArray(n) ? n.join(", ") : n);
2831
2835
  let i = e.url.indexOf("?"), a = i >= 0 ? e.url.slice(0, i) : e.url, s = i >= 0 ? e.url.slice(i + 1) : "", c = e.method !== "GET" && e.method !== "HEAD" ? new Uint8Array(yield* e.arrayBuffer.pipe(o.orElseSucceed(() => /* @__PURE__ */ new ArrayBuffer(0)))) : /* @__PURE__ */ new Uint8Array(), l = t.getStore?.(), u = {
@@ -2835,8 +2839,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2835
2839
  headers: r,
2836
2840
  rawBody: c,
2837
2841
  ...l === void 0 ? {} : { store: l }
2838
- }, d = yield* o.promise(() => Mt(n, u));
2839
- d.status >= 500 && ba.warn(`${e.method} ${a} → ${d.status}`, {
2842
+ }, d = yield* o.promise(() => Pt(n, u));
2843
+ d.status >= 500 && xa.warn(`${e.method} ${a} → ${d.status}`, {
2840
2844
  method: e.method,
2841
2845
  path: a,
2842
2846
  status: d.status,
@@ -2859,7 +2863,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2859
2863
  a !== void 0 && clearInterval(a), i();
2860
2864
  }));
2861
2865
  }));
2862
- return U.stream(i, {
2866
+ return V.stream(i, {
2863
2867
  status: d.status,
2864
2868
  headers: {
2865
2869
  ...f,
@@ -2870,45 +2874,45 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2870
2874
  }
2871
2875
  });
2872
2876
  }
2873
- return d.body instanceof Uint8Array ? U.uint8Array(d.body, p) : U.text(d.body ?? "", p);
2874
- })), o.tapErrorCause((t) => e.isInterruptedOnly(t) ? o.void : o.sync(() => ba.error(`${n.map((e) => e.method).join("|")} ${n[0].path} threw`, { path: n[0].path }, e.squash(t))))), r = /* @__PURE__ */ new Map();
2877
+ return d.body instanceof Uint8Array ? V.uint8Array(d.body, p) : V.text(d.body ?? "", p);
2878
+ })), o.tapErrorCause((t) => e.isInterruptedOnly(t) ? o.void : o.sync(() => xa.error(`${n.map((e) => e.method).join("|")} ${n[0].path} threw`, { path: n[0].path }, e.squash(t))))), r = /* @__PURE__ */ new Map();
2875
2879
  for (let e of t.httpRoutes) {
2876
2880
  let t = r.get(e.path);
2877
2881
  t ? t.push(e) : r.set(e.path, [e]);
2878
2882
  }
2879
2883
  let i = [...r.entries()].flatMap(([e, t]) => {
2880
2884
  let r = t.length === 1 ? t[0].method : "*", i = n(t);
2881
- return [H.add(r, e, i), H.add(r, `${e}/*`, i)];
2885
+ return [B.add(r, e, i), B.add(r, `${e}/*`, i)];
2882
2886
  });
2883
2887
  m = u.mergeAll(...i);
2884
2888
  }
2885
- let h = At.layerProtocolWebsocketRouter({ path: i }), g = At.layer(t.group), _ = At.layer(t.group).pipe(u.provide(At.layerProtocolHttpRouter({ path: "/rpc" })), u.provide(kt.layerJson), u.provide(t.httpHandlersLayer ?? t.handlersLayer)), v = u.scopedDiscard(o.gen(function* () {
2886
- let e = yield* At.Protocol;
2889
+ let h = Mt.layerProtocolWebsocketRouter({ path: i }), g = Mt.layer(t.group), _ = Mt.layer(t.group).pipe(u.provide(Mt.layerProtocolHttpRouter({ path: "/rpc" })), u.provide(jt.layerJson), u.provide(t.httpHandlersLayer ?? t.handlersLayer)), v = u.scopedDiscard(o.gen(function* () {
2890
+ let e = yield* Mt.Protocol;
2887
2891
  yield* o.forkScoped(o.gen(function* () {
2888
2892
  let t = yield* e.disconnects.take;
2889
2893
  Kr(t), Xr(t);
2890
2894
  }).pipe(o.forever));
2891
- })), y = u.mergeAll(g, v).pipe(u.provide(h), u.provide(kt.layerJson), u.provide(t.handlersLayer)), x = u.mergeAll(y, _, f, p, m), S = t.pluginHttpInterceptor, C = t.healthCheck, w = Number(process.env.VOLTRO_MAX_RPC_BODY_BYTES), T = t.maxRpcBodyBytes ?? (Number.isFinite(w) && w > 0 ? w : 8388608), E = { "cache-control": "no-store" }, ee = (e) => o.gen(function* () {
2892
- let t = yield* Tt.HttpServerRequest, n = {};
2895
+ })), y = u.mergeAll(g, v).pipe(u.provide(h), u.provide(jt.layerJson), u.provide(t.handlersLayer)), x = u.mergeAll(y, _, f, p, m), S = t.pluginHttpInterceptor, C = t.healthCheck, w = Number(process.env.VOLTRO_MAX_RPC_BODY_BYTES), T = t.maxRpcBodyBytes ?? (Number.isFinite(w) && w > 0 ? w : 8388608), E = { "cache-control": "no-store" }, ee = (e) => o.gen(function* () {
2896
+ let t = yield* Dt.HttpServerRequest, n = {};
2893
2897
  for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
2894
2898
  let r = t.url.indexOf("?"), i = r === -1 ? t.url : t.url.slice(0, r);
2895
2899
  if (t.method === "POST" && i === "/rpc") {
2896
2900
  let e = n["content-length"];
2897
- if (e !== void 0 && Number(e) > T) return U.text("rpc payload too large", {
2901
+ if (e !== void 0 && Number(e) > T) return V.text("rpc payload too large", {
2898
2902
  status: 413,
2899
2903
  headers: E
2900
2904
  });
2901
2905
  }
2902
- if (C && (i === "/internal/liveness" || i === "/internal/readiness")) return i === "/internal/liveness" ? U.text("ok", {
2906
+ if (C && (i === "/internal/liveness" || i === "/internal/readiness")) return i === "/internal/liveness" ? V.text("ok", {
2903
2907
  status: 200,
2904
2908
  headers: E
2905
- }) : C.isReady() ? C.ping && !(yield* o.tryPromise(() => C.ping()).pipe(o.orElseSucceed(() => !1))) ? U.text("not-ready: dependency", {
2909
+ }) : C.isReady() ? C.ping && !(yield* o.tryPromise(() => C.ping()).pipe(o.orElseSucceed(() => !1))) ? V.text("not-ready: dependency", {
2906
2910
  status: 503,
2907
2911
  headers: E
2908
- }) : U.text("ready", {
2912
+ }) : V.text("ready", {
2909
2913
  status: 200,
2910
2914
  headers: E
2911
- }) : U.text("not-ready", {
2915
+ }) : V.text("not-ready", {
2912
2916
  status: 503,
2913
2917
  headers: E
2914
2918
  });
@@ -2925,32 +2929,32 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2925
2929
  headers: n,
2926
2930
  remoteAddr: l
2927
2931
  })).pipe(o.orElseSucceed(() => null));
2928
- return u === null ? yield* e : U.text(u.body ?? "", {
2932
+ return u === null ? yield* e : V.text(u.body ?? "", {
2929
2933
  status: u.status,
2930
2934
  ...u.headers ? { headers: u.headers } : {}
2931
2935
  });
2932
- }), D = u.unwrapEffect(H.toHttpEffect(x).pipe(o.map((e) => wt.serve(ee(e))))).pipe(u.provide(Dt.layer(() => a, r === void 0 ? { port: n } : {
2936
+ }), D = u.unwrapEffect(B.toHttpEffect(x).pipe(o.map((e) => Et.serve(ee(e))))).pipe(u.provide(kt.layer(() => a, r === void 0 ? { port: n } : {
2933
2937
  port: n,
2934
2938
  host: r
2935
- })), u.provide(Et.layer));
2939
+ })), u.provide(Ot.layer));
2936
2940
  t.tracerLayer && (D = D.pipe(u.provide(t.tracerLayer)));
2937
- let te = B({ scope: "voltro:rpc" }), ne = u.launch(D).pipe(o.catchAllCause((t) => o.sync(() => {
2941
+ let te = z({ scope: "voltro:rpc" }), ne = u.launch(D).pipe(o.catchAllCause((t) => o.sync(() => {
2938
2942
  te.error("rpc server crashed", {}, e.squash(t)), process.exit(1);
2939
2943
  }))), re = o.runFork(ne);
2940
- return Ma.add(re), Va(), {
2944
+ return Na.add(re), Ha(), {
2941
2945
  server: a,
2942
2946
  shutdown: async () => {
2943
- Ma.delete(re), await o.runPromise(l.interrupt(re)).then(() => void 0, () => void 0);
2947
+ Na.delete(re), await o.runPromise(l.interrupt(re)).then(() => void 0, () => void 0);
2944
2948
  }
2945
2949
  };
2946
- }, Ma = /* @__PURE__ */ new Set(), Na = /* @__PURE__ */ new Set(), Pa = !1, Fa = (e) => (Na.add(e), () => {
2947
- Na.delete(e);
2948
- }), Ia = 1e4, La = 1e3, Ra = 3e5, za = () => {
2950
+ }, Na = /* @__PURE__ */ new Set(), Pa = /* @__PURE__ */ new Set(), Fa = !1, Ia = (e) => (Pa.add(e), () => {
2951
+ Pa.delete(e);
2952
+ }), La = 1e4, Ra = 1e3, za = 3e5, Ba = () => {
2949
2953
  let e = process.env.VOLTRO_SHUTDOWN_GRACE_MS;
2950
- if (e === void 0 || e === "") return Ia;
2954
+ if (e === void 0 || e === "") return La;
2951
2955
  let t = Number(e);
2952
- return !Number.isFinite(t) || t <= 0 ? Ia : Math.min(Ra, Math.max(La, Math.trunc(t)));
2953
- }, Ba = (e) => {
2956
+ return !Number.isFinite(t) || t <= 0 ? La : Math.min(za, Math.max(Ra, Math.trunc(t)));
2957
+ }, Va = (e) => {
2954
2958
  let t = Date.now(), n = !1, r = (r) => () => {
2955
2959
  n || (n = !0, clearTimeout(i), e.onOutcome?.({
2956
2960
  reason: r,
@@ -2958,23 +2962,23 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2958
2962
  }), e.exit());
2959
2963
  }, i = setTimeout(r("deadline"), e.deadlineMs);
2960
2964
  i.unref?.(), Promise.all(e.hooks.map((e) => Promise.resolve().then(e).then(() => void 0, () => void 0))).then(() => Promise.all(e.fibers.map((e) => o.runPromise(l.interrupt(e)).then(() => void 0, () => void 0)))).then(r("drained"), r("drained"));
2961
- }, Va = () => {
2962
- if (Pa) return;
2963
- Pa = !0;
2965
+ }, Ha = () => {
2966
+ if (Fa) return;
2967
+ Fa = !0;
2964
2968
  let e = () => {
2965
- let e = [...Ma], t = [...Na];
2966
- Ma.clear(), Na.clear(), Ba({
2969
+ let e = [...Na], t = [...Pa];
2970
+ Na.clear(), Pa.clear(), Va({
2967
2971
  fibers: e,
2968
2972
  hooks: t,
2969
- deadlineMs: za(),
2973
+ deadlineMs: Ba(),
2970
2974
  exit: () => process.exit(0),
2971
2975
  onOutcome: ({ reason: e, ms: t }) => {
2972
- e === "drained" ? xa.info(`drained in ${t}ms`) : xa.error(`drain deadline exceeded — cut at ${t}ms`, { hint: "a shutdown hook or a pool drain did not complete; whatever had not finished did not happen" });
2976
+ e === "drained" ? Sa.info(`drained in ${t}ms`) : Sa.error(`drain deadline exceeded — cut at ${t}ms`, { hint: "a shutdown hook or a pool drain did not complete; whatever had not finished did not happen" });
2973
2977
  }
2974
2978
  });
2975
2979
  };
2976
2980
  process.once("SIGINT", e), process.once("SIGTERM", e);
2977
- }, Ha = (e, t = 1e4) => new Promise((n, r) => {
2981
+ }, Ua = (e, t = 1e4) => new Promise((n, r) => {
2978
2982
  if (e.listening) {
2979
2983
  n();
2980
2984
  return;
@@ -2990,13 +2994,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
2990
2994
  o(e);
2991
2995
  }
2992
2996
  a = setTimeout(() => o(/* @__PURE__ */ Error(`rpc server did not bind within ${t}ms`)), t), e.on("listening", s), e.on("error", c);
2993
- }), Ua = () => {
2997
+ }), Wa = () => {
2994
2998
  let e = process.env.FRAMEWORK_TRACING?.toLowerCase();
2995
2999
  return e === "console" || e === "otlp" || e === "off" ? e : process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ? "otlp" : "off";
2996
- }, Wa = () => {
3000
+ }, Ga = () => {
2997
3001
  let e = process.env.FRAMEWORK_METRICS?.toLowerCase();
2998
3002
  return e === "console" || e === "otlp" || e === "off" ? e : process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ? "otlp" : "off";
2999
- }, Ga = async () => {
3003
+ }, Ka = async () => {
3000
3004
  let [e, t, n, r, i] = await Promise.all([
3001
3005
  import("@opentelemetry/sdk-trace-base"),
3002
3006
  import("@opentelemetry/sdk-metrics"),
@@ -3011,7 +3015,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3011
3015
  otlpMetrics: r,
3012
3016
  nodeSdk: i
3013
3017
  };
3014
- }, Ka = (e, t, n) => {
3018
+ }, qa = (e, t, n) => {
3015
3019
  let { PeriodicExportingMetricReader: r, ConsoleMetricExporter: i, InMemoryMetricExporter: a, AggregationTemporality: o } = e.sdkMetrics;
3016
3020
  if (t === "off") return {
3017
3021
  reader: void 0,
@@ -3034,8 +3038,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3034
3038
  }),
3035
3039
  inMemory: void 0
3036
3040
  };
3037
- }, qa = async (e = {}) => {
3038
- let t = e.mode ?? Ua(), n = e.metricsMode ?? Wa(), r = e.extraSpanProcessors ?? [], i = e.extraMetricReaders ?? [];
3041
+ }, Ja = async (e = {}) => {
3042
+ let t = e.mode ?? Wa(), n = e.metricsMode ?? Ga(), r = e.extraSpanProcessors ?? [], i = e.extraMetricReaders ?? [];
3039
3043
  if (t === "off" && e.traceSink === void 0 && n === "off" && r.length === 0 && i.length === 0) return {
3040
3044
  layer: u.empty,
3041
3045
  mode: t,
@@ -3044,13 +3048,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3044
3048
  metricsMode: n,
3045
3049
  inMemoryMetricExporter: void 0
3046
3050
  };
3047
- let a = await Ga(), { ConsoleSpanExporter: o, InMemorySpanExporter: s, SimpleSpanProcessor: c, BatchSpanProcessor: l } = a.sdkTrace, d = t === "off", f = e.serviceName ?? process.env.OTEL_SERVICE_NAME ?? "voltro-app", p, m;
3051
+ let a = await Ka(), { ConsoleSpanExporter: o, InMemorySpanExporter: s, SimpleSpanProcessor: c, BatchSpanProcessor: l } = a.sdkTrace, d = t === "off", f = e.serviceName ?? process.env.OTEL_SERVICE_NAME ?? "voltro-app", p, m;
3048
3052
  e.spanProcessor ? m = e.spanProcessor : d ? m = void 0 : t === "memory" ? (p = new s(), m = new c(p)) : m = t === "console" ? new c(new o()) : new l(new a.otlpTrace.OTLPTraceExporter());
3049
3053
  let h = [
3050
3054
  ...e.traceSink ? [e.traceSink] : [],
3051
3055
  ...m ? [m] : [],
3052
3056
  ...r
3053
- ], g = h.length === 1 ? h[0] : h, { reader: _, inMemory: v } = Ka(a, n, e.metricExportIntervalMillis ?? (process.env.OTEL_METRIC_EXPORT_INTERVAL ? Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) : 6e4)), y = [..._ ? [_] : [], ...i], b = y.length === 0 ? void 0 : y.length === 1 ? y[0] : y, x = {
3057
+ ], g = h.length === 1 ? h[0] : h, { reader: _, inMemory: v } = qa(a, n, e.metricExportIntervalMillis ?? (process.env.OTEL_METRIC_EXPORT_INTERVAL ? Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) : 6e4)), y = [..._ ? [_] : [], ...i], b = y.length === 0 ? void 0 : y.length === 1 ? y[0] : y, x = {
3054
3058
  serviceName: f,
3055
3059
  ...e.serviceVersion ? { serviceVersion: e.serviceVersion } : {},
3056
3060
  ...e.resourceAttributes ? { attributes: e.resourceAttributes } : {}
@@ -3068,18 +3072,18 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3068
3072
  metricsMode: n,
3069
3073
  inMemoryMetricExporter: v
3070
3074
  };
3071
- }, Ja = {
3072
- [Rt.INTERNAL]: "internal",
3073
- [Rt.SERVER]: "server",
3074
- [Rt.CLIENT]: "client",
3075
- [Rt.PRODUCER]: "producer",
3076
- [Rt.CONSUMER]: "consumer"
3077
- }, Ya = (e) => e[0] * 1e3 + e[1] / 1e6, Xa = 512, Za = 48, Qa = (e) => {
3075
+ }, Ya = {
3076
+ [Bt.INTERNAL]: "internal",
3077
+ [Bt.SERVER]: "server",
3078
+ [Bt.CLIENT]: "client",
3079
+ [Bt.PRODUCER]: "producer",
3080
+ [Bt.CONSUMER]: "consumer"
3081
+ }, Xa = (e) => e[0] * 1e3 + e[1] / 1e6, Za = 512, Qa = 48, $a = (e) => {
3078
3082
  let t = {}, n = 0;
3079
3083
  for (let r in e) {
3080
- if (n >= Za) break;
3084
+ if (n >= Qa) break;
3081
3085
  let i = e[r];
3082
- if (typeof i == "string") t[r] = i.length > Xa ? `${i.slice(0, Xa)}…` : i;
3086
+ if (typeof i == "string") t[r] = i.length > Za ? `${i.slice(0, Za)}…` : i;
3083
3087
  else if (typeof i == "number" || typeof i == "boolean" || i == null) t[r] = i;
3084
3088
  else {
3085
3089
  let e;
@@ -3088,49 +3092,49 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3088
3092
  } catch {
3089
3093
  e = String(i);
3090
3094
  }
3091
- t[r] = e.length > Xa ? `${e.slice(0, Xa)}…` : e;
3095
+ t[r] = e.length > Za ? `${e.slice(0, Za)}…` : e;
3092
3096
  }
3093
3097
  n++;
3094
3098
  }
3095
3099
  return t;
3096
- }, $a = {
3097
- [zt.UNSET]: "unset",
3098
- [zt.OK]: "ok",
3099
- [zt.ERROR]: "error"
3100
- }, eo = (e) => {
3100
+ }, eo = {
3101
+ [Vt.UNSET]: "unset",
3102
+ [Vt.OK]: "ok",
3103
+ [Vt.ERROR]: "error"
3104
+ }, to = (e) => {
3101
3105
  let t = e.spanContext(), n = e.events.length > 0 ? e.events.slice(0, 16).map((e) => ({
3102
3106
  name: e.name,
3103
- tsMs: Ya(e.time),
3104
- ...e.attributes ? { attributes: Qa(e.attributes) } : {}
3107
+ tsMs: Xa(e.time),
3108
+ ...e.attributes ? { attributes: $a(e.attributes) } : {}
3105
3109
  })) : void 0;
3106
3110
  return {
3107
3111
  traceId: t.traceId,
3108
3112
  spanId: t.spanId,
3109
3113
  parentSpanId: e.parentSpanContext?.spanId ?? null,
3110
3114
  name: e.name,
3111
- kind: Ja[e.kind] ?? "internal",
3112
- attributes: Qa(e.attributes),
3113
- startMs: Ya(e.startTime),
3114
- endMs: Ya(e.endTime),
3115
- durationMs: Ya(e.duration),
3116
- status: $a[e.status.code] ?? "unset",
3115
+ kind: Ya[e.kind] ?? "internal",
3116
+ attributes: $a(e.attributes),
3117
+ startMs: Xa(e.startTime),
3118
+ endMs: Xa(e.endTime),
3119
+ durationMs: Xa(e.duration),
3120
+ status: eo[e.status.code] ?? "unset",
3117
3121
  ...e.status.message ? { statusMessage: e.status.message } : {},
3118
3122
  ...n ? { events: n } : {}
3119
3123
  };
3120
- }, to = (e) => ({
3124
+ }, no = (e) => ({
3121
3125
  onStart: () => {},
3122
3126
  onEnd: (t) => {
3123
3127
  try {
3124
- e(eo(t));
3128
+ e(to(t));
3125
3129
  } catch {}
3126
3130
  },
3127
3131
  forceFlush: () => Promise.resolve(),
3128
3132
  shutdown: () => Promise.resolve()
3129
- }), no = { get: (e) => Promise.resolve(process.env[e]) }, ro = no, io = (e) => {
3130
- ro = e;
3131
- }, ao = () => {
3132
- ro = no;
3133
- }, oo = async (e) => await ro.get(e) ?? process.env[e], so = (e) => process.env[e], co = (e, t = 6e4, n = () => Date.now()) => {
3133
+ }), ro = { get: (e) => Promise.resolve(process.env[e]) }, io = ro, ao = (e) => {
3134
+ io = e;
3135
+ }, oo = () => {
3136
+ io = ro;
3137
+ }, so = async (e) => await io.get(e) ?? process.env[e], co = (e) => process.env[e], lo = (e, t = 6e4, n = () => Date.now()) => {
3134
3138
  let r = /* @__PURE__ */ new Map();
3135
3139
  return { get: async (i) => {
3136
3140
  let a = r.get(i);
@@ -3141,12 +3145,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3141
3145
  at: n()
3142
3146
  }), o;
3143
3147
  } };
3144
- }, lo = (e) => {
3148
+ }, uo = (e) => {
3145
3149
  let t = {
3146
3150
  accept: "application/json",
3147
3151
  ...e.headers ?? {}
3148
3152
  };
3149
- if (e.perKey) return co({ get: async (n) => {
3153
+ if (e.perKey) return lo({ get: async (n) => {
3150
3154
  let r = await fetch(`${e.url.replace(/\/$/, "")}/${encodeURIComponent(n)}`, { headers: t });
3151
3155
  if (!r.ok) return;
3152
3156
  let i = await r.json();
@@ -3157,34 +3161,34 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3157
3161
  let t = (await a())[e];
3158
3162
  return typeof t == "string" ? t : void 0;
3159
3163
  } };
3160
- }, uo = (e) => e === void 0 || e === "env" || typeof e == "object" && e.kind === "env" ? no : e.kind === "custom" ? e.backend : e.kind === "http" ? lo(e) : no, fo = "_voltro_idempotency", po = (e) => {
3164
+ }, fo = (e) => e === void 0 || e === "env" || typeof e == "object" && e.kind === "env" ? ro : e.kind === "custom" ? e.backend : e.kind === "http" ? uo(e) : ro, po = "_voltro_idempotency", mo = (e) => {
3161
3165
  if (e == null) return null;
3162
3166
  let t = typeof e == "string" ? JSON.parse(e) : e;
3163
3167
  return t && typeof t == "object" && "status" in t ? t : null;
3164
- }, mo = (e) => ({
3168
+ }, ho = (e) => ({
3165
3169
  scope: e.scope,
3166
3170
  key: e.key,
3167
3171
  status: e.status === "completed" ? "completed" : "in_flight",
3168
- response: po(e.response),
3169
- createdAt: vt(e.createdAt)
3170
- }), ho = async (e, t, n) => (await e.query({
3171
- table: fo,
3172
+ response: mo(e.response),
3173
+ createdAt: yt(e.createdAt)
3174
+ }), go = async (e, t, n) => (await e.query({
3175
+ table: po,
3172
3176
  predicate: C(O("scope", t), O("key", n)),
3173
3177
  order: [],
3174
3178
  take: 1,
3175
3179
  skip: void 0,
3176
3180
  projection: void 0
3177
- }))[0] ?? null, go = (e) => ({
3181
+ }))[0] ?? null, _o = (e) => ({
3178
3182
  get: async (t, n) => {
3179
- let r = await ho(e, t, n);
3180
- return r ? mo(r) : null;
3183
+ let r = await go(e, t, n);
3184
+ return r ? ho(r) : null;
3181
3185
  },
3182
3186
  claim: async (t, n, r, i) => {
3183
3187
  for (let a = 0; a < 2; a++) {
3184
3188
  let a = A({
3185
3189
  kind: "typeid",
3186
3190
  prefix: "idem"
3187
- }, fo), o = await e.insertIgnore(fo, {
3191
+ }, po), o = await e.insertIgnore(po, {
3188
3192
  id: a,
3189
3193
  scope: t,
3190
3194
  key: n,
@@ -3193,11 +3197,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3193
3197
  createdAt: new Date(r)
3194
3198
  }, { conflictColumns: ["scope", "key"] });
3195
3199
  if (o.id === a) return "claimed";
3196
- if (r - vt(o.createdAt) < i) return mo(o);
3197
- await e.delete(fo, o.id);
3200
+ if (r - yt(o.createdAt) < i) return ho(o);
3201
+ await e.delete(po, o.id);
3198
3202
  }
3199
- let a = await ho(e, t, n);
3200
- return a ? mo(a) : {
3203
+ let a = await go(e, t, n);
3204
+ return a ? ho(a) : {
3201
3205
  scope: t,
3202
3206
  key: n,
3203
3207
  status: "in_flight",
@@ -3206,36 +3210,36 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3206
3210
  };
3207
3211
  },
3208
3212
  complete: async (t, n, r, i) => {
3209
- let a = await ho(e, t, n);
3210
- a && await e.update(fo, a.id, {
3213
+ let a = await go(e, t, n);
3214
+ a && await e.update(po, a.id, {
3211
3215
  status: "completed",
3212
3216
  response: r
3213
3217
  });
3214
3218
  },
3215
3219
  release: async (t, n) => {
3216
- let r = await ho(e, t, n);
3217
- r && await e.delete(fo, r.id);
3220
+ let r = await go(e, t, n);
3221
+ r && await e.delete(po, r.id);
3218
3222
  }
3219
- }), J = "_voltro_kv", _o = (e) => {
3223
+ }), J = "_voltro_kv", vo = (e) => {
3220
3224
  if (e == null) return null;
3221
3225
  if (e instanceof Date) return e.getTime();
3222
3226
  if (typeof e == "number") return e;
3223
3227
  let t = Date.parse(String(e));
3224
3228
  return Number.isNaN(t) ? null : t;
3225
- }, vo = (e, t) => {
3226
- let n = _o(e.expiresAt);
3229
+ }, yo = (e, t) => {
3230
+ let n = vo(e.expiresAt);
3227
3231
  return n !== null && n <= t;
3228
- }, yo = (e) => e === null ? null : JSON.parse(e), bo = async (e, t) => (await e.query({
3232
+ }, bo = (e) => e === null ? null : JSON.parse(e), xo = async (e, t) => (await e.query({
3229
3233
  table: J,
3230
3234
  predicate: O("key", t),
3231
3235
  order: [],
3232
3236
  take: 1,
3233
3237
  skip: void 0,
3234
3238
  projection: void 0
3235
- }))[0] ?? null, xo = (e) => {
3239
+ }))[0] ?? null, So = (e) => {
3236
3240
  let t = (e, t, n) => o.tryPromise({
3237
3241
  try: n,
3238
- catch: (n) => new Vt({
3242
+ catch: (n) => new Ut({
3239
3243
  operation: e,
3240
3244
  key: t,
3241
3245
  cause: String(n)
@@ -3243,8 +3247,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3243
3247
  });
3244
3248
  return {
3245
3249
  get: (n) => t("get", n, async () => {
3246
- let t = await bo(e, n);
3247
- return t === null ? h.none() : vo(t, Date.now()) ? (await e.delete(J, t.id), h.none()) : h.some(yo(t.value));
3250
+ let t = await xo(e, n);
3251
+ return t === null ? h.none() : yo(t, Date.now()) ? (await e.delete(J, t.id), h.none()) : h.some(bo(t.value));
3248
3252
  }),
3249
3253
  set: (n, r, i) => t("set", n, async () => {
3250
3254
  let t = Date.now(), a = i?.ttlMs !== void 0 && i.ttlMs > 0 ? new Date(t + i.ttlMs) : null, o = A({
@@ -3267,14 +3271,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3267
3271
  });
3268
3272
  }),
3269
3273
  delete: (n) => t("delete", n, async () => {
3270
- let t = await bo(e, n);
3274
+ let t = await xo(e, n);
3271
3275
  if (t === null) return !1;
3272
- let r = !vo(t, Date.now());
3276
+ let r = !yo(t, Date.now());
3273
3277
  return await e.delete(J, t.id), r;
3274
3278
  }),
3275
3279
  has: (n) => t("has", n, async () => {
3276
- let t = await bo(e, n);
3277
- return t === null ? !1 : vo(t, Date.now()) ? (await e.delete(J, t.id), !1) : !0;
3280
+ let t = await xo(e, n);
3281
+ return t === null ? !1 : yo(t, Date.now()) ? (await e.delete(J, t.id), !1) : !0;
3278
3282
  }),
3279
3283
  list: (n) => t("list", "", async () => {
3280
3284
  let t = Date.now(), r = ye(de("expiresAt"), oe("expiresAt", new Date(t))), i = n === "" ? r : C(te("key", n), r), a = await e.query({
@@ -3285,7 +3289,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3285
3289
  skip: void 0,
3286
3290
  projection: void 0
3287
3291
  }), o = [];
3288
- for (let e of a) vo(e, t) || (n === "" || e.key.startsWith(n)) && o.push(e.key);
3292
+ for (let e of a) yo(e, t) || (n === "" || e.key.startsWith(n)) && o.push(e.key);
3289
3293
  return o;
3290
3294
  }),
3291
3295
  clear: () => t("clear", "", async () => {
@@ -3295,8 +3299,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3295
3299
  } });
3296
3300
  })
3297
3301
  };
3298
- }, So = async ({ store: e, env: t = process.env }) => {
3299
- let n = (t.KV_BACKEND ?? "database").toLowerCase(), r = n === "redis" ? "redis" : n === "memory" ? "memory" : "database", i = r === "redis" ? Gt(t.KV_KEY_PREFIX ? { keyPrefix: t.KV_KEY_PREFIX } : {}).pipe(u.provide(Ut)) : r === "memory" ? Wt() : u.succeed(Ht, Ht.of(xo(e))), a = d.make(Bt.Default.pipe(u.provide(i))), o = await a.runPromise(Bt);
3302
+ }, Co = async ({ store: e, env: t = process.env }) => {
3303
+ let n = (t.KV_BACKEND ?? "database").toLowerCase(), r = n === "redis" ? "redis" : n === "memory" ? "memory" : "database", i = r === "redis" ? qt(t.KV_KEY_PREFIX ? { keyPrefix: t.KV_KEY_PREFIX } : {}).pipe(u.provide(Gt)) : r === "memory" ? Kt() : u.succeed(Wt, Wt.of(So(e))), a = d.make(Ht.Default.pipe(u.provide(i))), o = await a.runPromise(Ht);
3300
3304
  return {
3301
3305
  kv: {
3302
3306
  get: (e) => a.runPromise(o.get(e)).then((e) => h.getOrUndefined(e)),
@@ -3311,7 +3315,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3311
3315
  backend: r,
3312
3316
  dispose: () => a.dispose()
3313
3317
  };
3314
- }, Co = {
3318
+ }, wo = {
3315
3319
  get: () => Promise.resolve(void 0),
3316
3320
  getOrElse: (e, t) => Promise.resolve(t()),
3317
3321
  set: () => Promise.resolve(),
@@ -3319,7 +3323,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3319
3323
  has: () => Promise.resolve(!1),
3320
3324
  list: () => Promise.resolve([]),
3321
3325
  clear: () => Promise.resolve()
3322
- }, wo = "_voltro_api_keys", To = (e) => Ie("sha256").update(e, "utf8").digest("hex"), Eo = (e = "voltro_") => `${e}${Le(30).toString("base64url")}`, Do = (e) => ({
3326
+ }, To = "_voltro_api_keys", Eo = (e) => Ie("sha256").update(e, "utf8").digest("hex"), Do = (e = "voltro_") => `${e}${Le(30).toString("base64url")}`, Oo = (e) => ({
3323
3327
  id: e.id,
3324
3328
  name: e.name,
3325
3329
  keyPrefix: e.keyPrefix,
@@ -3332,18 +3336,18 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3332
3336
  createdBy: e.createdBy ?? null,
3333
3337
  onBehalfOf: e.onBehalfOf ?? null,
3334
3338
  ...e.metadata == null ? {} : { metadata: e.metadata }
3335
- }), Oo = (e, t) => e.revokedAt === null && (e.expiresAt === null || e.expiresAt > t), ko = (e, t = {}) => {
3339
+ }), ko = (e, t) => e.revokedAt === null && (e.expiresAt === null || e.expiresAt > t), Ao = (e, t = {}) => {
3336
3340
  let n = t.prefix ?? "voltro_", r = t.usage, i = async (t) => {
3337
- let r = Eo(n), i = A({
3341
+ let r = Do(n), i = A({
3338
3342
  kind: "typeid",
3339
3343
  prefix: "apikey"
3340
- }, wo), a = t.scopes ?? [], o = t.expiresAt == null ? null : t.expiresAt instanceof Date ? t.expiresAt.getTime() : t.expiresAt;
3344
+ }, To), a = t.scopes ?? [], o = t.expiresAt == null ? null : t.expiresAt instanceof Date ? t.expiresAt.getTime() : t.expiresAt;
3341
3345
  return await e.insert({
3342
3346
  id: i,
3343
3347
  tenantId: t.tenantId ?? null,
3344
3348
  name: t.name,
3345
3349
  onBehalfOf: t.onBehalfOf ?? null,
3346
- hashedKey: To(r),
3350
+ hashedKey: Eo(r),
3347
3351
  keyPrefix: r.slice(0, n.length + 6),
3348
3352
  scopes: a,
3349
3353
  lastUsedAt: null,
@@ -3362,7 +3366,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3362
3366
  };
3363
3367
  }, a = async (t, n = Date.now()) => {
3364
3368
  let i = await e.findByHash(t);
3365
- return !i || !Oo(i, n) ? null : (r === void 0 ? await e.patch(i.id, { lastUsedAt: n }) : r.touch(i.id, n), {
3369
+ return !i || !ko(i, n) ? null : (r === void 0 ? await e.patch(i.id, { lastUsedAt: n }) : r.touch(i.id, n), {
3366
3370
  id: i.id,
3367
3371
  tenantId: i.tenantId ?? "",
3368
3372
  createdBy: i.createdBy ?? null,
@@ -3374,7 +3378,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3374
3378
  return {
3375
3379
  issue: i,
3376
3380
  resolveByHash: a,
3377
- verify: (e, t) => a(To(e), t),
3381
+ verify: (e, t) => a(Eo(e), t),
3378
3382
  revoke: async (t, n, r = Date.now()) => {
3379
3383
  let i = await e.findById(t);
3380
3384
  return !i || (i.tenantId ?? null) !== n ? !1 : (await e.patch(t, { revokedAt: r }), !0);
@@ -3390,9 +3394,9 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3390
3394
  ...a.metadata == null ? {} : { metadata: a.metadata }
3391
3395
  }));
3392
3396
  },
3393
- list: async (t) => (await e.listByTenant(t)).map(Do)
3397
+ list: async (t) => (await e.listByTenant(t)).map(Oo)
3394
3398
  };
3395
- }, Ao = () => {
3399
+ }, jo = () => {
3396
3400
  let e = /* @__PURE__ */ new Map();
3397
3401
  return {
3398
3402
  insert: async (t) => {
@@ -3409,21 +3413,21 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3409
3413
  });
3410
3414
  }
3411
3415
  };
3412
- }, jo = (e) => e == null ? null : e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : null, Mo = (e) => ({
3416
+ }, Mo = (e) => e == null ? null : e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : null, No = (e) => ({
3413
3417
  id: String(e.id),
3414
3418
  tenantId: e.tenantId ?? null,
3415
3419
  name: String(e.name),
3416
3420
  hashedKey: String(e.hashedKey),
3417
3421
  keyPrefix: String(e.keyPrefix),
3418
3422
  scopes: e.scopes ?? null,
3419
- lastUsedAt: jo(e.lastUsedAt),
3420
- expiresAt: jo(e.expiresAt),
3421
- revokedAt: jo(e.revokedAt),
3423
+ lastUsedAt: Mo(e.lastUsedAt),
3424
+ expiresAt: Mo(e.expiresAt),
3425
+ revokedAt: Mo(e.revokedAt),
3422
3426
  createdBy: e.createdBy ?? null,
3423
3427
  onBehalfOf: e.onBehalfOf ?? null,
3424
- createdAt: jo(e.createdAt) ?? 0,
3428
+ createdAt: Mo(e.createdAt) ?? 0,
3425
3429
  ...e.metadata == null ? {} : { metadata: e.metadata }
3426
- }), No = (e) => async (t, n) => {
3430
+ }), Po = (e) => async (t, n) => {
3427
3431
  let r = await e.findById(t);
3428
3432
  if (r === null) return;
3429
3433
  let i = r.requestCount ?? 0, a = r.lastUsedAt ?? 0;
@@ -3431,9 +3435,9 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3431
3435
  requestCount: i + n.requests,
3432
3436
  lastUsedAt: Math.max(a, n.lastUsedAt)
3433
3437
  });
3434
- }, Po = (e) => {
3438
+ }, Fo = (e) => {
3435
3439
  let t = async (t) => await e.query({
3436
- table: wo,
3440
+ table: To,
3437
3441
  predicate: t,
3438
3442
  order: [],
3439
3443
  take: void 0,
@@ -3451,33 +3455,33 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3451
3455
  };
3452
3456
  return {
3453
3457
  insert: async (t) => {
3454
- await e.insert(wo, n(t));
3458
+ await e.insert(To, n(t));
3455
3459
  },
3456
3460
  findByHash: async (e) => {
3457
3461
  let n = await t(O("hashedKey", e));
3458
- return n[0] ? Mo(n[0]) : null;
3462
+ return n[0] ? No(n[0]) : null;
3459
3463
  },
3460
3464
  findById: async (e) => {
3461
3465
  let n = await t(O("id", e));
3462
- return n[0] ? Mo(n[0]) : null;
3466
+ return n[0] ? No(n[0]) : null;
3463
3467
  },
3464
- listByTenant: async (e) => (await t(e === null ? void 0 : O("tenantId", e))).map(Mo).filter((t) => e === null || t.tenantId === e),
3468
+ listByTenant: async (e) => (await t(e === null ? void 0 : O("tenantId", e))).map(No).filter((t) => e === null || t.tenantId === e),
3465
3469
  patch: async (t, r) => {
3466
- await e.update(wo, t, n(r));
3470
+ await e.update(To, t, n(r));
3467
3471
  }
3468
3472
  };
3469
- }, Fo = (e, t = {}) => Kt({
3473
+ }, Io = (e, t = {}) => Jt({
3470
3474
  id: "voltro-apikey",
3471
3475
  ...t.prefix ? { prefix: t.prefix } : {},
3472
3476
  resolveKey: (t) => e.resolveByHash(t)
3473
- }), Io = (e) => {
3477
+ }), Lo = (e) => {
3474
3478
  let t = e.subject;
3475
3479
  return {
3476
3480
  id: t.id ?? null,
3477
3481
  tenantId: t.tenantId ?? null,
3478
3482
  scopes: t.scopes ?? []
3479
3483
  };
3480
- }, Lo = (e, t = "/v1/api-keys") => {
3484
+ }, Ro = (e, t = "/v1/api-keys") => {
3481
3485
  let n = y.Struct({
3482
3486
  id: y.String,
3483
3487
  name: y.String,
@@ -3496,11 +3500,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3496
3500
  })))
3497
3501
  });
3498
3502
  return [
3499
- jt({
3503
+ Nt({
3500
3504
  method: "POST",
3501
3505
  path: `${t}/issue`,
3502
3506
  summary: "Issue an API key (the token is returned ONCE).",
3503
- guards: [Nt([
3507
+ guards: [Ft([
3504
3508
  Ve,
3505
3509
  We,
3506
3510
  He,
@@ -3518,7 +3522,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3518
3522
  keyPrefix: y.String
3519
3523
  }),
3520
3524
  handler: async (t, n) => {
3521
- let r = t.body, i = Io(n), a = new Set(i.scopes), o = (e) => a.has(Ve) || a.has(e), s = r.onBehalfOf === void 0 ? i.id : r.onBehalfOf;
3525
+ let r = t.body, i = Lo(n), a = new Set(i.scopes), o = (e) => a.has(Ve) || a.has(e), s = r.onBehalfOf === void 0 ? i.id : r.onBehalfOf;
3522
3526
  if (s === null) {
3523
3527
  if (!o(He)) throw new $e({
3524
3528
  required: He,
@@ -3556,58 +3560,58 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3556
3560
  };
3557
3561
  }
3558
3562
  }),
3559
- jt({
3563
+ Nt({
3560
3564
  method: "GET",
3561
3565
  path: t,
3562
3566
  summary: "List the caller tenant's API keys (no secrets).",
3563
- guards: [Pt(Ve)],
3567
+ guards: [It(Ve)],
3564
3568
  input: y.Struct({}),
3565
3569
  output: y.Struct({ keys: y.Array(n) }),
3566
- handler: async (t, n) => ({ keys: [...await e.list(Io(n).tenantId)] })
3570
+ handler: async (t, n) => ({ keys: [...await e.list(Lo(n).tenantId)] })
3567
3571
  }),
3568
- jt({
3572
+ Nt({
3569
3573
  method: "POST",
3570
3574
  path: `${t}/revoke`,
3571
3575
  summary: "Revoke an API key by id.",
3572
- guards: [Pt(Ve)],
3576
+ guards: [It(Ve)],
3573
3577
  input: y.Struct({ body: y.Struct({ id: y.String }) }),
3574
3578
  output: y.Struct({ ok: y.Boolean }),
3575
- handler: async (t, n) => ({ ok: await e.revoke(t.body.id, Io(n).tenantId) })
3579
+ handler: async (t, n) => ({ ok: await e.revoke(t.body.id, Lo(n).tenantId) })
3576
3580
  })
3577
3581
  ];
3578
- }, Ro = {
3582
+ }, zo = {
3579
3583
  type: "anonymous",
3580
3584
  id: null,
3581
3585
  tenantId: null
3582
- }, zo = class extends n.Tag("@voltro/EffectStore")() {}, Bo = (e, t) => (n) => n instanceof Ii ? n : new Li({
3586
+ }, Bo = class extends n.Tag("@voltro/EffectStore")() {}, Vo = (e, t) => (n) => n instanceof Ii ? n : new Li({
3583
3587
  operation: e,
3584
3588
  table: t,
3585
3589
  cause: String(n)
3586
- }), Vo = (e, t, n) => o.tryPromise({
3590
+ }), Ho = (e, t, n) => o.tryPromise({
3587
3591
  try: n,
3588
- catch: Bo(e, t)
3589
- }), Ho = (e) => u.succeed(zo, {
3590
- query: ((t) => Vo("query", t.table, () => e.query(t))),
3591
- insert: (t, n) => Vo("insert", t, () => e.insert(t, n)),
3592
- update: (t, n, r) => Vo("update", t, () => e.update(t, n, r)),
3593
- delete: (t, n) => Vo("delete", t, () => e.delete(t, n)),
3594
- hardDelete: (t, n) => Vo("hardDelete", t, () => e.hardDelete(t, n))
3595
- }), Uo = (e) => Ot.make(e.name, {
3592
+ catch: Vo(e, t)
3593
+ }), Uo = (e) => u.succeed(Bo, {
3594
+ query: ((t) => Ho("query", t.table, () => e.query(t))),
3595
+ insert: (t, n) => Ho("insert", t, () => e.insert(t, n)),
3596
+ update: (t, n, r) => Ho("update", t, () => e.update(t, n, r)),
3597
+ delete: (t, n) => Ho("delete", t, () => e.delete(t, n)),
3598
+ hardDelete: (t, n) => Ho("hardDelete", t, () => e.hardDelete(t, n))
3599
+ }), Wo = (e) => At.make(e.name, {
3596
3600
  payload: e.payloadSchema,
3597
- success: rt,
3601
+ success: it,
3598
3602
  error: e.errorSchema
3599
- }), Wo = (e, t) => ({
3603
+ }), Go = (e, t) => ({
3600
3604
  id: t,
3601
3605
  workflowName: e,
3602
3606
  executionId: t,
3603
3607
  status: "running"
3604
- }), Go = Wo, Ko = (t) => {
3608
+ }), Ko = Go, qo = (t) => {
3605
3609
  let n = e.failureOption(t), r = n._tag === "Some" ? n.value : e.squash(t);
3606
3610
  return {
3607
3611
  tag: r && typeof r == "object" && "_tag" in r ? String(r._tag) : null,
3608
3612
  message: r?.message ?? String(r)
3609
3613
  };
3610
- }, qo = (e, t, n) => {
3614
+ }, Jo = (e, t, n) => {
3611
3615
  if (n === void 0) return {
3612
3616
  id: t,
3613
3617
  workflowName: e,
@@ -3633,7 +3637,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3633
3637
  workflowName: e,
3634
3638
  executionId: t,
3635
3639
  status: "failed",
3636
- error: Ko(r.cause)
3640
+ error: qo(r.cause)
3637
3641
  };
3638
3642
  }
3639
3643
  return {
@@ -3642,7 +3646,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3642
3646
  executionId: t,
3643
3647
  status: "running"
3644
3648
  };
3645
- }, Jo = (e) => new Promise((t) => setTimeout(t, e)), Yo = class extends Error {
3649
+ }, Yo = (e) => new Promise((t) => setTimeout(t, e)), Xo = class extends Error {
3646
3650
  workflowName;
3647
3651
  missingFields;
3648
3652
  detail;
@@ -3651,7 +3655,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3651
3655
  let r = t.length > 0 ? ` missing required field(s): ${t.join(", ")}.` : "";
3652
3656
  super(`Workflow "${e}" was started with an invalid payload.${r} ${n}`), this.workflowName = e, this.missingFields = t, this.detail = n, this.name = "WorkflowPayloadError";
3653
3657
  }
3654
- }, Xo = (e) => {
3658
+ }, Zo = (e) => {
3655
3659
  let t = e.ast;
3656
3660
  if (!Array.isArray(t.propertySignatures)) return {
3657
3661
  required: [],
@@ -3662,10 +3666,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3662
3666
  required: n.filter((e) => !e.isOptional).map((e) => String(e.name)),
3663
3667
  optional: n.filter((e) => e.isOptional).map((e) => String(e.name))
3664
3668
  };
3665
- }, Zo = (e) => {
3669
+ }, Qo = (e) => {
3666
3670
  let t = e.ast;
3667
3671
  return Array.isArray(t.propertySignatures) ? t.propertySignatures.filter((e) => !e.isOptional && typeof e.name == "string").map((e) => String(e.name)) : [];
3668
- }, Qo = (e) => {
3672
+ }, $o = (e) => {
3669
3673
  let t = new Map(e.workflows.map((e) => [e.definition.name, e.definition])), n = (e) => {
3670
3674
  let n = t.get(e);
3671
3675
  if (!n) {
@@ -3676,17 +3680,19 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3676
3680
  }, r = (e, t) => {
3677
3681
  let n = y.validateEither(e.payloadSchema)(t);
3678
3682
  if (n._tag === "Right") return;
3679
- let r = typeof t == "object" && t ? Object.keys(t) : [], i = Zo(e.payloadSchema).filter((e) => !r.includes(e));
3680
- throw new Yo(e.name, i, Lt.formatErrorSync(n.left));
3683
+ let r = typeof t == "object" && t ? Object.keys(t) : [], i = Qo(e.payloadSchema).filter((e) => !r.includes(e));
3684
+ throw new Xo(e.name, i, zt.formatErrorSync(n.left));
3681
3685
  }, i = (e, t) => {
3682
3686
  let i = n(e);
3683
3687
  return r(i, t), i;
3684
3688
  }, a = async (t, r) => {
3685
3689
  let i = n(t);
3686
- return qo(t, r, await e.runEffect(i.poll(r)));
3687
- }, o = async () => e.runEffect(qt()), s = async (t, n, r) => {
3690
+ return Jo(t, r, await e.runEffect(i.poll(r)));
3691
+ }, o = async () => e.runEffect(Yt()), s = async (t, n, r) => {
3688
3692
  let a = i(t, n), o;
3689
- return r?.callerContext !== void 0 && (o = await e.runEffect(a.executionId(n)), await e.rememberStartContext?.(t, o, r.callerContext)), r?.wait ? (await e.runEffect(a.execute(n)), Wo(t, o ?? await e.runEffect(a.executionId(n)))) : Wo(t, await e.runEffect(a.execute(n, { discard: !0 })));
3693
+ if (r?.callerContext !== void 0 && (o = await e.runEffect(a.executionId(n)), await e.rememberStartContext?.(t, o, r.callerContext)), r?.wait) return await e.runEffect(a.execute(n)), e.onEnqueue?.(), Go(t, o ?? await e.runEffect(a.executionId(n)));
3694
+ let s = await e.runEffect(a.execute(n, { discard: !0 }));
3695
+ return e.onEnqueue?.(), Go(t, s);
3690
3696
  };
3691
3697
  return {
3692
3698
  start: s,
@@ -3724,7 +3730,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3724
3730
  let e = await a(r, i);
3725
3731
  if (e.status === "succeeded" || e.status === "failed" || e.status === "cancelled") return e;
3726
3732
  if (o?.timeoutMs !== void 0 && Date.now() - s >= o.timeoutMs) throw Error(`Timed out waiting for workflow '${r}' run '${i}'`);
3727
- await Jo(c);
3733
+ await Yo(c);
3728
3734
  }
3729
3735
  }),
3730
3736
  cancel: async (t, r) => {
@@ -3760,24 +3766,28 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3760
3766
  retry: async (t, n) => {
3761
3767
  if (!e.retry) throw Error("Workflow retry is not configured in this runtime");
3762
3768
  return e.retry(t, n);
3769
+ },
3770
+ redrive: async (t) => {
3771
+ if (!e.redrive) throw Error("Workflow redrive is not configured in this runtime");
3772
+ return e.redrive(t);
3763
3773
  }
3764
3774
  };
3765
- }, $o = (e, t) => ({
3775
+ }, es = (e, t) => ({
3766
3776
  ...e,
3767
3777
  start: async (n, r, i) => {
3768
3778
  if (i?.wait) throw Error("ctx.workflows.start(..., { wait: true }) is not allowed inside a mutation transaction; start the workflow and wait after commit.");
3769
3779
  let a = await e.executionId(n, r);
3770
- return t(() => e.start(n, r)), Wo(n, a);
3780
+ return t(() => e.start(n, r)), Go(n, a);
3771
3781
  },
3772
3782
  child: async (n, r, i) => {
3773
3783
  if (i?.wait) throw Error("ctx.workflows.child(..., { wait: true }) is not allowed inside a mutation transaction; start the child workflow and wait after commit.");
3774
3784
  let a = await e.executionId(n, r);
3775
- return t(() => e.child(n, r, i)), Wo(n, a);
3785
+ return t(() => e.child(n, r, i)), Go(n, a);
3776
3786
  },
3777
3787
  run: async () => {
3778
3788
  throw Error("ctx.workflows.run(...) is not allowed inside a mutation transaction; use ctx.workflows.start(...) so the workflow starts after commit.");
3779
3789
  }
3780
- }), es = (e, t) => ({
3790
+ }), ts = (e, t) => ({
3781
3791
  ...e,
3782
3792
  start: (n, r, i) => e.start(n, r, {
3783
3793
  ...i,
@@ -3791,7 +3801,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3791
3801
  ...i,
3792
3802
  callerContext: t
3793
3803
  })
3794
- }), ts = (e) => {
3804
+ }), ns = (e) => {
3795
3805
  let t = () => {
3796
3806
  let t = e();
3797
3807
  if (!t) throw Error("Workflow runtime is not ready yet");
@@ -3810,28 +3820,29 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3810
3820
  signal: (e, n, r) => t().signal(e, n, r),
3811
3821
  update: (e, n, r, i) => t().update(e, n, r, i),
3812
3822
  listRuns: ((e) => t().listRuns(e)),
3813
- retry: (e, n) => t().retry(e, n)
3823
+ retry: (e, n) => t().retry(e, n),
3824
+ redrive: (e) => t().redrive(e)
3814
3825
  };
3815
- }, ns = (e, t) => {
3826
+ }, rs = (e, t) => {
3816
3827
  let n = {};
3817
- for (let r of e) n[r.definition.name] = (e) => (t ? o.promise(() => t.start(r.definition.name, e)) : r.definition.execute(e, { discard: !0 }).pipe(o.map((e) => Wo(r.definition.name, e)))).pipe(o.withSpan(`workflow.${r.definition.name}`, { attributes: { "framework.kind": "workflow" } }));
3828
+ for (let r of e) n[r.definition.name] = (e) => (t ? o.promise(() => t.start(r.definition.name, e)) : r.definition.execute(e, { discard: !0 }).pipe(o.map((e) => Go(r.definition.name, e)))).pipe(o.withSpan(`workflow.${r.definition.name}`, { attributes: { "framework.kind": "workflow" } }));
3818
3829
  return n;
3819
- }, rs = (e, t, n) => e.map((e) => e.definition.toLayer(((r, i) => {
3830
+ }, is = (e, t, n) => e.map((e) => e.definition.toLayer(((r, i) => {
3820
3831
  let a = t.resolveStartContext?.(e.definition.name, i);
3821
3832
  return (a === void 0 ? o.succeed(void 0) : o.promise(() => Promise.resolve(a))).pipe(o.flatMap((a) => {
3822
3833
  let s = {
3823
3834
  ...a,
3824
- subject: a?.subject ?? Ro,
3835
+ subject: a?.subject ?? zo,
3825
3836
  traceId: a?.traceId ?? "workflow-bootstrap"
3826
3837
  }, c = t.buildContext(s, {
3827
3838
  workflowName: e.definition.name,
3828
3839
  executionId: i,
3829
3840
  parentExecutionId: a?.parentExecutionId ?? null,
3830
3841
  parentClosePolicy: a?.parentClosePolicy ?? null
3831
- }), l = e.buildExecute(c), d = (n?.(e, l, s) ?? l)(r, i), f = u.succeed(z, s.subject), p = c?.store, m = p === void 0 ? d : o.provide(d, Ho(p));
3842
+ }), l = e.buildExecute(c), d = (n?.(e, l, s) ?? l)(r, i), f = u.succeed(et, s.subject), p = c?.store, m = p === void 0 ? d : o.provide(d, Uo(p));
3832
3843
  return o.provide(m, f);
3833
3844
  }));
3834
- }))), is = (e) => {
3845
+ }))), as = (e) => {
3835
3846
  if ("on" in e) {
3836
3847
  let { on: t, ...n } = e;
3837
3848
  return {
@@ -3844,10 +3855,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3844
3855
  _tag: "workflowEventTrigger",
3845
3856
  ...e
3846
3857
  };
3847
- }, as = is, os = (e) => typeof e == "object" && !!e && e._tag === "workflowEventTrigger", ss = () => {
3858
+ }, os = as, ss = (e) => typeof e == "object" && !!e && e._tag === "workflowEventTrigger", cs = () => {
3848
3859
  let e = globalThis.crypto;
3849
3860
  return typeof e?.randomUUID == "function" ? e.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
3850
- }, cs = (e) => `${e}_${ss()}`, ls = (e) => e.id ?? `${e.event}->${e.workflow}`, us = F("_voltro_workflow_events", {
3861
+ }, ls = (e) => `${e}_${cs()}`, us = (e) => e.id ?? `${e.event}->${e.workflow}`, ds = F("_voltro_workflow_events", {
3851
3862
  id: M({ prefix: "wfe" }),
3852
3863
  name: I(),
3853
3864
  payload: P(),
@@ -3855,7 +3866,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3855
3866
  subject: P().nullable(),
3856
3867
  traceId: I().nullable(),
3857
3868
  occurredAt: L().default("now")
3858
- }).index(["name"]).index(["source"]).index(["occurredAt"]), ds = F("_voltro_workflow_event_deliveries", {
3869
+ }).index(["name"]).index(["source"]).index(["occurredAt"]), fs = F("_voltro_workflow_event_deliveries", {
3859
3870
  id: M({ prefix: "wfed" }),
3860
3871
  eventId: I(),
3861
3872
  eventName: I(),
@@ -3873,8 +3884,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3873
3884
  errorMessage: I().nullable(),
3874
3885
  createdAt: L().default("now"),
3875
3886
  completedAt: L().nullable()
3876
- }).index(["eventId"]).index(["eventName"]).index(["triggerId"]).index(["workflowName"]).index(["status"]), fs = (e) => {
3877
- let t = e.makeId ?? cs, n = /* @__PURE__ */ new Map();
3887
+ }).index(["eventId"]).index(["eventName"]).index(["triggerId"]).index(["workflowName"]).index(["status"]), ps = (e) => {
3888
+ let t = e.makeId ?? ls, n = /* @__PURE__ */ new Map();
3878
3889
  for (let t of e.triggers) {
3879
3890
  let e = n.get(t.event);
3880
3891
  e ? e.push(t) : n.set(t.event, [t]);
@@ -3915,7 +3926,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
3915
3926
  });
3916
3927
  let f = o(n), p = [];
3917
3928
  for (let o of f) {
3918
- let s = ls(o), l = o.workflow, u;
3929
+ let s = us(o), l = o.workflow, u;
3919
3930
  try {
3920
3931
  let f = o.idempotencyKey?.(d) ?? `${c}:${s}`;
3921
3932
  if (o.filter && !await o.filter(d)) {
@@ -4018,7 +4029,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4018
4029
  triggered: p
4019
4030
  };
4020
4031
  } };
4021
- }, ps = B({ scope: "voltro:events" }), ms = 64, hs = 5 * 6e4, gs = 1e4, _s = class {
4032
+ }, ms = z({ scope: "voltro:events" }), hs = 64, gs = 5 * 6e4, _s = 1e4, vs = class {
4022
4033
  routes = /* @__PURE__ */ new Map();
4023
4034
  origin;
4024
4035
  ringSize;
@@ -4030,7 +4041,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4030
4041
  interestListeners = /* @__PURE__ */ new Set();
4031
4042
  now;
4032
4043
  constructor(e) {
4033
- this.origin = e.origin, this.ringSize = e.ringSize ?? ms, this.ringTtlMs = e.ringTtlMs ?? hs, this.maxRoutes = e.maxRoutes ?? gs, this.publishRemote = e.publishRemote, this.deliveryOf = e.deliveryOf, this.now = e.now ?? Date.now;
4044
+ this.origin = e.origin, this.ringSize = e.ringSize ?? hs, this.ringTtlMs = e.ringTtlMs ?? gs, this.maxRoutes = e.maxRoutes ?? _s, this.publishRemote = e.publishRemote, this.deliveryOf = e.deliveryOf, this.now = e.now ?? Date.now;
4034
4045
  }
4035
4046
  get instanceOrigin() {
4036
4047
  return this.origin;
@@ -4050,7 +4061,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4050
4061
  for (let n of this.interestListeners) try {
4051
4062
  n(e, t);
4052
4063
  } catch (n) {
4053
- ps.warn("event interest listener threw", {
4064
+ ms.warn("event interest listener threw", {
4054
4065
  event: e,
4055
4066
  active: t,
4056
4067
  cause: n
@@ -4068,7 +4079,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4068
4079
  if (t !== void 0) return t.lastTouched = this.now(), t;
4069
4080
  this.evictIfOverCapacity();
4070
4081
  let n = {
4071
- latest: this.deliveryOf?.(pt(e).event) === "latest",
4082
+ latest: this.deliveryOf?.(mt(e).event) === "latest",
4072
4083
  listeners: /* @__PURE__ */ new Set(),
4073
4084
  watermark: /* @__PURE__ */ new Map(),
4074
4085
  localNext: 1,
@@ -4085,7 +4096,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4085
4096
  this.routes.delete(r), n += 1;
4086
4097
  }
4087
4098
  if (n === 0) {
4088
- ps.warn("event ring capacity reached with all routes live — replay buffers cleared", {
4099
+ ms.warn("event ring capacity reached with all routes live — replay buffers cleared", {
4089
4100
  routes: this.routes.size,
4090
4101
  maxRoutes: this.maxRoutes
4091
4102
  });
@@ -4099,7 +4110,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4099
4110
  i > 0 && e.ring.splice(0, i);
4100
4111
  }
4101
4112
  publish(e) {
4102
- let t = ct(e.tenantId, e.event, e.key), n = this.state(t), r = {
4113
+ let t = lt(e.tenantId, e.event, e.key), n = this.state(t), r = {
4103
4114
  route: t,
4104
4115
  event: e.event,
4105
4116
  origin: this.origin,
@@ -4110,7 +4121,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4110
4121
  if (n.localNext += 1, this.accept(n, r), or(e.event), this.publishRemote !== void 0) try {
4111
4122
  this.publishRemote(r);
4112
4123
  } catch (t) {
4113
- ps.warn("event broadcast publish failed — local delivery unaffected", {
4124
+ ms.warn("event broadcast publish failed — local delivery unaffected", {
4114
4125
  event: e.event,
4115
4126
  cause: t
4116
4127
  });
@@ -4139,14 +4150,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4139
4150
  for (let n of e.listeners) try {
4140
4151
  n(i);
4141
4152
  } catch (e) {
4142
- ps.warn("event listener threw — other subscribers unaffected", {
4153
+ ms.warn("event listener threw — other subscribers unaffected", {
4143
4154
  event: t.event,
4144
4155
  cause: e
4145
4156
  });
4146
4157
  }
4147
4158
  }
4148
4159
  subscribe(e) {
4149
- let t = ct(e.tenantId, e.event, e.key), n = this.state(t);
4160
+ let t = lt(e.tenantId, e.event, e.key), n = this.state(t);
4150
4161
  e.onAttach?.(new Map(n.watermark)), n.listeners.add(e.listener), lr(e.event, 1), this.shiftInterest(e.event, 1);
4151
4162
  let r = e.options?.resume;
4152
4163
  if (r !== void 0) this.replayForResume(n, r, e.listener);
@@ -4203,7 +4214,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4203
4214
  snapshot() {
4204
4215
  return [...this.routes.entries()].map(([e, t]) => ({
4205
4216
  route: e,
4206
- event: t.ring[t.ring.length - 1]?.envelope.event ?? pt(e).event,
4217
+ event: t.ring[t.ring.length - 1]?.envelope.event ?? mt(e).event,
4207
4218
  subscribers: t.listeners.size,
4208
4219
  buffered: t.ring.length,
4209
4220
  lastEmittedAt: t.ring[t.ring.length - 1]?.envelope.emittedAt
@@ -4212,13 +4223,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4212
4223
  clear() {
4213
4224
  this.routes.clear();
4214
4225
  }
4215
- }, vs = (e) => e instanceof Error ? e.message : String(e), ys = (e, t, n, r) => o.gen(function* () {
4226
+ }, ys = (e) => e instanceof Error ? e.message : String(e), bs = (e, t, n, r) => o.gen(function* () {
4216
4227
  let i = y.encode(t.key), a = y.encode(t.payload), s = yield* i(n).pipe(o.mapError((e) => new Ye({
4217
4228
  event: t.name,
4218
- message: vs(e)
4229
+ message: ys(e)
4219
4230
  }))), c = yield* a(r).pipe(o.mapError((e) => new Xe({
4220
4231
  event: t.name,
4221
- message: vs(e)
4232
+ message: ys(e)
4222
4233
  }))), l = Buffer.byteLength(JSON.stringify({
4223
4234
  event: t.name,
4224
4235
  key: s,
@@ -4247,10 +4258,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4247
4258
  n: -1,
4248
4259
  deferred: !0
4249
4260
  });
4250
- }), bs = (e) => {
4261
+ }), xs = (e) => {
4251
4262
  let t;
4252
4263
  return Object.assign(e, { then: (n, r) => (t ??= o.runPromise(e), t.then(n, r)) });
4253
- }, xs = (e) => ({ publish: (t, n, r) => bs(ys(e, t, n, r)) }), Ss = 64, Cs = 1, ws = (e) => e.kind === "gap" ? {
4264
+ }, Ss = (e) => ({ publish: (t, n, r) => xs(bs(e, t, n, r)) }), Cs = 64, ws = 1, Ts = (e) => e.kind === "gap" ? {
4254
4265
  _tag: "gap",
4255
4266
  missed: e.missed,
4256
4267
  reason: e.reason
@@ -4260,16 +4271,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4260
4271
  n: e.envelope.n,
4261
4272
  emittedAt: e.envelope.emittedAt,
4262
4273
  payload: e.envelope.payload
4263
- }, Ts = (e) => {
4274
+ }, Es = (e) => {
4264
4275
  let t = new Map(e ?? []);
4265
4276
  return (e, n = 0) => {
4266
4277
  let r = t.get(e.origin) ?? 0;
4267
4278
  return t.set(e.origin, Math.max(r, e.n)), r === 0 && n === 0 ? 0 : Math.max(0, e.n - r - 1);
4268
4279
  };
4269
- }, Es = (e) => b.unwrapScoped(o.gen(function* () {
4270
- let t = yield* z, n = yield* Ge, r = t.tenantId ?? null;
4280
+ }, Ds = (e) => b.unwrapScoped(o.gen(function* () {
4281
+ let t = yield* et, n = yield* Ge, r = t.tenantId ?? null;
4271
4282
  if (e.guards !== void 0 && e.guards.length > 0) {
4272
- let n = yield* at(t, e.guards, e.key);
4283
+ let n = yield* ot(t, e.guards, e.key);
4273
4284
  if (n) return yield* o.fail(n);
4274
4285
  }
4275
4286
  let i = e.bus.deliveryFor(e.event) === "latest", a = yield* g.sliding(e.queueSize ?? (i ? 1 : 64)), s = /* @__PURE__ */ new Map(), c = e.bus.subscribe({
@@ -4294,22 +4305,26 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4294
4305
  e();
4295
4306
  }));
4296
4307
  }
4297
- let l = i ? () => 0 : Ts(s), u = b.fromQueue(a, { shutdown: !0 }).pipe(b.flatMap((t) => {
4298
- if (t.kind === "gap") return b.make(ws(t));
4299
- let n = l(t.envelope, t.prior);
4300
- sr(e.event);
4301
- let r = ws(t);
4302
- if (n === 0) return b.make(r);
4303
- cr(e.event, "buffer", n);
4304
- let i = {
4305
- _tag: "gap",
4306
- missed: n,
4307
- reason: "buffer"
4308
- };
4309
- return b.fromIterable([i, r]);
4310
- }));
4311
- return b.concat(b.fromIterable([{ _tag: "attached" }]), u);
4312
- })), Ds = B({ scope: "voltro:members" }), Os = 5e3, ks = class {
4308
+ let l = i ? () => 0 : Es(s), u = e.guards, d = u === void 0 || u.length === 0 ? void 0 : () => ot(t, u, e.key), f = b.fromQueue(a, { shutdown: !0 }).pipe(b.flatMap((e) => d === void 0 ? p(e) : b.unwrap(d().pipe(o.map((t) => t ? b.fail(t) : p(e))))));
4309
+ function p(t) {
4310
+ return b.suspend(() => {
4311
+ if (t.kind === "gap") return b.make(Ts(t));
4312
+ let n = l(t.envelope, t.prior);
4313
+ sr(e.event);
4314
+ let r = Ts(t);
4315
+ if (n === 0) return b.make(r);
4316
+ cr(e.event, "buffer", n);
4317
+ let i = {
4318
+ _tag: "gap",
4319
+ missed: n,
4320
+ reason: "buffer"
4321
+ };
4322
+ return b.fromIterable([i, r]);
4323
+ });
4324
+ }
4325
+ let m = { _tag: "attached" };
4326
+ return ra(b.concat(b.fromIterable([m]), f), n.credentialExpiresAt, b.fromIterable([m]));
4327
+ })), Os = z({ scope: "voltro:members" }), ks = 5e3, As = class {
4313
4328
  members = /* @__PURE__ */ new Map();
4314
4329
  listeners = /* @__PURE__ */ new Set();
4315
4330
  instanceId;
@@ -4321,7 +4336,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4321
4336
  now;
4322
4337
  timer;
4323
4338
  constructor(e) {
4324
- this.instanceId = e.instanceId, this.now = e.now ?? Date.now, this.startedAt = e.startedAt ?? this.now(), this.meta = e.meta, this.heartbeatMs = e.heartbeatMs ?? Os, this.downAfterMs = e.downAfterMs ?? this.heartbeatMs * 3, this.announce = e.announce, this.members.set(this.instanceId, {
4339
+ this.instanceId = e.instanceId, this.now = e.now ?? Date.now, this.startedAt = e.startedAt ?? this.now(), this.meta = e.meta, this.heartbeatMs = e.heartbeatMs ?? ks, this.downAfterMs = e.downAfterMs ?? this.heartbeatMs * 3, this.announce = e.announce, this.members.set(this.instanceId, {
4325
4340
  startedAt: this.startedAt,
4326
4341
  meta: this.meta,
4327
4342
  lastHeardAt: this.now()
@@ -4347,7 +4362,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4347
4362
  ...this.meta === void 0 ? {} : { meta: this.meta }
4348
4363
  });
4349
4364
  } catch (e) {
4350
- Ds.warn("membership: announce failed", { cause: e });
4365
+ Os.warn("membership: announce failed", { cause: e });
4351
4366
  }
4352
4367
  }
4353
4368
  receive(e) {
@@ -4401,16 +4416,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4401
4416
  for (let t of this.listeners) try {
4402
4417
  t(e);
4403
4418
  } catch (t) {
4404
- Ds.warn("membership: listener threw", {
4419
+ Os.warn("membership: listener threw", {
4405
4420
  event: e.kind,
4406
4421
  cause: t
4407
4422
  });
4408
4423
  }
4409
4424
  }
4410
- }, As = B({ scope: "voltro:outbox" }), Y = "_voltro_outbox", js = {
4425
+ }, js = z({ scope: "voltro:outbox" }), Y = "_voltro_outbox", Ms = {
4411
4426
  kind: "typeid",
4412
4427
  prefix: "obx"
4413
- }, Ms = F(Y, {
4428
+ }, Ns = F(Y, {
4414
4429
  id: M({ prefix: "obx" }),
4415
4430
  effect: I(),
4416
4431
  payload: P(),
@@ -4428,10 +4443,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4428
4443
  resendRequestedBy: I().nullable(),
4429
4444
  resendReason: I().nullable(),
4430
4445
  resendCount: N()
4431
- }), Ns = "_voltro_outbox_attempts", Ps = {
4446
+ }), Ps = "_voltro_outbox_attempts", Fs = {
4432
4447
  kind: "typeid",
4433
4448
  prefix: "obxa"
4434
- }, Fs = F(Ns, {
4449
+ }, Is = F(Ps, {
4435
4450
  id: M({ prefix: "obxa" }),
4436
4451
  outboxId: I(),
4437
4452
  effect: I(),
@@ -4452,11 +4467,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4452
4467
  subjectId: I().nullable(),
4453
4468
  tenantId: I().nullable(),
4454
4469
  traceId: I().nullable()
4455
- }).index(["outboxId", "attempt"]).index(["startedAt"]).index(["outcome"]), Is = (e) => {
4470
+ }).index(["outboxId", "attempt"]).index(["startedAt"]).index(["outcome"]), Ls = (e) => {
4456
4471
  if (e.effect.trim() === "") throw Error("defineOutboxHandler: `effect` must be a non-empty name");
4457
4472
  if (e.maxAttempts !== void 0 && e.maxAttempts < 1) throw Error(`defineOutboxHandler("${e.effect}"): maxAttempts must be >= 1`);
4458
4473
  return e;
4459
- }, Ls = 8, Rs = (e) => ({
4474
+ }, Rs = 8, zs = (e) => ({
4460
4475
  enqueue: async (t, n, r) => {
4461
4476
  let i = (e.now ?? (() => /* @__PURE__ */ new Date()))(), a = r?.idempotencyKey;
4462
4477
  if (a !== void 0) {
@@ -4471,12 +4486,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4471
4486
  if (t !== void 0) return t.id;
4472
4487
  }
4473
4488
  let o = {
4474
- id: A(js, Y),
4489
+ id: A(Ms, Y),
4475
4490
  effect: t,
4476
4491
  payload: n,
4477
4492
  status: "pending",
4478
4493
  attempts: 0,
4479
- maxAttempts: r?.maxAttempts ?? Ls,
4494
+ maxAttempts: r?.maxAttempts ?? Rs,
4480
4495
  nextAttemptAt: new Date(i.getTime() + (r?.delayMs ?? 0)),
4481
4496
  idempotencyKey: a ?? null,
4482
4497
  lastError: null,
@@ -4523,7 +4538,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4523
4538
  });
4524
4539
  } else e.nudge?.();
4525
4540
  }
4526
- }), zs = (e) => Math.min(1e3 * 2 ** Math.max(0, e - 1), 5 * 6e4), Bs = 50, Vs = (e, t) => e.length <= t ? e : `${e.slice(0, t)}… [clipped]`, Hs = (e) => {
4541
+ }), Bs = (e) => Math.min(1e3 * 2 ** Math.max(0, e - 1), 5 * 6e4), Vs = 50, Hs = (e, t) => e.length <= t ? e : `${e.slice(0, t)}… [clipped]`, Us = (e) => {
4527
4542
  if (e == null) return null;
4528
4543
  let t = typeof e == "object" && !Array.isArray(e) ? e : { value: e }, n;
4529
4544
  try {
@@ -4533,13 +4548,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4533
4548
  }
4534
4549
  return n.length > 8192 ? {
4535
4550
  truncated: !0,
4536
- preview: Vs(n, 8192)
4551
+ preview: Hs(n, 8192)
4537
4552
  } : t;
4538
- }, Us = async (e, t, n) => {
4553
+ }, Ws = async (e, t, n) => {
4539
4554
  let r = t.outboxRow, i = r.id, a = r.resendRequestedBy ?? null;
4540
4555
  try {
4541
- await e.insert(Ns, {
4542
- id: A(Ps, Ns),
4556
+ await e.insert(Ps, {
4557
+ id: A(Fs, Ps),
4543
4558
  outboxId: i,
4544
4559
  effect: r.effect,
4545
4560
  attempt: t.attempt,
@@ -4550,14 +4565,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4550
4565
  startedAt: t.startedAt,
4551
4566
  finishedAt: t.finishedAt,
4552
4567
  durationMs: Math.max(0, t.finishedAt.getTime() - t.startedAt.getTime()),
4553
- error: t.error === null ? null : Vs(t.error, 4e3),
4554
- response: Hs(t.response),
4568
+ error: t.error === null ? null : Hs(t.error, 4e3),
4569
+ response: Us(t.response),
4555
4570
  subjectId: r.subjectId ?? null,
4556
4571
  tenantId: r.tenantId ?? null,
4557
4572
  traceId: r.traceId ?? null
4558
4573
  });
4559
4574
  } catch (e) {
4560
- As.warn("outbox: could not record delivery attempt (delivery itself is unaffected)", {
4575
+ js.warn("outbox: could not record delivery attempt (delivery itself is unaffected)", {
4561
4576
  outboxId: i,
4562
4577
  attempt: t.attempt
4563
4578
  }, e);
@@ -4565,7 +4580,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4565
4580
  }
4566
4581
  if (!(t.attempt <= n)) try {
4567
4582
  let t = await e.query({
4568
- table: Ns,
4583
+ table: Ps,
4569
4584
  predicate: O("outboxId", i),
4570
4585
  order: [{
4571
4586
  column: "attempt",
@@ -4575,11 +4590,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4575
4590
  skip: void 0,
4576
4591
  projection: ["id"]
4577
4592
  });
4578
- for (let r of t.slice(0, Math.max(0, t.length - n))) await e.delete(Ns, r.id);
4593
+ for (let r of t.slice(0, Math.max(0, t.length - n))) await e.delete(Ps, r.id);
4579
4594
  } catch (e) {
4580
- As.warn("outbox: attempt-log trim failed; the log may exceed its cap", { outboxId: i }, e);
4595
+ js.warn("outbox: attempt-log trim failed; the log may exceed its cap", { outboxId: i }, e);
4581
4596
  }
4582
- }, Ws = async (e) => {
4597
+ }, Gs = async (e) => {
4583
4598
  let t = (e.now ?? (() => /* @__PURE__ */ new Date()))(), n = await e.store.query({
4584
4599
  table: Y,
4585
4600
  predicate: C(O("status", "pending"), he("nextAttemptAt", t)),
@@ -4597,7 +4612,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4597
4612
  o++;
4598
4613
  continue;
4599
4614
  }
4600
- let u = s.attempts + 1, d = s.maxAttempts ?? Ls, f = /* @__PURE__ */ new Date(), p = e.attemptLogCap ?? 50;
4615
+ let u = s.attempts + 1, d = s.maxAttempts ?? Rs, f = /* @__PURE__ */ new Date(), p = e.attemptLogCap ?? 50;
4601
4616
  try {
4602
4617
  let t = await l.handler({
4603
4618
  payload: s.payload ?? {},
@@ -4606,7 +4621,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4606
4621
  tenantId: s.tenantId ?? null,
4607
4622
  traceId: s.traceId ?? null
4608
4623
  });
4609
- await Us(e.store, {
4624
+ await Ws(e.store, {
4610
4625
  outboxRow: s,
4611
4626
  attempt: u,
4612
4627
  outcome: "delivered",
@@ -4624,7 +4639,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4624
4639
  }), r++;
4625
4640
  } catch (r) {
4626
4641
  let o = r instanceof Error ? r.message : String(r), l = u >= d;
4627
- await Us(e.store, {
4642
+ await Ws(e.store, {
4628
4643
  outboxRow: s,
4629
4644
  attempt: u,
4630
4645
  outcome: l ? "dead" : "failed",
@@ -4636,20 +4651,20 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4636
4651
  status: l ? "dead" : "pending",
4637
4652
  attempts: u,
4638
4653
  lastError: o,
4639
- nextAttemptAt: new Date(t.getTime() + zs(u)),
4654
+ nextAttemptAt: new Date(t.getTime() + Bs(u)),
4640
4655
  resendRequestedBy: null,
4641
4656
  resendReason: null
4642
- }), l ? (a++, As.error("outbox effect dead-lettered after exhausting attempts", {
4657
+ }), l ? (a++, js.error("outbox effect dead-lettered after exhausting attempts", {
4643
4658
  id: n,
4644
4659
  effect: c,
4645
4660
  attempts: u,
4646
4661
  maxAttempts: d
4647
- }, r)) : (i++, As.warn("outbox delivery failed; will retry", {
4662
+ }, r)) : (i++, js.warn("outbox delivery failed; will retry", {
4648
4663
  id: n,
4649
4664
  effect: c,
4650
4665
  attempt: u,
4651
4666
  maxAttempts: d,
4652
- retryInMs: zs(u)
4667
+ retryInMs: Bs(u)
4653
4668
  }));
4654
4669
  }
4655
4670
  }
@@ -4659,10 +4674,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4659
4674
  dead: a,
4660
4675
  skipped: o
4661
4676
  };
4662
- }, Gs = B({ scope: "voltro:connections" }), X = "_voltro_connections", Ks = {
4677
+ }, Ks = z({ scope: "voltro:connections" }), X = "_voltro_connections", qs = {
4663
4678
  kind: "typeid",
4664
4679
  prefix: "conn"
4665
- }, qs = F(X, {
4680
+ }, Js = F(X, {
4666
4681
  id: M({ prefix: "conn" }),
4667
4682
  connectionId: I(),
4668
4683
  subjectId: I(),
@@ -4685,10 +4700,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4685
4700
  metadata: P().nullable(),
4686
4701
  connectedAt: L(),
4687
4702
  updatedAt: L()
4688
- }).unique("byConnectionSubject", ["connectionId", "subjectId"]).index(["subjectId"]), Js = "_voltro_connection_grants", Ys = {
4703
+ }).unique("byConnectionSubject", ["connectionId", "subjectId"]).index(["subjectId"]), Ys = "_voltro_connection_grants", Xs = {
4689
4704
  kind: "typeid",
4690
4705
  prefix: "cgrant"
4691
- }, Xs = F(Js, {
4706
+ }, Zs = F(Ys, {
4692
4707
  id: M({ prefix: "cgrant" }),
4693
4708
  state: I().unique(),
4694
4709
  connectionId: I(),
@@ -4698,8 +4713,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4698
4713
  redirectTo: I(),
4699
4714
  createdAt: L(),
4700
4715
  expiresAt: L()
4701
- }).index(["expiresAt"]), Zs = /^[a-z][a-z0-9-]*$/, Qs = (e) => {
4702
- if (!Zs.test(e.id)) throw Error(`defineConnection: id "${e.id}" must be lowercase kebab-case (it becomes a URL path segment).`);
4716
+ }).index(["expiresAt"]), Qs = /^[a-z][a-z0-9-]*$/, $s = (e) => {
4717
+ if (!Qs.test(e.id)) throw Error(`defineConnection: id "${e.id}" must be lowercase kebab-case (it becomes a URL path segment).`);
4703
4718
  if (e.kind === "oauth2") {
4704
4719
  for (let t of [
4705
4720
  "authorizeUrl",
@@ -4709,9 +4724,9 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4709
4724
  ]) if (typeof e[t] != "string" || e[t].length === 0) throw Error(`defineConnection("${e.id}"): \`${t}\` is required for kind 'oauth2'.`);
4710
4725
  }
4711
4726
  return e;
4712
- }, $s = (e) => e.label ?? e.id, ec = (e) => {
4727
+ }, ec = (e) => e.label ?? e.id, tc = (e) => {
4713
4728
  if (e.length !== 0 && q() === void 0) throw Error(`connections: ${e.length} connection(s) declared (${e.map((e) => e.id).join(", ")}) but no field cipher is registered. Connection tokens are stored encrypted and there is no plaintext fallback. Enable \`@voltro/plugin-governance\` with \`governancePlugin({ fieldEncryption: { key: env.FIELD_ENCRYPTION_KEY } })\` (or call setFieldCipher at boot).`);
4714
- }, tc = (e) => {
4729
+ }, nc = (e) => {
4715
4730
  let t = /* @__PURE__ */ new Map();
4716
4731
  for (let n of e) {
4717
4732
  if (t.has(n.id)) throw Error(`connections: duplicate connection id "${n.id}" — each *.connection.ts must declare a distinct id.`);
@@ -4721,14 +4736,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4721
4736
  get: (e) => t.get(e),
4722
4737
  list: () => [...t.values()]
4723
4738
  };
4724
- }, nc = (e) => {
4739
+ }, rc = (e) => {
4725
4740
  if (e == null) return null;
4726
4741
  let t = e instanceof Date ? e : new Date(String(e));
4727
4742
  return Number.isNaN(t.getTime()) ? null : t;
4728
- }, rc = (e) => nc(e)?.toISOString() ?? null, ic = (e) => String(e ?? "").split(" ").filter((e) => e.length > 0), ac = (e, t) => t === void 0 ? {
4743
+ }, ic = (e) => rc(e)?.toISOString() ?? null, ac = (e) => String(e ?? "").split(" ").filter((e) => e.length > 0), oc = (e, t) => t === void 0 ? {
4729
4744
  connectionId: e.id,
4730
4745
  kind: e.kind,
4731
- label: $s(e),
4746
+ label: ec(e),
4732
4747
  status: "disconnected",
4733
4748
  accountId: null,
4734
4749
  accountLabel: null,
@@ -4739,24 +4754,24 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4739
4754
  } : {
4740
4755
  connectionId: e.id,
4741
4756
  kind: e.kind,
4742
- label: $s(e),
4757
+ label: ec(e),
4743
4758
  status: String(t.status ?? "connected"),
4744
4759
  accountId: t.accountId ?? null,
4745
4760
  accountLabel: t.accountLabel ?? null,
4746
- scopes: ic(t.scopes),
4747
- expiresAt: rc(t.expiresAt),
4761
+ scopes: ac(t.scopes),
4762
+ expiresAt: ic(t.expiresAt),
4748
4763
  lastError: t.lastError ?? null,
4749
- connectedAt: rc(t.connectedAt)
4750
- }, oc = async (e, t, n) => (await e.query({
4764
+ connectedAt: ic(t.connectedAt)
4765
+ }, sc = async (e, t, n) => (await e.query({
4751
4766
  table: X,
4752
4767
  predicate: C(O("connectionId", t), O("subjectId", n)),
4753
4768
  order: [],
4754
4769
  take: 1,
4755
4770
  skip: void 0,
4756
4771
  projection: void 0
4757
- }))[0], sc = async (e) => {
4772
+ }))[0], cc = async (e) => {
4758
4773
  let t = (e.now ?? (() => /* @__PURE__ */ new Date()))(), n = e.tokens.expiresAt === void 0 ? null : new Date(e.tokens.expiresAt), r = {
4759
- id: A(Ks, X),
4774
+ id: A(qs, X),
4760
4775
  connectionId: e.definition.id,
4761
4776
  subjectId: e.subjectId,
4762
4777
  tenantId: e.tenantId,
@@ -4774,8 +4789,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4774
4789
  connectedAt: t,
4775
4790
  updatedAt: t
4776
4791
  };
4777
- return cc(e.store, r);
4778
- }, cc = (e, t) => e.upsert(X, t, {
4792
+ return lc(e.store, r);
4793
+ }, lc = (e, t) => e.upsert(X, t, {
4779
4794
  conflictColumns: ["connectionId", "subjectId"],
4780
4795
  update: [
4781
4796
  "kind",
@@ -4791,10 +4806,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4791
4806
  "metadata",
4792
4807
  "updatedAt"
4793
4808
  ]
4794
- }), lc = async (e, t, n) => {
4795
- let r = await oc(e, t, n);
4809
+ }), uc = async (e, t, n) => {
4810
+ let r = await sc(e, t, n);
4796
4811
  return r !== void 0 && e.delete(X, r.id);
4797
- }, uc = async (e, t, n) => {
4812
+ }, dc = async (e, t, n) => {
4798
4813
  let r = await e.query({
4799
4814
  table: X,
4800
4815
  predicate: O("subjectId", n),
@@ -4803,9 +4818,9 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4803
4818
  skip: void 0,
4804
4819
  projection: void 0
4805
4820
  }), i = new Map(r.map((e) => [String(e.connectionId), e]));
4806
- return t.list().map((e) => ac(e, i.get(e.id)));
4807
- }, dc = (e, t) => globalThis.fetch(e, t), fc = async (e, t, n) => {
4808
- let r = e.fetchImpl ?? dc, i, a;
4821
+ return t.list().map((e) => oc(e, i.get(e.id)));
4822
+ }, fc = (e, t) => globalThis.fetch(e, t), pc = async (e, t, n) => {
4823
+ let r = e.fetchImpl ?? fc, i, a;
4809
4824
  try {
4810
4825
  let n = await r(e.tokenUrl, {
4811
4826
  method: "POST",
@@ -4845,62 +4860,62 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4845
4860
  ...Number.isFinite(o.expires_in) ? { expiresAt: n() + o.expires_in * 1e3 } : {},
4846
4861
  scopes: (o.scope ?? e.scopes?.join(" ") ?? "").split(" ").filter(Boolean)
4847
4862
  };
4848
- }, pc = (e, t, n = Date.now) => fc(e, {
4863
+ }, mc = (e, t, n = Date.now) => pc(e, {
4849
4864
  grant_type: "authorization_code",
4850
4865
  client_id: e.clientId,
4851
4866
  client_secret: e.clientSecret,
4852
4867
  code: t.code,
4853
4868
  redirect_uri: t.redirectUri,
4854
4869
  ...t.codeVerifier ? { code_verifier: t.codeVerifier } : {}
4855
- }, n), mc = (e, t, n = Date.now) => fc(e, {
4870
+ }, n), hc = (e, t, n = Date.now) => pc(e, {
4856
4871
  grant_type: "refresh_token",
4857
4872
  client_id: e.clientId,
4858
4873
  client_secret: e.clientSecret,
4859
4874
  refresh_token: t
4860
- }, n), hc = 6e4, gc = 3e4, _c = class extends Error {
4875
+ }, n), gc = 6e4, _c = 3e4, vc = class extends Error {
4861
4876
  connectionId;
4862
4877
  subjectId;
4863
4878
  _tag = "ConnectionNotConnected";
4864
4879
  constructor(e, t) {
4865
4880
  super(`connection "${e}" is not connected for this subject`), this.connectionId = e, this.subjectId = t, this.name = "ConnectionNotConnected";
4866
4881
  }
4867
- }, vc = (e) => new Promise((t) => {
4882
+ }, yc = (e) => new Promise((t) => {
4868
4883
  setTimeout(t, e);
4869
- }), yc = /* @__PURE__ */ new Map(), bc = (e, t) => `${e}\u0000${t}`, xc = () => {
4870
- yc.clear();
4871
- }, Sc = (e, t) => ({
4884
+ }), bc = /* @__PURE__ */ new Map(), xc = (e, t) => `${e}\u0000${t}`, Sc = () => {
4885
+ bc.clear();
4886
+ }, Cc = (e, t) => ({
4872
4887
  connectionId: e.id,
4873
4888
  kind: e.kind,
4874
4889
  accessToken: mi(String(t.accessToken)),
4875
- expiresAt: nc(t.expiresAt),
4876
- scopes: ic(t.scopes),
4890
+ expiresAt: rc(t.expiresAt),
4891
+ scopes: ac(t.scopes),
4877
4892
  accountId: t.accountId ?? null,
4878
4893
  accountLabel: t.accountLabel ?? null
4879
- }), Cc = (e, t, n) => {
4880
- let r = nc(e.expiresAt);
4894
+ }), wc = (e, t, n) => {
4895
+ let r = rc(e.expiresAt);
4881
4896
  return r !== null && r.getTime() - n < t;
4882
- }, wc = async (e) => {
4883
- let t = e.now ?? Date.now, { store: n, definition: r, subjectId: i } = e, a = await oc(n, r.id, i);
4884
- if (a === void 0) throw new _c(r.id, i);
4885
- if (r.kind === "pat" || !Cc(a, r.refreshSkewMs ?? 6e4, t())) return Sc(r, a);
4886
- let o = bc(r.id, i), s = yc.get(o);
4897
+ }, Tc = async (e) => {
4898
+ let t = e.now ?? Date.now, { store: n, definition: r, subjectId: i } = e, a = await sc(n, r.id, i);
4899
+ if (a === void 0) throw new vc(r.id, i);
4900
+ if (r.kind === "pat" || !wc(a, r.refreshSkewMs ?? 6e4, t())) return Cc(r, a);
4901
+ let o = xc(r.id, i), s = bc.get(o);
4887
4902
  if (s !== void 0) return s;
4888
- let c = Tc({
4903
+ let c = Ec({
4889
4904
  ...e,
4890
4905
  now: t,
4891
4906
  row: a
4892
4907
  }).finally(() => {
4893
- yc.delete(o);
4908
+ bc.delete(o);
4894
4909
  });
4895
- return yc.set(o, c), c;
4896
- }, Tc = async (e) => {
4897
- let { store: t, subjectId: n, now: r } = e, i = e.definition, a = e.sleep ?? vc, o = i.refreshSkewMs ?? 6e4, s = e.row.id;
4910
+ return bc.set(o, c), c;
4911
+ }, Ec = async (e) => {
4912
+ let { store: t, subjectId: n, now: r } = e, i = e.definition, a = e.sleep ?? yc, o = i.refreshSkewMs ?? 6e4, s = e.row.id;
4898
4913
  if (await t.updateMany("_voltro_connections", { refreshLockedUntil: new Date(r() + 3e4) }, { where: C(O("id", s), he("refreshLockedUntil", new Date(r()))) }) === 0) {
4899
4914
  for (let e = 0; e < 10; e++) {
4900
4915
  await a(200);
4901
- let e = await oc(t, i.id, n);
4902
- if (e === void 0) throw new _c(i.id, n);
4903
- if (!Cc(e, o, r())) return Sc(i, e);
4916
+ let e = await sc(t, i.id, n);
4917
+ if (e === void 0) throw new vc(i.id, n);
4918
+ if (!wc(e, o, r())) return Cc(i, e);
4904
4919
  }
4905
4920
  throw new R({
4906
4921
  connectionId: i.id,
@@ -4921,7 +4936,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4921
4936
  });
4922
4937
  let l;
4923
4938
  try {
4924
- l = await mc(i, mi(String(c)), r);
4939
+ l = await hc(i, mi(String(c)), r);
4925
4940
  } catch (e) {
4926
4941
  let n = e instanceof R ? e : new R({
4927
4942
  connectionId: i.id,
@@ -4938,7 +4953,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4938
4953
  refreshToken: null,
4939
4954
  expiresAt: null
4940
4955
  }
4941
- }), Gs.warn("connection refresh failed", {
4956
+ }), Ks.warn("connection refresh failed", {
4942
4957
  connectionId: i.id,
4943
4958
  transient: n.transient,
4944
4959
  reason: n.reason
@@ -4954,32 +4969,32 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4954
4969
  refreshLockedUntil: /* @__PURE__ */ new Date(0),
4955
4970
  updatedAt: new Date(r())
4956
4971
  };
4957
- return Sc(i, await t.update(X, s, u) ?? {
4972
+ return Cc(i, await t.update(X, s, u) ?? {
4958
4973
  ...e.row,
4959
4974
  ...u
4960
4975
  });
4961
- }, Ec = (e = 32) => {
4976
+ }, Dc = (e = 32) => {
4962
4977
  let t = new Uint8Array(e);
4963
4978
  return globalThis.crypto.getRandomValues(t), Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
4964
- }, Dc = (e) => {
4979
+ }, Oc = (e) => {
4965
4980
  let t = "";
4966
4981
  for (let n of e) t += String.fromCharCode(n);
4967
4982
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4968
- }, Oc = async (e) => {
4983
+ }, kc = async (e) => {
4969
4984
  let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
4970
- return Dc(new Uint8Array(t));
4971
- }, kc = 10 * 6e4, Ac = (e) => `/_voltro/connections/${e}/callback`, jc = (e) => e === void 0 || e.length === 0 || !e.startsWith("/") || e.startsWith("//") || e.startsWith("/\\") ? "/" : e, Mc = (e, t) => e.redirectUri ?? `${t.replace(/\/+$/, "")}${Ac(e.id)}`, Nc = async (e) => {
4972
- let t = (e.now ?? (() => /* @__PURE__ */ new Date()))(), { definition: n } = e, r = Ec(), i = n.pkce === !1 ? null : Ec(48), a = Mc(n, e.publicUrl);
4973
- await e.store.insert(Js, {
4974
- id: A(Ys, Js),
4985
+ return Oc(new Uint8Array(t));
4986
+ }, Ac = 10 * 6e4, jc = (e) => `/_voltro/connections/${e}/callback`, Mc = (e) => e === void 0 || e.length === 0 || !e.startsWith("/") || e.startsWith("//") || e.startsWith("/\\") ? "/" : e, Nc = (e, t) => e.redirectUri ?? `${t.replace(/\/+$/, "")}${jc(e.id)}`, Pc = async (e) => {
4987
+ let t = (e.now ?? (() => /* @__PURE__ */ new Date()))(), { definition: n } = e, r = Dc(), i = n.pkce === !1 ? null : Dc(48), a = Nc(n, e.publicUrl);
4988
+ await e.store.insert(Ys, {
4989
+ id: A(Xs, Ys),
4975
4990
  state: r,
4976
4991
  connectionId: n.id,
4977
4992
  subjectId: e.subjectId,
4978
4993
  tenantId: e.tenantId,
4979
4994
  codeVerifier: i === null ? null : pi(i),
4980
- redirectTo: jc(e.redirectTo),
4995
+ redirectTo: Mc(e.redirectTo),
4981
4996
  createdAt: t,
4982
- expiresAt: new Date(t.getTime() + kc)
4997
+ expiresAt: new Date(t.getTime() + Ac)
4983
4998
  });
4984
4999
  let o = new URLSearchParams({
4985
5000
  response_type: "code",
@@ -4989,15 +5004,15 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
4989
5004
  ...n.scopes && n.scopes.length > 0 ? { scope: n.scopes.join(" ") } : {},
4990
5005
  ...n.authorizeParams ?? {}
4991
5006
  });
4992
- i !== null && (o.set("code_challenge", await Oc(i)), o.set("code_challenge_method", "S256"));
5007
+ i !== null && (o.set("code_challenge", await kc(i)), o.set("code_challenge_method", "S256"));
4993
5008
  let s = n.authorizeUrl.includes("?") ? "&" : "?";
4994
5009
  return {
4995
5010
  authorizeUrl: `${n.authorizeUrl}${s}${o.toString()}`,
4996
5011
  state: r
4997
5012
  };
4998
- }, Pc = async (e) => {
5013
+ }, Fc = async (e) => {
4999
5014
  let t = (e.now ?? (() => /* @__PURE__ */ new Date()))(), n = (await e.store.query({
5000
- table: Js,
5015
+ table: Ys,
5001
5016
  predicate: O("state", e.state),
5002
5017
  order: [],
5003
5018
  take: 1,
@@ -5009,8 +5024,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5009
5024
  reason: "unknown or already-used handshake state",
5010
5025
  transient: !1
5011
5026
  });
5012
- await e.store.delete(Js, n.id);
5013
- let r = String(n.connectionId), i = nc(n.expiresAt);
5027
+ await e.store.delete(Ys, n.id);
5028
+ let r = String(n.connectionId), i = rc(n.expiresAt);
5014
5029
  if (i !== null && i.getTime() < t.getTime()) throw new R({
5015
5030
  connectionId: r,
5016
5031
  reason: "handshake expired — start again",
@@ -5022,17 +5037,17 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5022
5037
  reason: "no oauth2 connection is declared under that id",
5023
5038
  transient: !1
5024
5039
  });
5025
- let o = n.codeVerifier === null || n.codeVerifier === void 0 ? null : mi(String(n.codeVerifier)), s = await pc(a, {
5040
+ let o = n.codeVerifier === null || n.codeVerifier === void 0 ? null : mi(String(n.codeVerifier)), s = await mc(a, {
5026
5041
  code: e.code,
5027
- redirectUri: Mc(a, e.publicUrl),
5042
+ redirectUri: Nc(a, e.publicUrl),
5028
5043
  codeVerifier: o
5029
5044
  }, () => t.getTime()), c = a.identify === void 0 ? void 0 : await a.identify(s).catch((e) => {
5030
- Gs.warn("connection identify failed; storing without account details", {
5045
+ Ks.warn("connection identify failed; storing without account details", {
5031
5046
  connectionId: r,
5032
5047
  reason: String(e)
5033
5048
  });
5034
5049
  });
5035
- return await sc({
5050
+ return await cc({
5036
5051
  store: e.store,
5037
5052
  definition: a,
5038
5053
  subjectId: String(n.subjectId),
@@ -5042,11 +5057,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5042
5057
  now: () => t
5043
5058
  }), {
5044
5059
  connectionId: r,
5045
- redirectTo: jc(String(n.redirectTo ?? "/"))
5060
+ redirectTo: Mc(String(n.redirectTo ?? "/"))
5046
5061
  };
5047
- }, Fc = async (e, t = /* @__PURE__ */ new Date()) => {
5062
+ }, Ic = async (e, t = /* @__PURE__ */ new Date()) => {
5048
5063
  let n = await e.query({
5049
- table: Js,
5064
+ table: Ys,
5050
5065
  predicate: he("expiresAt", t),
5051
5066
  order: [],
5052
5067
  take: void 0,
@@ -5055,27 +5070,27 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5055
5070
  }), r = 0;
5056
5071
  for (let t of n) await e.delete("_voltro_connection_grants", t.id) && r++;
5057
5072
  return r;
5058
- }, Ic, Lc = (e) => {
5059
- Ic = e;
5060
- }, Rc = () => Ic, zc = (e, t) => {
5061
- let n = Ic;
5073
+ }, Lc, Rc = (e) => {
5074
+ Lc = e;
5075
+ }, zc = () => Lc, Bc = (e, t) => {
5076
+ let n = Lc;
5062
5077
  return n === void 0 ? Promise.reject(/* @__PURE__ */ Error(`resolveConnectionForSubject("${t}"): no connection vault is registered — the app declares no \`*.connection.ts\`, or this call ran before boot completed.`)) : n(e, t);
5063
- }, Bc = (e) => async (t, n) => {
5078
+ }, Vc = (e) => async (t, n) => {
5064
5079
  let r = e.registry.get(n);
5065
5080
  if (r === void 0) throw Error(`connection "${n}" is not declared. Declared: ${e.registry.list().map((e) => e.id).join(", ") || "(none)"}.`);
5066
5081
  let i = t.id ?? null;
5067
- if (i === null || i === "") throw new _c(n, "<anonymous>");
5068
- return wc({
5082
+ if (i === null || i === "") throw new vc(n, "<anonymous>");
5083
+ return Tc({
5069
5084
  store: e.store,
5070
5085
  definition: r,
5071
5086
  subjectId: i
5072
5087
  });
5073
- }, Vc = (e) => {
5088
+ }, Hc = (e) => {
5074
5089
  let t = e.subject.id ?? null, n = async (n) => {
5075
5090
  let r = e.registry.get(n);
5076
5091
  if (r === void 0) throw Error(`ctx.connections.get("${n}"): no such connection is declared. Declared: ${e.registry.list().map((e) => e.id).join(", ") || "(none)"}.`);
5077
- if (t === null || t === "") throw new _c(n, "<anonymous>");
5078
- return wc({
5092
+ if (t === null || t === "") throw new vc(n, "<anonymous>");
5093
+ return Tc({
5079
5094
  store: e.store,
5080
5095
  definition: r,
5081
5096
  subjectId: t
@@ -5087,7 +5102,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5087
5102
  try {
5088
5103
  return await n(e);
5089
5104
  } catch (e) {
5090
- if (e instanceof _c) return null;
5105
+ if (e instanceof vc) return null;
5091
5106
  throw e;
5092
5107
  }
5093
5108
  },
@@ -5102,17 +5117,17 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5102
5117
  expiresAt: null,
5103
5118
  lastError: null,
5104
5119
  connectedAt: null
5105
- })) : uc(e.store, e.registry, t)
5120
+ })) : dc(e.store, e.registry, t)
5106
5121
  };
5107
- }, Hc = (e, t) => {
5122
+ }, Uc = (e, t) => {
5108
5123
  let n = e.request?.subject?.id ?? null;
5109
5124
  if (n === null || n === "") throw new Je({ connectionId: t });
5110
5125
  return n;
5111
- }, Uc = (e, t) => {
5126
+ }, Wc = (e, t) => {
5112
5127
  let n = e.registry.get(t);
5113
5128
  if (n === void 0) throw new qe({ connectionId: t });
5114
5129
  return n;
5115
- }, Wc = (e) => async (t, n) => {
5130
+ }, Gc = (e) => async (t, n) => {
5116
5131
  let r = n.request?.subject?.id ?? null;
5117
5132
  return r === null || r === "" ? e.registry.list().map((e) => ({
5118
5133
  connectionId: e.id,
@@ -5125,15 +5140,15 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5125
5140
  expiresAt: null,
5126
5141
  lastError: null,
5127
5142
  connectedAt: null
5128
- })) : uc(n.store, e.registry, r);
5129
- }, Gc = (e) => async (t, n) => {
5130
- let r = Uc(e, t.connectionId), i = Hc(n, t.connectionId);
5143
+ })) : dc(n.store, e.registry, r);
5144
+ }, Kc = (e) => async (t, n) => {
5145
+ let r = Wc(e, t.connectionId), i = Uc(n, t.connectionId);
5131
5146
  if (r.kind !== "oauth2") throw new Ke({
5132
5147
  connectionId: t.connectionId,
5133
5148
  expected: "oauth2",
5134
5149
  actual: r.kind
5135
5150
  });
5136
- return Nc({
5151
+ return Pc({
5137
5152
  store: n.store,
5138
5153
  definition: r,
5139
5154
  subjectId: i,
@@ -5141,8 +5156,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5141
5156
  publicUrl: e.publicUrl,
5142
5157
  ...t.redirectTo === void 0 ? {} : { redirectTo: t.redirectTo }
5143
5158
  });
5144
- }, Kc = (e) => async (t, n) => {
5145
- let r = Uc(e, t.connectionId), i = Hc(n, t.connectionId);
5159
+ }, qc = (e) => async (t, n) => {
5160
+ let r = Wc(e, t.connectionId), i = Uc(n, t.connectionId);
5146
5161
  if (r.kind !== "pat") throw new Ke({
5147
5162
  connectionId: t.connectionId,
5148
5163
  expected: "pat",
@@ -5164,7 +5179,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5164
5179
  transient: !1
5165
5180
  });
5166
5181
  }
5167
- return await sc({
5182
+ return await cc({
5168
5183
  store: n.store,
5169
5184
  definition: r,
5170
5185
  subjectId: i,
@@ -5175,20 +5190,20 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5175
5190
  },
5176
5191
  ...o === void 0 ? {} : { account: o }
5177
5192
  }), { ok: !0 };
5178
- }, qc = (e) => async (t, n) => {
5179
- Uc(e, t.connectionId);
5180
- let r = Hc(n, t.connectionId);
5181
- return { ok: await lc(n.store, t.connectionId, r) };
5182
- }, Jc = "admin:full", Yc = class extends y.TaggedError()("AccessDenied", {
5193
+ }, Jc = (e) => async (t, n) => {
5194
+ Wc(e, t.connectionId);
5195
+ let r = Uc(n, t.connectionId);
5196
+ return { ok: await uc(n.store, t.connectionId, r) };
5197
+ }, Yc = "admin:full", Xc = class extends y.TaggedError()("AccessDenied", {
5183
5198
  action: y.String,
5184
5199
  resourceType: y.String,
5185
5200
  resourceId: y.String
5186
- }) {}, Xc = /* @__PURE__ */ new Map(), Zc = (e) => {
5201
+ }) {}, Zc = /* @__PURE__ */ new Map(), Qc = (e) => {
5187
5202
  if (typeof e.resourceType != "string" || e.resourceType.length === 0) throw Error("defineResourcePolicy: a non-empty `resourceType` is required");
5188
5203
  if (e.actions === void 0 || Object.keys(e.actions).length === 0) throw Error(`resource policy '${e.resourceType}': at least one action is required`);
5189
- if (Xc.has(e.resourceType)) throw Error(`resource policy '${e.resourceType}' is already registered — types must be unique`);
5190
- return Xc.set(e.resourceType, e), e;
5191
- }, Qc = (e) => Xc.get(e), $c = () => [...Xc.values()], el = () => Xc.clear(), tl = () => $c().map((e) => {
5204
+ if (Zc.has(e.resourceType)) throw Error(`resource policy '${e.resourceType}' is already registered — types must be unique`);
5205
+ return Zc.set(e.resourceType, e), e;
5206
+ }, $c = (e) => Zc.get(e), el = () => [...Zc.values()], tl = () => Zc.clear(), nl = () => el().map((e) => {
5192
5207
  let t = /* @__PURE__ */ new Set();
5193
5208
  for (let n of Object.values(e.actions)) for (let e of n) t.add(e);
5194
5209
  for (let [n, r] of Object.entries(e.implies ?? {})) {
@@ -5201,7 +5216,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5201
5216
  relations: [...t],
5202
5217
  implies: e.implies ?? {}
5203
5218
  };
5204
- }), nl = (e, t) => {
5219
+ }), rl = (e, t) => {
5205
5220
  let n = new Set(e);
5206
5221
  if (t === void 0) return n;
5207
5222
  let r = [...e];
@@ -5210,39 +5225,39 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5210
5225
  for (let i of t[e] ?? []) n.has(i) || (n.add(i), r.push(i));
5211
5226
  }
5212
5227
  return n;
5213
- }, rl = (e, t, n, r) => e.id === null ? /* @__PURE__ */ new Set() : nl(n.filter((n) => n.subjectId === e.id && n.resourceType === t.type && n.resourceId === t.id).map((e) => e.relation), r.implies), il = (e, t, n, r) => {
5228
+ }, il = (e, t, n, r) => e.id === null ? /* @__PURE__ */ new Set() : rl(n.filter((n) => n.subjectId === e.id && n.resourceType === t.type && n.resourceId === t.id).map((e) => e.relation), r.implies), al = (e, t, n, r) => {
5214
5229
  if (e.scopes?.includes("admin:full")) return !0;
5215
5230
  if (e.id === null || n.tenantId != null && e.tenantId !== n.tenantId) return !1;
5216
5231
  let i = r.policy.actions[t];
5217
5232
  if (i === void 0 || i.length === 0) return !1;
5218
- let a = rl(e, n, r.tuples, r.policy);
5233
+ let a = il(e, n, r.tuples, r.policy);
5219
5234
  return i.some((e) => a.has(e));
5220
- }, al = (e, t, n, r) => {
5221
- if (!il(e, t, n, r)) throw new Yc({
5235
+ }, ol = (e, t, n, r) => {
5236
+ if (!al(e, t, n, r)) throw new Xc({
5222
5237
  action: t,
5223
5238
  resourceType: n.type,
5224
5239
  resourceId: n.id
5225
5240
  });
5226
- }, ol = (e, t, n, r, i) => r.filter((r) => il(e, t, {
5241
+ }, sl = (e, t, n, r, i) => r.filter((r) => al(e, t, {
5227
5242
  type: n,
5228
5243
  id: r.id,
5229
5244
  ...r.tenantId === void 0 ? {} : { tenantId: r.tenantId }
5230
- }, i)), sl = (e, t) => {
5245
+ }, i)), cl = (e, t) => {
5231
5246
  let n = new Set(t.map((e) => e.id));
5232
5247
  return e.filter((e) => !n.has(e.id)).map((e) => e.id);
5233
- }, cl = new Ft(), ll = (e) => {
5234
- cl.enterWith(e);
5235
- }, ul = () => cl.getStore(), dl = (e, t) => cl.run(e, t), fl = B({ scope: "voltro:policy" }), pl, ml = (e) => {
5236
- pl = e;
5237
- }, hl = () => pl, gl = () => {
5238
- gt((e) => o.gen(function* () {
5239
- let t = Qc(e.resourceType);
5240
- if (t === void 0) return fl.warn("policy guard denied — no resource policy registered for this type", {
5248
+ }, ll = new Lt(), ul = (e) => {
5249
+ ll.enterWith(e);
5250
+ }, dl = () => ll.getStore(), fl = (e, t) => ll.run(e, t), pl = z({ scope: "voltro:policy" }), ml, hl = (e) => {
5251
+ ml = e;
5252
+ }, gl = () => ml, _l = () => {
5253
+ _t((e) => o.gen(function* () {
5254
+ let t = $c(e.resourceType);
5255
+ if (t === void 0) return pl.warn("policy guard denied — no resource policy registered for this type", {
5241
5256
  resourceType: e.resourceType,
5242
5257
  action: e.action
5243
5258
  }), !1;
5244
- let n = pl;
5245
- if (n === void 0) return fl.warn("policy guard denied — no tuple source registered (call setTupleSource at boot)", {
5259
+ let n = ml;
5260
+ if (n === void 0) return pl.warn("policy guard denied — no tuple source registered (call setTupleSource at boot)", {
5246
5261
  resourceType: e.resourceType,
5247
5262
  action: e.action
5248
5263
  }), !1;
@@ -5251,14 +5266,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5251
5266
  subjectId: e.subject.id,
5252
5267
  resourceType: e.resourceType,
5253
5268
  resourceId: e.resourceId,
5254
- load: ul()
5269
+ load: dl()
5255
5270
  }),
5256
5271
  catch: (e) => e
5257
- }).pipe(o.catchAll((t) => (fl.error("policy guard denied — tuple source failed", {
5272
+ }).pipe(o.catchAll((t) => (pl.error("policy guard denied — tuple source failed", {
5258
5273
  resourceType: e.resourceType,
5259
5274
  resourceId: e.resourceId
5260
5275
  }, t), o.succeed([])))), i = e.subject;
5261
- return il({
5276
+ return al({
5262
5277
  id: e.subject.id,
5263
5278
  tenantId: i.tenantId ?? null,
5264
5279
  ...i.scopes === void 0 ? {} : { scopes: i.scopes }
@@ -5271,10 +5286,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5271
5286
  tuples: r
5272
5287
  });
5273
5288
  }));
5274
- }, _l = (e) => {
5275
- Promise.resolve().then(e);
5276
5289
  }, vl = (e) => {
5277
- let t = e.schedule ?? _l, n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), i = (e, t) => `${e}\u0000${t}`, a = async (t) => {
5290
+ Promise.resolve().then(e);
5291
+ }, yl = (e) => {
5292
+ let t = e.schedule ?? vl, n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), i = (e, t) => `${e}\u0000${t}`, a = async (t) => {
5278
5293
  let a = r.get(t);
5279
5294
  if (a === void 0) return;
5280
5295
  r.delete(t);
@@ -5320,23 +5335,23 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5320
5335
  load: async (e, t) => (await o(e, [t]))[0] ?? null,
5321
5336
  loadMany: (e, t) => o(e, t)
5322
5337
  };
5323
- }, yl = u.effect(V.HttpClient, o.map(V.HttpClient, (e) => e.pipe(V.mapRequestEffect((e) => o.currentSpan.pipe(o.map((t) => e.headers.traceparent === void 0 ? Ct.setHeader(e, "traceparent", ti({
5338
+ }, bl = u.effect(Ct.HttpClient, o.map(Ct.HttpClient, (e) => e.pipe(Ct.mapRequestEffect((e) => o.currentSpan.pipe(o.map((t) => e.headers.traceparent === void 0 ? Tt.setHeader(e, "traceparent", ti({
5324
5339
  traceId: t.traceId,
5325
5340
  spanId: t.spanId,
5326
5341
  sampled: t.sampled
5327
- })) : e), o.catchAll(() => o.succeed(e))))))), bl = class extends Error {
5342
+ })) : e), o.catchAll(() => o.succeed(e))))))), xl = class extends Error {
5328
5343
  url;
5329
5344
  reason;
5330
5345
  _tag = "SsrfBlockedError";
5331
5346
  constructor(e, t) {
5332
5347
  super(`SSRF: blocked outbound request to ${e} — ${t}. If this target is intentional, add its host to \`http.allowHosts\` in app.config.ts.`), this.url = e, this.reason = t, this.name = "SsrfBlockedError";
5333
5348
  }
5334
- }, xl = (e, t) => e === 0 || e === 10 || e === 127 || e === 100 && t >= 64 && t <= 127 || e === 169 && t === 254 || e === 172 && t >= 16 && t <= 31 || e === 192 && t === 168 || e === 198 && (t === 18 || t === 19) || e >= 224, Sl = (e) => e === "::" || e === "::1" || e.startsWith("fc") || e.startsWith("fd") || e.startsWith("fe80") || e.startsWith("::ffff:"), Cl = (e, t, n) => n.some((n) => {
5349
+ }, Sl = (e, t) => e === 0 || e === 10 || e === 127 || e === 100 && t >= 64 && t <= 127 || e === 169 && t === 254 || e === 172 && t >= 16 && t <= 31 || e === 192 && t === 168 || e === 198 && (t === 18 || t === 19) || e >= 224, Cl = (e) => e === "::" || e === "::1" || e.startsWith("fc") || e.startsWith("fd") || e.startsWith("fe80") || e.startsWith("::ffff:"), wl = (e, t, n) => n.some((n) => {
5335
5350
  let r = n.trim().toLowerCase();
5336
5351
  if (r === "") return !1;
5337
5352
  let i = t === "" ? e : `${e}:${t}`;
5338
5353
  return r === e || r === i ? !0 : r.startsWith("*.") ? e.endsWith(r.slice(1)) : !1;
5339
- }), wl = (e, t = {}) => {
5354
+ }), Tl = (e, t = {}) => {
5340
5355
  let n;
5341
5356
  try {
5342
5357
  n = new URL(e);
@@ -5345,30 +5360,30 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5345
5360
  }
5346
5361
  if (n.protocol !== "http:" && n.protocol !== "https:") return `blocked scheme "${n.protocol}"`;
5347
5362
  let r = n.hostname.replace(/^\[|\]$/g, "").toLowerCase();
5348
- if (Cl(r, n.port, t.allowHosts ?? [])) return null;
5363
+ if (wl(r, n.port, t.allowHosts ?? [])) return null;
5349
5364
  if (r === "localhost" || r.endsWith(".localhost") || r.endsWith(".internal") || r.endsWith(".local")) return `blocked host "${r}"`;
5350
5365
  let i = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(r);
5351
5366
  if (i) {
5352
5367
  let e = Number(i[1]), t = Number(i[2]);
5353
- return e > 255 || t > 255 || Number(i[3]) > 255 || Number(i[4]) > 255 ? "malformed ipv4 literal" : xl(e, t) ? `blocked private/reserved address ${r}` : null;
5368
+ return e > 255 || t > 255 || Number(i[3]) > 255 || Number(i[4]) > 255 ? "malformed ipv4 literal" : Sl(e, t) ? `blocked private/reserved address ${r}` : null;
5354
5369
  }
5355
5370
  if (r.includes(":")) {
5356
5371
  let e = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(r);
5357
- return e ? wl(`${n.protocol}//${e[1]}`, t) : Sl(r) ? `blocked private/reserved address ${r}` : null;
5372
+ return e ? Tl(`${n.protocol}//${e[1]}`, t) : Cl(r) ? `blocked private/reserved address ${r}` : null;
5358
5373
  }
5359
5374
  return null;
5360
- }, Tl = (e = {}) => u.effect(V.HttpClient, o.map(V.HttpClient, (t) => {
5361
- let n = V.transform(t, (t, n) => o.suspend(() => {
5362
- let r = wl(n.url, e);
5363
- return r === null ? t : o.fail(new St.RequestError({
5375
+ }, El = (e = {}) => u.effect(Ct.HttpClient, o.map(Ct.HttpClient, (t) => {
5376
+ let n = Ct.transform(t, (t, n) => o.suspend(() => {
5377
+ let r = Tl(n.url, e);
5378
+ return r === null ? t : o.fail(new wt.RequestError({
5364
5379
  request: n,
5365
5380
  reason: "Transport",
5366
- cause: new bl(n.url, r),
5381
+ cause: new xl(n.url, r),
5367
5382
  description: `SSRF policy: ${r}`
5368
5383
  }));
5369
5384
  }));
5370
- return V.followRedirects(n, e.maxRedirects ?? 5);
5371
- })), El = (e) => {
5385
+ return Ct.followRedirects(n, e.maxRedirects ?? 5);
5386
+ })), Dl = (e) => {
5372
5387
  let t = e.now ?? Date.now, n = e.intervalMs ?? 3e4, r = e.maxPending ?? 500, i = /* @__PURE__ */ new Map(), a = !1, o = async () => {
5373
5388
  if (i.size === 0) return;
5374
5389
  let t = i;
@@ -5397,7 +5412,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5397
5412
  },
5398
5413
  pending: () => i.size
5399
5414
  };
5400
- }, Dl = "voltro/audit", Ol = "voltro/softDelete", kl = "voltro/expires", Al = "voltro/tenant", jl = (e) => {
5415
+ }, Ol = "voltro/audit", kl = "voltro/softDelete", Al = "voltro/expires", jl = "voltro/tenant", Ml = (e) => {
5401
5416
  let t = /* @__PURE__ */ new Map();
5402
5417
  for (let n of e) {
5403
5418
  let e = /* @__PURE__ */ new Set();
@@ -5443,17 +5458,17 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5443
5458
  return !1;
5444
5459
  },
5445
5460
  idScheme: (e) => t.get(e)?.idScheme,
5446
- defaultFactories: (e) => t.get(e)?.defaultFactories ?? Ml,
5447
- computedFields: (e) => t.get(e)?.computedFields ?? Nl,
5461
+ defaultFactories: (e) => t.get(e)?.defaultFactories ?? Nl,
5462
+ computedFields: (e) => t.get(e)?.computedFields ?? Pl,
5448
5463
  versionColumn: (e) => t.get(e)?.versionColumn,
5449
- generatedColumns: (e) => t.get(e)?.generatedColumns ?? Pl,
5464
+ generatedColumns: (e) => t.get(e)?.generatedColumns ?? Fl,
5450
5465
  insertSchema: (e) => t.get(e)?.insertSchema,
5451
5466
  validatePatchSchema: (e) => t.get(e)?.validatePatchSchema
5452
5467
  };
5453
- }, Ml = /* @__PURE__ */ new Map(), Nl = /* @__PURE__ */ new Map(), Pl = /* @__PURE__ */ new Set(), Fl = jl([]), Il = B({ scope: "store.fieldEncryption" }), Ll = (e, t) => {
5468
+ }, Nl = /* @__PURE__ */ new Map(), Pl = /* @__PURE__ */ new Map(), Fl = /* @__PURE__ */ new Set(), Il = Ml([]), Ll = z({ scope: "store.fieldEncryption" }), Rl = (e, t) => {
5454
5469
  let n = t, r = process.env.VOLTRO_FIELD_DECRYPT_ON_ERROR === "null" ? "null" : "throw", i = /* @__PURE__ */ new Set(), a = (e) => {
5455
5470
  let t = `${e.table}.${e.column}`;
5456
- i.has(t) || (i.add(t), Il.warn("encrypted column degraded to null — could not decrypt with the active key", {
5471
+ i.has(t) || (i.add(t), Ll.warn("encrypted column degraded to null — could not decrypt with the active key", {
5457
5472
  table: e.table,
5458
5473
  column: e.column,
5459
5474
  reason: e.reason,
@@ -5477,7 +5492,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5477
5492
  e.injectExternalChange(t);
5478
5493
  },
5479
5494
  ...e.changeScope === void 0 ? {} : { changeScope: e.changeScope },
5480
- ...e.withNamespace === void 0 ? {} : { withNamespace: (n) => Ll(e.withNamespace(n), t) },
5495
+ ...e.withNamespace === void 0 ? {} : { withNamespace: (n) => Rl(e.withNamespace(n), t) },
5481
5496
  ...e.raw === void 0 ? {} : { raw: ((...t) => e.raw(...t)) },
5482
5497
  ...e.close === void 0 ? {} : { close: (t) => e.close(t) },
5483
5498
  ...e.ping === void 0 ? {} : { ping: () => e.ping() },
@@ -5489,24 +5504,24 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5489
5504
  upsert: async (t, n, r) => c(t, await e.upsert(t, o(t, n), r)),
5490
5505
  insertIgnore: async (t, n, r) => c(t, await e.insertIgnore(t, o(t, n), r)),
5491
5506
  patchJson: async (t, n, r, i) => c(t, await e.patchJson(t, n, r, i)),
5492
- transactional: (n) => e.transactional((e) => n(Ll(e, t)))
5507
+ transactional: (n) => e.transactional((e) => n(Rl(e, t)))
5493
5508
  };
5494
- }, Rl = (e, t) => {
5509
+ }, zl = (e, t) => {
5495
5510
  if (t === void 0 || t.length === 0) return e;
5496
5511
  let n = { ...e };
5497
5512
  for (let e of t) delete n[e];
5498
5513
  return n;
5499
- }, zl = (e, t) => {
5514
+ }, Bl = (e, t) => {
5500
5515
  let n = j(e), r = n === void 0 ? [] : Oe(n);
5501
5516
  return r.length === 0 ? t ?? [] : t === void 0 ? r : [...t, ...r];
5502
- }, Bl = (e, t) => t.length === 0 ? e : e.map((e) => Rl(e, t)), Vl = (e, t, n, r, i) => {
5517
+ }, Vl = (e, t) => t.length === 0 ? e : e.map((e) => zl(e, t)), Hl = (e, t, n, r, i) => {
5503
5518
  let a = {
5504
5519
  ...t?.(r) ?? {},
5505
5520
  ...n?.(i) ?? {}
5506
5521
  }, o = e;
5507
5522
  for (let [e, t] of Object.entries(a)) t !== void 0 && (o = o.where(e, t));
5508
5523
  return o;
5509
- }, Hl = 1e3, Ul = (e, t = Hl) => {
5524
+ }, Ul = 1e3, Wl = (e, t = Ul) => {
5510
5525
  let n = (e) => typeof e == "number" && Number.isFinite(e) ? e : void 0, r = (e) => Math.max(1, Math.min(Math.floor(e), t)), i = n(e.page);
5511
5526
  if (i !== void 0) {
5512
5527
  let t = r(n(e.pageSize) ?? 100);
@@ -5519,35 +5534,35 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5519
5534
  limit: r(n(e.limit) ?? 100),
5520
5535
  offset: Math.max(0, Math.floor(n(e.offset) ?? 0))
5521
5536
  };
5522
- }, Wl = {
5537
+ }, Gl = {
5523
5538
  list: (e, t = {}) => async (n, r) => {
5524
5539
  let i = n ?? {}, a = r.store.select(e);
5525
5540
  if (t.columns !== void 0 && t.columns.length > 0) {
5526
- let n = new Set(zl(e, void 0)), r = t.columns.filter((e) => !n.has(e));
5541
+ let n = new Set(Bl(e, void 0)), r = t.columns.filter((e) => !n.has(e));
5527
5542
  r.length > 0 && (a = a.select(...r));
5528
5543
  }
5529
- t.include !== void 0 && (a = a.with(t.include)), a = Vl(a, t.filter, t.scope, i, r);
5544
+ t.include !== void 0 && (a = a.with(t.include)), a = Hl(a, t.filter, t.scope, i, r);
5530
5545
  for (let e of t.sort ?? []) a = a.orderBy(e.column, e.direction ?? "asc");
5531
5546
  if (t.paginate === !0) {
5532
- let { limit: e, offset: n } = Ul(i, t.maxPageSize);
5547
+ let { limit: e, offset: n } = Wl(i, t.maxPageSize);
5533
5548
  a = a.limit(e).offset(n);
5534
5549
  }
5535
- return Bl(await a.all(), zl(e, t.redact));
5550
+ return Vl(await a.all(), Bl(e, t.redact));
5536
5551
  },
5537
5552
  getById: (e, t = {}) => async (n, r) => {
5538
5553
  let i = r.store.select(e).where("id", n.id);
5539
5554
  t.include !== void 0 && (i = i.with(t.include));
5540
5555
  let a = await i.first();
5541
- return a === null ? null : Rl(a, zl(e, t.redact));
5556
+ return a === null ? null : zl(a, Bl(e, t.redact));
5542
5557
  },
5543
- create: (e, t = {}) => async (n, r) => Rl(await r.store.insert(e, n), zl(e, t.redact)),
5558
+ create: (e, t = {}) => async (n, r) => zl(await r.store.insert(e, n), Bl(e, t.redact)),
5544
5559
  update: (e, t = {}) => async (n, r) => {
5545
5560
  let { id: i, ...a } = n, o = await r.store.update(e, i, a);
5546
- return o === null ? null : Rl(o, zl(e, t.redact));
5561
+ return o === null ? null : zl(o, Bl(e, t.redact));
5547
5562
  },
5548
- count: (e, t = {}) => async (n, r) => Vl(r.store.select(e), t.filter, t.scope, n ?? {}, r).count(),
5563
+ count: (e, t = {}) => async (n, r) => Hl(r.store.select(e), t.filter, t.scope, n ?? {}, r).count(),
5549
5564
  remove: (e) => async (t, n) => ({ deleted: await n.store.delete(e, t.id) })
5550
- }, Gl = (e) => {
5565
+ }, Kl = (e) => {
5551
5566
  let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), r = (e) => {
5552
5567
  if (!n.has(e)) switch (n.add(e), e._tag) {
5553
5568
  case "TypeLiteral":
@@ -5574,7 +5589,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5574
5589
  }
5575
5590
  };
5576
5591
  return r(e.ast), t;
5577
- }, Kl = (e) => {
5592
+ }, ql = (e) => {
5578
5593
  let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), r = (e) => {
5579
5594
  switch (e._tag) {
5580
5595
  case "Literal": return e.literal === null;
@@ -5609,43 +5624,127 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5609
5624
  }
5610
5625
  };
5611
5626
  return i(e.ast), t;
5612
- }, ql = (e, t) => {
5627
+ }, Jl = (e, t) => {
5613
5628
  let n = e.source === void 0 ? [] : Array.isArray(e.source) ? e.source : [e.source];
5614
5629
  if (n.length === 0) return [];
5615
- let r = Gl(e.output), i = Kl(e.output), a = [];
5630
+ let r = Kl(e.output), i = ql(e.output), a = [];
5616
5631
  for (let o of n) for (let n of t.get(o) ?? []) r.has(n) && !i.has(n) && a.push({
5617
5632
  query: e.name,
5618
5633
  table: o,
5619
5634
  column: n
5620
5635
  });
5621
5636
  return a;
5622
- }, Jl = (e) => {
5637
+ }, Yl = (e) => {
5623
5638
  if (e.length !== 0) return `A wire-reachable query exposes a server-only column:\n${e.map((e) => ` • query '${e.query}' output declares '${e.column}' — a .serverOnly() column of '${e.table}'`).join("\n")}\nThree ways out, in order of preference:\n 1. Omit the column from the query's output schema. The crud.* read helpers strip these automatically.\n 2. Keep the KEY but type it \`Schema.Null\` — for a view that must stay wire-compatible (an importer that breaks if the key vanishes) while never sending a value. The audit accepts that, because the schema then PROVES no value can flow instead of promising it. Pair it with a \`hasX\` boolean.\n 3. Drop the .serverOnly() marker, if the column may in fact reach a client.\nNote the audit reads the DECLARED shape, not what your handler emits: a field typed \`string\` that you always set to null still fails, and should — the next edit to that handler is one line away from sending it.`;
5624
- }, Yl = (e, t) => e.cache?.scope === "global" ? (e.source === void 0 ? [] : Array.isArray(e.source) ? e.source : [e.source]).filter((e) => t.has(e)).map((t) => ({
5639
+ }, Xl = (e, t) => e.cache?.scope === "global" ? (e.source === void 0 ? [] : Array.isArray(e.source) ? e.source : [e.source]).filter((e) => t.has(e)).map((t) => ({
5625
5640
  query: e.name,
5626
5641
  table: t
5627
- })) : [], Xl = (e) => {
5642
+ })) : [], Zl = (e) => {
5628
5643
  if (e.length !== 0) return `A cached query shares one entry across tenants:\n${e.map((e) => ` • query '${e.query}' caches scope:'global' while reading '${e.table}', a tenant()-scoped table`).join("\n")}\n\nscope:'global' stores ONE entry for every caller. On a tenant-scoped table the\nrows depend on who asked, so the first caller's rows are served to the next one.\n\nUse scope:'tenant' — one entry per org, none shared across orgs. Use 'subject'\nif the result also depends on WHICH person is asking, and 'global' only for data\nthat depends on neither.`;
5629
- }, Zl = class extends y.TaggedError()("CircuitOpen", {
5644
+ }, Ql = (e, t) => {
5645
+ let n, r = 0;
5646
+ for (let i of t) {
5647
+ let t = 0;
5648
+ for (; t < e.length && t < i.length && e[t] === i[t];) t++;
5649
+ let a = 0;
5650
+ for (; a < e.length - t && a < i.length - t && e[e.length - 1 - a] === i[i.length - 1 - a];) a++;
5651
+ let o = (t + a) / Math.max(e.length, i.length);
5652
+ o > r && o >= .6 && (r = o, n = i);
5653
+ }
5654
+ return n;
5655
+ }, $l = (e, t) => {
5656
+ if (t.size === 0) return [];
5657
+ let n = [];
5658
+ for (let r of e) {
5659
+ if (r.source === void 0) continue;
5660
+ let e = typeof r.source == "string" ? [r.source] : r.source;
5661
+ for (let i of e) t.has(i) || n.push({
5662
+ procedure: r.name,
5663
+ source: i,
5664
+ didYouMean: Ql(i, t)
5665
+ });
5666
+ }
5667
+ return n;
5668
+ }, eu = (e) => {
5669
+ if (e.length === 0) return;
5670
+ let t = e.map((e) => ` ${e.procedure}: source '${e.source}' matches no declared table` + (e.didYouMean === void 0 ? "" : ` — did you mean '${e.didYouMean}'?`));
5671
+ return `${e.length} reactive source(s) name a table that does not exist:\n${t.join("\n")}\n
5672
+ These queries are NOT broken. They serve their first snapshot and then never
5673
+ update again, which is indistinguishable from "nothing has changed" — so the
5674
+ symptom is silence, and silence is what this surface exists to eliminate.
5675
+ A \`source:\` is a STRING, so \`tsc\` cannot see a stale one and a rename leaves it
5676
+ behind quietly.`;
5677
+ }, tu = (e) => e.op === "update" && (e.old?.deletedAt ?? null) === null && (e.new?.deletedAt ?? null) !== null, nu = (e, t) => {
5678
+ let n = tu(t);
5679
+ return t.op !== "delete" && !n ? [] : e.filter((e) => e.targetTable === t.table && e.policy !== "keep" && (!n || e.onSoftDelete));
5680
+ }, ru = async (e, t, n) => {
5681
+ let r = nu(t, n);
5682
+ if (r.length === 0) return [];
5683
+ let i = [];
5684
+ for (let t of r) {
5685
+ let r = await e.query({
5686
+ table: t.table,
5687
+ predicate: {
5688
+ kind: "eq",
5689
+ column: t.column,
5690
+ value: n.rowId
5691
+ },
5692
+ order: void 0,
5693
+ take: void 0,
5694
+ skip: void 0,
5695
+ projection: void 0
5696
+ }), a = n.tenantId === null || n.tenantId === void 0 ? r : r.filter((e) => e.tenantId === n.tenantId);
5697
+ for (let n of a) {
5698
+ let r = String(n.id);
5699
+ t.policy === "delete" ? await e.delete(t.table, r) : await e.update(t.table, r, { [t.column]: null });
5700
+ }
5701
+ i.push({
5702
+ rule: t,
5703
+ affected: a.length
5704
+ });
5705
+ }
5706
+ return i;
5707
+ }, iu = (e, t, n) => {
5708
+ let r = [];
5709
+ for (let i of e) for (let [e, a] of Object.entries(i.columns)) {
5710
+ let o = t(a);
5711
+ if (o === void 0) continue;
5712
+ let s;
5713
+ try {
5714
+ s = o.target()?.name;
5715
+ } catch {
5716
+ s = void 0;
5717
+ }
5718
+ if (s === void 0 || !n.has(s)) throw Error(`pluginRef: ${i.name}.${e} points at ${s ?? "an unresolvable table"}, which no installed plugin registers. A declared orphan rule against an absent table would look enforced and never fire — install the plugin that owns it, or drop the column.`);
5719
+ r.push({
5720
+ table: i.name,
5721
+ column: e,
5722
+ targetTable: s,
5723
+ policy: o.orphanPolicy,
5724
+ onSoftDelete: o.onSoftDelete
5725
+ });
5726
+ }
5727
+ return r.filter((e) => e.policy !== "keep");
5728
+ }, au = class extends y.TaggedError()("CircuitOpen", {
5630
5729
  name: y.String,
5631
5730
  retryAfterMs: y.Number
5632
- }) {}, Ql = {
5731
+ }) {}, ou = {
5633
5732
  tag: "closed",
5634
5733
  failureCount: 0,
5635
5734
  halfOpenSuccesses: 0,
5636
5735
  openedAt: 0
5637
- }, $l = { make: (n) => o.gen(function* () {
5638
- let r = n.name ?? "circuit", i = a.toMillis(a.decode(n.resetTimeout)), s = n.halfOpenSuccessThreshold ?? 1, c = n.isFailure ?? (() => !0), l = yield* _.make(Ql), u = o.gen(function* () {
5736
+ }, su = { make: (n) => o.gen(function* () {
5737
+ let r = n.name ?? "circuit", i = a.toMillis(a.decode(n.resetTimeout)), s = n.halfOpenSuccessThreshold ?? 1, c = n.isFailure ?? (() => !0), l = yield* _.make(ou), u = o.gen(function* () {
5639
5738
  let e = yield* _.get(l);
5640
5739
  if (e.tag === "half-open") {
5641
5740
  let t = e.halfOpenSuccesses + 1;
5642
- yield* _.set(l, t >= s ? Ql : {
5741
+ yield* _.set(l, t >= s ? ou : {
5643
5742
  ...e,
5644
5743
  halfOpenSuccesses: t
5645
5744
  });
5646
5745
  return;
5647
5746
  }
5648
- e.failureCount !== 0 && (yield* _.set(l, Ql));
5747
+ e.failureCount !== 0 && (yield* _.set(l, ou));
5649
5748
  }), d = o.gen(function* () {
5650
5749
  let e = yield* t.currentTimeMillis, r = yield* _.get(l);
5651
5750
  if (r.tag === "half-open" || r.tag === "open") {
@@ -5683,7 +5782,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5683
5782
  if (e.isInterruptedOnly(t)) return o.void;
5684
5783
  let n = e.failureOption(t), r = n._tag === "Some" ? n.value : void 0;
5685
5784
  return c(r) ? d : o.void;
5686
- })) : yield* o.fail(new Zl({
5785
+ })) : yield* o.fail(new au({
5687
5786
  name: r,
5688
5787
  retryAfterMs: n
5689
5788
  }));
@@ -5692,15 +5791,15 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5692
5791
  value: _.get(l).pipe(o.map((e) => e.tag)),
5693
5792
  enumerable: !0
5694
5793
  }), Object.defineProperty(m, "reset", {
5695
- value: _.set(l, Ql),
5794
+ value: _.set(l, ou),
5696
5795
  enumerable: !0
5697
5796
  }), m;
5698
- }) }, eu, tu = (e) => {
5699
- eu = e;
5700
- }, nu = () => {
5701
- eu = void 0;
5702
- }, ru = () => eu, iu = async (e, t = {}) => {
5703
- let n = t.scopes === void 0 ? _t(t.id ?? "system") : _t(t.id ?? "system", t.scopes), r = t.store ?? eu?.dataStore, i = t.schemaRegistry ?? eu?.schemaRegistry, a = t.dialect ?? eu?.dialect;
5797
+ }) }, cu, lu = (e) => {
5798
+ cu = e;
5799
+ }, uu = () => {
5800
+ cu = void 0;
5801
+ }, du = () => cu, fu = async (e, t = {}) => {
5802
+ let n = t.scopes === void 0 ? vt(t.id ?? "system") : vt(t.id ?? "system", t.scopes), r = t.store ?? cu?.dataStore, i = t.schemaRegistry ?? cu?.schemaRegistry, a = t.dialect ?? cu?.dialect;
5704
5803
  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.");
5705
5804
  return e({
5706
5805
  subject: n,
@@ -5710,7 +5809,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5710
5809
  ...a === void 0 ? {} : { dialect: a }
5711
5810
  })
5712
5811
  });
5713
- }, au = (e) => {
5812
+ }, pu = (e) => {
5714
5813
  let { currentRegion: t, replicaRegions: n, inner: r } = e, i = (e) => {
5715
5814
  if (t === void 0) return {
5716
5815
  sameRegion: [],
@@ -5738,7 +5837,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5738
5837
  return r.loadSnapshot();
5739
5838
  }
5740
5839
  };
5741
- }, ou = (e = process.env) => {
5840
+ }, mu = (e = process.env) => {
5742
5841
  for (let t of [
5743
5842
  "VOLTRO_REGION",
5744
5843
  "AWS_REGION",
@@ -5750,7 +5849,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5750
5849
  let n = e[t];
5751
5850
  if (typeof n == "string" && n.length > 0) return n;
5752
5851
  }
5753
- }, su = () => {
5852
+ }, hu = () => {
5754
5853
  let e = {
5755
5854
  primary: 0,
5756
5855
  lagByReplica: /* @__PURE__ */ new Map()
@@ -5775,27 +5874,27 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5775
5874
  e.lagByReplica.set(t, n);
5776
5875
  }
5777
5876
  };
5778
- }, cu = Symbol.for("@voltro/ScheduleDefinition"), lu = (e) => typeof e == "object" && !!e && cu in e, uu = 30 * 6e4, du = (e) => {
5877
+ }, gu = Symbol.for("@voltro/ScheduleDefinition"), _u = (e) => typeof e == "object" && !!e && gu in e, vu = 30 * 6e4, yu = (e) => {
5779
5878
  let t = r.parse(e.cron, e.timezone);
5780
5879
  if (s.isLeft(t)) throw Error(`defineSchedule("${e.name}"): invalid cron expression "${e.cron}" (tz="${e.timezone}") — ${String(t.left)}`);
5781
- if (!e.timezone || e.timezone.trim() === "") throw Error(`defineSchedule("${e.name}"): timezone is required (e.g. "UTC", "Europe/Berlin")`);
5880
+ if (!e.timezone || e.timezone.trim() === "") throw Error(`defineSchedule("${e.name}"): timezone is required (e.g. "UTC", "Europe/Berlin").\nThe field is non-optional in \`ScheduleDefinition\`, so an ABSENT one is a tsc error and never reaches here. Arriving at this message means the value was present and EMPTY — almost always \`process.env.TZ ?? ''\` or a config lookup that missed. A reporter lost a crashloop to it, so the distinction is worth stating: this is not a check the type could have made for you.`);
5782
5881
  if (e.handler === void 0 && e.workflow === void 0) throw Error(`defineSchedule("${e.name}"): define either handler or workflow`);
5783
5882
  return {
5784
5883
  ...e,
5785
5884
  onOverlap: e.onOverlap ?? "skip",
5786
5885
  backfill: e.backfill ?? "skip",
5787
- maxRuntimeMs: e.maxRuntimeMs ?? uu,
5788
- [cu]: !0
5886
+ maxRuntimeMs: e.maxRuntimeMs ?? vu,
5887
+ [gu]: !0
5789
5888
  };
5790
- }, fu = (e) => r.unsafeParse(e.cron, e.timezone), pu = (e, t = /* @__PURE__ */ new Date()) => r.next(fu(e), t), Z = "_voltro_wakeups", mu = (e) => `${e.tenantId}:${e.kind}:${e.refId}`, hu = (e) => ({
5889
+ }, bu = (e) => r.unsafeParse(e.cron, e.timezone), xu = (e, t = /* @__PURE__ */ new Date()) => r.next(bu(e), t), Z = "_voltro_wakeups", Su = (e) => `${e.tenantId}:${e.kind}:${e.refId}`, Cu = (e) => ({
5791
5890
  tenantId: String(e.tenantId),
5792
5891
  kind: String(e.kind),
5793
5892
  refId: String(e.refId),
5794
5893
  wakeAt: e.wakeAt instanceof Date ? e.wakeAt : new Date(String(e.wakeAt)),
5795
5894
  status: e.status === "fired" ? "fired" : "pending"
5796
- }), gu = async (e, t) => {
5895
+ }), wu = async (e, t) => {
5797
5896
  await e.upsert(Z, {
5798
- id: mu(t),
5897
+ id: Su(t),
5799
5898
  tenantId: t.tenantId,
5800
5899
  kind: t.kind,
5801
5900
  refId: t.refId,
@@ -5805,7 +5904,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5805
5904
  conflictColumns: ["id"],
5806
5905
  update: ["wakeAt", "status"]
5807
5906
  });
5808
- }, _u = async (e, t) => e.delete(Z, mu(t)), vu = async (e, t) => await e.update(Z, mu(t), { status: "fired" }) !== null, yu = (e, t) => ({ and: [{
5907
+ }, Tu = async (e, t) => e.delete(Z, Su(t)), Eu = async (e, t) => await e.update(Z, Su(t), { status: "fired" }) !== null, Du = (e, t) => ({ and: [{
5809
5908
  column: "id",
5810
5909
  op: "eq",
5811
5910
  value: e
@@ -5813,16 +5912,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5813
5912
  column: "status",
5814
5913
  op: "eq",
5815
5914
  value: t
5816
- }] }), bu = async (e, t) => await e.updateMany(Z, { status: "fired" }, { where: yu(mu(t), "pending") }) > 0, xu = async (e, t) => {
5817
- await e.updateMany(Z, { status: "pending" }, { where: yu(mu(t), "fired") });
5818
- }, Su = {
5915
+ }] }), Ou = async (e, t) => await e.updateMany(Z, { status: "fired" }, { where: Du(Su(t), "pending") }) > 0, ku = async (e, t) => {
5916
+ await e.updateMany(Z, { status: "pending" }, { where: Du(Su(t), "fired") });
5917
+ }, Au = {
5819
5918
  column: "status",
5820
5919
  op: "eq",
5821
5920
  value: "pending"
5822
- }, Cu = async (e, t) => {
5921
+ }, ju = async (e, t) => {
5823
5922
  let n = {
5824
5923
  table: Z,
5825
- predicate: Su,
5924
+ predicate: Au,
5826
5925
  order: [{
5827
5926
  column: "wakeAt",
5828
5927
  direction: "asc"
@@ -5831,18 +5930,18 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5831
5930
  skip: void 0,
5832
5931
  projection: void 0
5833
5932
  };
5834
- return (await e.query(n)).map(hu);
5835
- }, wu = async (e, t, n = 500) => {
5836
- let r = await Cu(e, n), i = t.getTime();
5933
+ return (await e.query(n)).map(Cu);
5934
+ }, Mu = async (e, t, n = 500) => {
5935
+ let r = await ju(e, n), i = t.getTime();
5837
5936
  return r.filter((e) => e.wakeAt.getTime() <= i);
5838
- }, Tu = async (e) => (await Cu(e, 1))[0] ?? null, Eu = {
5937
+ }, Nu = async (e) => (await ju(e, 1))[0] ?? null, Pu = {
5839
5938
  column: "status",
5840
5939
  op: "eq",
5841
5940
  value: "fired"
5842
- }, Du = async (e, t = {}) => {
5941
+ }, Fu = async (e, t = {}) => {
5843
5942
  let n = {
5844
5943
  table: Z,
5845
- predicate: Eu,
5944
+ predicate: Pu,
5846
5945
  order: [{
5847
5946
  column: "wakeAt",
5848
5947
  direction: "asc"
@@ -5853,12 +5952,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5853
5952
  }, r = await e.query(n), i = t.firedOlderThan?.getTime(), a = 0;
5854
5953
  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++;
5855
5954
  return a;
5856
- }, Ou = Ro, ku = "default", Au = {
5955
+ }, Iu = zo, Lu = "default", Ru = {
5857
5956
  kind: "single",
5858
5957
  tryClaim: async () => !0
5859
- }, ju = "_voltro_schedule_claims", Mu = (e, t, n) => {
5958
+ }, zu = "_voltro_schedule_claims", Bu = (e, t, n) => {
5860
5959
  let r = async (t) => (await e.query({
5861
- table: ju,
5960
+ table: zu,
5862
5961
  order: [],
5863
5962
  predicate: void 0,
5864
5963
  projection: ["id"],
@@ -5873,7 +5972,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5873
5972
  if (await r(s)) return !1;
5874
5973
  } catch {}
5875
5974
  try {
5876
- return await e.insert(ju, {
5975
+ return await e.insert(zu, {
5877
5976
  id: s,
5878
5977
  scheduleName: i,
5879
5978
  bucket: o,
@@ -5891,12 +5990,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5891
5990
  }
5892
5991
  }
5893
5992
  };
5894
- }, Nu = "_voltro_schedule_runs", Pu = async (e, t) => {
5993
+ }, Vu = "_voltro_schedule_runs", Hu = async (e, t) => {
5895
5994
  let { store: n, coordinator: i, buildContext: a, replicaId: o, log: s, onRunEvent: c, interceptFire: l } = t, u = t.dormancy === "sleep", d = t.dormancyTenantId ?? "default", f = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Set(), m = /* @__PURE__ */ new Map(), h = !1, g = new Map(e.map((e) => [e.name, e])), _ = (e, t) => {
5896
- c?.(e, Iu(t));
5995
+ c?.(e, Wu(t));
5897
5996
  }, v = async (e, t, r, i, a, c) => {
5898
5997
  try {
5899
- let s = `sr_${Re()}`, l = await n.insert(Nu, {
5998
+ let s = `sr_${Re()}`, l = await n.insert(Vu, {
5900
5999
  id: s,
5901
6000
  name: e.name,
5902
6001
  status: i,
@@ -5921,7 +6020,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5921
6020
  }
5922
6021
  }, y = async (e, t) => {
5923
6022
  try {
5924
- let r = await n.update(Nu, e, t);
6023
+ let r = await n.update(Vu, e, t);
5925
6024
  r && _("update", r);
5926
6025
  } catch (t) {
5927
6026
  s.warn("schedule: failed to record run finish", {
@@ -5932,7 +6031,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5932
6031
  }, b = async (e) => {
5933
6032
  try {
5934
6033
  let t = await n.query({
5935
- table: Nu,
6034
+ table: Vu,
5936
6035
  predicate: {
5937
6036
  _tag: "leaf",
5938
6037
  column: "status",
@@ -5967,7 +6066,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5967
6066
  scheduleName: e.name,
5968
6067
  trigger: n,
5969
6068
  runId: o,
5970
- subject: Ou
6069
+ subject: Iu
5971
6070
  })
5972
6071
  };
5973
6072
  try {
@@ -5978,7 +6077,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
5978
6077
  let n = typeof e.workflow.payload == "function" ? await e.workflow.payload(f) : e.workflow.payload ?? {};
5979
6078
  await t.start(e.workflow.name, n);
5980
6079
  }
5981
- e.handler !== void 0 && await Xt(e.handler(f));
6080
+ e.handler !== void 0 && await Qt(e.handler(f));
5982
6081
  }, a = l ? l(r, {
5983
6082
  name: e.name,
5984
6083
  scheduledAt: t,
@@ -6000,10 +6099,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6000
6099
  completedAtSec: Date.now() / 1e3
6001
6100
  });
6002
6101
  } catch (t) {
6003
- let n = Q(t).includes("exceeded maxRuntimeMs"), r = bn(t).dbMessage, i = typeof r == "string" && r !== "" ? `${Q(t)} — ${r}` : Q(t);
6102
+ let n = Q(t).includes("exceeded maxRuntimeMs"), r = xn(t).dbMessage, i = typeof r == "string" && r !== "" ? `${Q(t)} — ${r}` : Q(t);
6004
6103
  o && await y(o, {
6005
6104
  status: "failed",
6006
- errorTag: n ? "timeout" : Fu(t),
6105
+ errorTag: n ? "timeout" : Uu(t),
6007
6106
  errorMessage: i,
6008
6107
  completedAt: /* @__PURE__ */ new Date(),
6009
6108
  durationMs: Date.now() - c
@@ -6012,13 +6111,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6012
6111
  name: e.name,
6013
6112
  reason: Q(t),
6014
6113
  timeout: n,
6015
- ...bn(t)
6114
+ ...xn(t)
6016
6115
  };
6017
6116
  s.error ? s.error("schedule: handler failed", a) : s.warn("schedule: handler failed", a), hr({
6018
6117
  name: e.name,
6019
6118
  status: "failed",
6020
6119
  durationMs: Date.now() - c
6021
- }), mt({
6120
+ }), ht({
6022
6121
  error: t,
6023
6122
  source: "schedule",
6024
6123
  name: e.name,
@@ -6067,8 +6166,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6067
6166
  }
6068
6167
  }, w = async (e) => {
6069
6168
  try {
6070
- let t = r.next(fu(e), /* @__PURE__ */ new Date());
6071
- await gu(n, {
6169
+ let t = r.next(bu(e), /* @__PURE__ */ new Date());
6170
+ await wu(n, {
6072
6171
  tenantId: d,
6073
6172
  kind: "schedule",
6074
6173
  refId: e.name,
@@ -6082,7 +6181,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6082
6181
  }
6083
6182
  }, T = 2147483647, E = (e) => {
6084
6183
  if (h) return;
6085
- let n = fu(e), i = r.next(n, /* @__PURE__ */ new Date()), a = () => {
6184
+ let n = bu(e), i = r.next(n, /* @__PURE__ */ new Date()), a = () => {
6086
6185
  if (h) return;
6087
6186
  let n = i.getTime() - Date.now();
6088
6187
  if (n > T) {
@@ -6104,7 +6203,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6104
6203
  let i;
6105
6204
  try {
6106
6205
  let t = (await n.query({
6107
- table: Nu,
6206
+ table: Vu,
6108
6207
  order: [{
6109
6208
  column: "scheduledAt",
6110
6209
  direction: "desc"
@@ -6123,7 +6222,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6123
6222
  return;
6124
6223
  }
6125
6224
  if (!i) return;
6126
- let a = fu(e), o = [], c = r.next(a, i), l = Date.now();
6225
+ let a = bu(e), o = [], c = r.next(a, i), l = Date.now();
6127
6226
  for (; c.getTime() < l && o.length < 1e3;) o.push(c), c = r.next(a, c);
6128
6227
  if (o.length !== 0) if (s.info("schedule: backfill", {
6129
6228
  name: e.name,
@@ -6168,11 +6267,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6168
6267
  f.clear(), s.info("scheduler: stopped");
6169
6268
  }
6170
6269
  };
6171
- }, Q = (e) => e?.message ?? String(e), Fu = (e) => e && typeof e == "object" && "_tag" in e ? String(e._tag) : null, Iu = (e) => {
6270
+ }, Q = (e) => e?.message ?? String(e), Uu = (e) => e && typeof e == "object" && "_tag" in e ? String(e._tag) : null, Wu = (e) => {
6172
6271
  let t = {};
6173
6272
  for (let [n, r] of Object.entries(e)) t[n] = r instanceof Date ? r.toISOString() : r;
6174
6273
  return t;
6175
- }, Lu = (e, t, n, r) => {
6274
+ }, Gu = (e, t, n, r) => {
6176
6275
  let i = !1, a, o = async () => {
6177
6276
  if (i) return;
6178
6277
  let a = new Date(Math.floor(Date.now() / t) * t), o = !1;
@@ -6202,7 +6301,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6202
6301
  i || (i = !0, a && clearInterval(a), a = void 0);
6203
6302
  }
6204
6303
  };
6205
- }, Ru = (e) => (t, n, r) => Lu(t, n, r, e), zu = F("_voltro_schedule_runs", {
6304
+ }, Ku = (e) => (t, n, r) => Gu(t, n, r, e), qu = F("_voltro_schedule_runs", {
6206
6305
  id: M({ prefix: "schrun" }),
6207
6306
  name: I(),
6208
6307
  status: I().oneOf([
@@ -6232,13 +6331,13 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6232
6331
  ]).nullable(),
6233
6332
  replicaId: I().nullable(),
6234
6333
  result: P().nullable()
6235
- }).index(["name", "scheduledAt"]).index(["status"]), Bu = F("_voltro_schedule_claims", {
6334
+ }).index(["name", "scheduledAt"]).index(["status"]), Ju = F("_voltro_schedule_claims", {
6236
6335
  id: M({ prefix: "schclaim" }),
6237
6336
  scheduleName: I(),
6238
6337
  bucket: I(),
6239
6338
  claimedBy: I(),
6240
6339
  claimedAt: L()
6241
- }).index(["scheduleName", "bucket"]).index(["claimedAt"]), Vu = F("_voltro_traces", {
6340
+ }).index(["scheduleName", "bucket"]).index(["claimedAt"]), Yu = F("_voltro_traces", {
6242
6341
  id: M({ prefix: "span" }),
6243
6342
  traceId: I(),
6244
6343
  spanId: I(),
@@ -6262,7 +6361,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6262
6361
  durationMs: N(),
6263
6362
  attributes: P().nullable(),
6264
6363
  events: P().nullable()
6265
- }).index(["traceId", "startedAt"]).index(["startedAt"]).index(["status"]), Hu = F("_voltro_undo_log", {
6364
+ }).index(["traceId", "startedAt"]).index(["startedAt"]).index(["status"]), Xu = F("_voltro_undo_log", {
6266
6365
  id: M({ prefix: "undo" }),
6267
6366
  tag: I(),
6268
6367
  label: I().nullable(),
@@ -6273,25 +6372,25 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6273
6372
  crossesAction: E().default(!1),
6274
6373
  undone: E().default(!1),
6275
6374
  createdAt: L().default("now")
6276
- }).index(["subjectId", "createdAt"]), Uu = (e = process.env) => {
6375
+ }).index(["subjectId", "createdAt"]), Zu = (e = process.env) => {
6277
6376
  let t = (e.VOLTRO_UNDO ?? "").toLowerCase();
6278
6377
  return t === "on" || t === "1" || t === "true" ? !0 : t === "off" || t === "0" || t === "false" ? !1 : e.NODE_ENV !== "production";
6279
- }, Wu = (e) => e.startsWith("_voltro"), Gu = async (e, t, n) => (await e.query({
6378
+ }, Qu = (e) => e.startsWith("_voltro"), $u = async (e, t, n) => (await e.query({
6280
6379
  table: t,
6281
6380
  predicate: O("id", n),
6282
6381
  order: []
6283
- }))[0] ?? null, Ku = (e, t) => new Proxy(e, { get(e, n, r) {
6382
+ }))[0] ?? null, ed = (e, t) => new Proxy(e, { get(e, n, r) {
6284
6383
  if (n === "insert") return async (n, r) => {
6285
6384
  let i = await e.insert(n, r);
6286
- return Wu(n) || t({
6385
+ return Qu(n) || t({
6287
6386
  table: n,
6288
6387
  op: "insert",
6289
6388
  next: i
6290
6389
  }), i;
6291
6390
  };
6292
6391
  if (n === "update") return async (n, r, i) => {
6293
- let a = Wu(n) ? null : await Gu(e, n, r), o = await e.update(n, r, i);
6294
- return Wu(n) || t({
6392
+ let a = Qu(n) ? null : await $u(e, n, r), o = await e.update(n, r, i);
6393
+ return Qu(n) || t({
6295
6394
  table: n,
6296
6395
  op: "update",
6297
6396
  id: r,
@@ -6300,8 +6399,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6300
6399
  }), o;
6301
6400
  };
6302
6401
  if (n === "delete") return async (n, r) => {
6303
- let i = Wu(n) ? null : await Gu(e, n, r), a = await e.delete(n, r);
6304
- return !Wu(n) && a && t({
6402
+ let i = Qu(n) ? null : await $u(e, n, r), a = await e.delete(n, r);
6403
+ return !Qu(n) && a && t({
6305
6404
  table: n,
6306
6405
  op: "delete",
6307
6406
  id: r,
@@ -6310,10 +6409,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6310
6409
  };
6311
6410
  let i = Reflect.get(e, n, r);
6312
6411
  return typeof i == "function" ? i.bind(e) : i;
6313
- } }), qu = (e) => {
6412
+ } }), td = (e) => {
6314
6413
  let t = [];
6315
6414
  return {
6316
- tx: Ku(e, (e) => t.push(e)),
6415
+ tx: ed(e, (e) => t.push(e)),
6317
6416
  persist: async (e, n) => {
6318
6417
  if (t.length === 0 || n.tag.startsWith("__voltro")) return;
6319
6418
  let r = n.subject;
@@ -6329,14 +6428,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6329
6428
  });
6330
6429
  }
6331
6430
  };
6332
- }, Ju = (e) => {
6431
+ }, nd = (e) => {
6333
6432
  if (e.id !== void 0) return e.id;
6334
6433
  let t = e.next?.id;
6335
6434
  if (typeof t == "string") return t;
6336
6435
  let n = e.prev?.id;
6337
6436
  return typeof n == "string" ? n : void 0;
6338
- }, Yu = (e) => {
6339
- let t = Ju(e);
6437
+ }, rd = (e) => {
6438
+ let t = nd(e);
6340
6439
  switch (e.op) {
6341
6440
  case "insert": return t === void 0 ? null : {
6342
6441
  table: e.table,
@@ -6360,28 +6459,28 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6360
6459
  row: e.prev
6361
6460
  };
6362
6461
  }
6363
- }, Xu = (e) => {
6364
- if (e.crossesAction) throw new Zu(e.invocationId, "action");
6462
+ }, id = (e) => {
6463
+ if (e.crossesAction) throw new ad(e.invocationId, "action");
6365
6464
  let t = [];
6366
6465
  for (let n = e.changes.length - 1; n >= 0; --n) {
6367
- let r = Yu(e.changes[n]);
6466
+ let r = rd(e.changes[n]);
6368
6467
  r !== null && t.push(r);
6369
6468
  }
6370
6469
  return t;
6371
- }, Zu = class extends Error {
6470
+ }, ad = class extends Error {
6372
6471
  invocationId;
6373
6472
  boundary;
6374
6473
  _tag = "UndoBoundaryError";
6375
6474
  constructor(e, t) {
6376
6475
  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";
6377
6476
  }
6378
- }, Qu = (e, t, n = ["updatedAt", "updatedBy"]) => {
6477
+ }, od = (e, t, n = ["updatedAt", "updatedBy"]) => {
6379
6478
  if (t == null) return e == null;
6380
6479
  if (e == null) return !1;
6381
6480
  let r = new Set(n);
6382
6481
  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;
6383
6482
  return !0;
6384
- }, $u = class {
6483
+ }, sd = class {
6385
6484
  capacity;
6386
6485
  done = [];
6387
6486
  undone = [];
@@ -6417,7 +6516,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6417
6516
  redo: [...this.undone]
6418
6517
  };
6419
6518
  }
6420
- }, ed = (e, t = /* @__PURE__ */ new Set()) => e.op === "insert" ? {
6519
+ }, cd = (e, t = /* @__PURE__ */ new Set()) => e.op === "insert" ? {
6421
6520
  table: e.table,
6422
6521
  op: "insert",
6423
6522
  next: e.new ?? null
@@ -6434,7 +6533,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6434
6533
  table: e.table,
6435
6534
  op: "delete",
6436
6535
  prev: e.old ?? null
6437
- }, td = async (e, t) => {
6536
+ }, ld = async (e, t) => {
6438
6537
  switch (t.op) {
6439
6538
  case "delete":
6440
6539
  await e.delete(t.table, t.id);
@@ -6452,21 +6551,21 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6452
6551
  await e.insert(t.table, t.row);
6453
6552
  return;
6454
6553
  }
6455
- }, nd = async (e, t) => {
6456
- for (let n of t) await td(e, n);
6457
- }, rd = (e) => e.request?.subject?.id ?? null, id = (e) => e === !0 || e === 1, ad = async (e, t, n) => (await e.query({
6554
+ }, ud = async (e, t) => {
6555
+ for (let n of t) await ld(e, n);
6556
+ }, dd = (e) => e.request?.subject?.id ?? null, fd = (e) => e === !0 || e === 1, pd = async (e, t, n) => (await e.query({
6458
6557
  table: t,
6459
6558
  predicate: O("id", n),
6460
6559
  order: []
6461
- }))[0] ?? null, od = (e) => {
6560
+ }))[0] ?? null, md = (e) => {
6462
6561
  try {
6463
6562
  let t = JSON.parse(String(e ?? "[]"));
6464
6563
  return Array.isArray(t) ? t : [];
6465
6564
  } catch {
6466
6565
  return [];
6467
6566
  }
6468
- }, sd = (e) => e.id ?? e.next?.id ?? e.prev?.id, cd = async (e, t) => {
6469
- let n = rd(t);
6567
+ }, hd = (e) => e.id ?? e.next?.id ?? e.prev?.id, gd = async (e, t) => {
6568
+ let n = dd(t);
6470
6569
  return [...await t.store.query({
6471
6570
  table: "_voltro_undo_log",
6472
6571
  predicate: O("subjectId", n),
@@ -6475,68 +6574,68 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6475
6574
  id: String(e.id),
6476
6575
  tag: String(e.tag ?? ""),
6477
6576
  label: e.label ?? null,
6478
- undone: id(e.undone),
6479
- crossesAction: id(e.crossesAction),
6577
+ undone: fd(e.undone),
6578
+ crossesAction: fd(e.crossesAction),
6480
6579
  createdAt: String(e.createdAt ?? "")
6481
6580
  }));
6482
- }, ld = async (e, t) => {
6483
- let n = await ad(t.store, "_voltro_undo_log", e.invocationId);
6484
- if (!n) throw new nt({ invocationId: e.invocationId });
6485
- if ((n.subjectId ?? null) !== rd(t)) throw new tt({ invocationId: e.invocationId });
6581
+ }, _d = async (e, t) => {
6582
+ let n = await pd(t.store, "_voltro_undo_log", e.invocationId);
6583
+ if (!n) throw new rt({ invocationId: e.invocationId });
6584
+ if ((n.subjectId ?? null) !== dd(t)) throw new nt({ invocationId: e.invocationId });
6486
6585
  return n;
6487
- }, ud = async (e, t) => {
6488
- let n = await ld(e, t);
6489
- if (id(n.undone)) return { ok: !0 };
6490
- if (id(n.crossesAction)) throw new et({
6586
+ }, vd = async (e, t) => {
6587
+ let n = await _d(e, t);
6588
+ if (fd(n.undone)) return { ok: !0 };
6589
+ if (fd(n.crossesAction)) throw new tt({
6491
6590
  invocationId: e.invocationId,
6492
6591
  reason: "action"
6493
6592
  });
6494
- let r = od(n.changes);
6593
+ let r = md(n.changes);
6495
6594
  for (let n of r) {
6496
- let r = sd(n);
6497
- if (r !== void 0 && !Qu(await ad(t.store, n.table, r), n.next ?? null)) throw new et({
6595
+ let r = hd(n);
6596
+ if (r !== void 0 && !od(await pd(t.store, n.table, r), n.next ?? null)) throw new tt({
6498
6597
  invocationId: e.invocationId,
6499
6598
  reason: "conflict"
6500
6599
  });
6501
6600
  }
6502
6601
  let i = {
6503
6602
  invocationId: e.invocationId,
6504
- subject: rd(t),
6603
+ subject: dd(t),
6505
6604
  changes: r,
6506
6605
  crossesAction: !1
6507
6606
  };
6508
- return await nd(t.store, Xu(i)), await t.store.update("_voltro_undo_log", e.invocationId, { undone: !0 }), { ok: !0 };
6509
- }, dd = async (e, t) => {
6510
- let n = await ld(e, t);
6511
- if (!id(n.undone)) return { ok: !0 };
6512
- for (let e of od(n.changes)) {
6513
- let n = sd(e);
6607
+ return await ud(t.store, id(i)), await t.store.update("_voltro_undo_log", e.invocationId, { undone: !0 }), { ok: !0 };
6608
+ }, yd = async (e, t) => {
6609
+ let n = await _d(e, t);
6610
+ if (!fd(n.undone)) return { ok: !0 };
6611
+ for (let e of md(n.changes)) {
6612
+ let n = hd(e);
6514
6613
  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);
6515
6614
  }
6516
6615
  return await t.store.update("_voltro_undo_log", e.invocationId, { undone: !1 }), { ok: !0 };
6517
- }, fd = (e = process.env) => {
6616
+ }, bd = (e = process.env) => {
6518
6617
  let t = (e.VOLTRO_TIMELINE ?? "").toLowerCase();
6519
6618
  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";
6520
- }, pd = /pass(word)?|secret|token|api[_-]?key|authorization|cookie|ssn|credit[_-]?card|card[_-]?number|cvv|encrypted/i, md = "«redacted»", hd = (e) => {
6619
+ }, xd = /pass(word)?|secret|token|api[_-]?key|authorization|cookie|ssn|credit[_-]?card|card[_-]?number|cvv|encrypted/i, Sd = "«redacted»", Cd = (e) => {
6521
6620
  if (e == null) return null;
6522
6621
  let t = {};
6523
- for (let [n, r] of Object.entries(e)) t[n] = pd.test(n) ? md : r;
6622
+ for (let [n, r] of Object.entries(e)) t[n] = xd.test(n) ? Sd : r;
6524
6623
  return t;
6525
- }, gd = (e) => {
6624
+ }, wd = (e) => {
6526
6625
  let t = e?.id;
6527
6626
  return typeof t == "string" ? t : void 0;
6528
- }, _d = (e, t) => {
6627
+ }, Td = (e, t) => {
6529
6628
  if (t.op === "insert") {
6530
- let n = gd(t.new);
6629
+ let n = wd(t.new);
6531
6630
  return n === void 0 ? e : e.filter((e) => e.id !== n);
6532
6631
  }
6533
6632
  if (t.op === "update") {
6534
6633
  if (t.old == null) return e;
6535
- let n = gd(t.new) ?? gd(t.old);
6634
+ let n = wd(t.new) ?? wd(t.old);
6536
6635
  return e.map((e) => e.id === n ? t.old : e);
6537
6636
  }
6538
6637
  return t.old == null ? e : [...e, t.old];
6539
- }, vd = class {
6638
+ }, Ed = class {
6540
6639
  mode;
6541
6640
  capacity;
6542
6641
  now;
@@ -6556,8 +6655,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6556
6655
  ts: this.now(),
6557
6656
  table: e.table,
6558
6657
  op: e.op,
6559
- old: hd(e.old),
6560
- new: hd(e.new),
6658
+ old: Cd(e.old),
6659
+ new: Cd(e.new),
6561
6660
  tenantId: n
6562
6661
  }), this.ring.length > this.capacity && this.ring.shift(), t;
6563
6662
  }
@@ -6570,23 +6669,23 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6570
6669
  }
6571
6670
  replay(e, t, n) {
6572
6671
  let r = this.ring.filter((n) => n.table === e && n.seq > t).sort((e, t) => t.seq - e.seq), i = n;
6573
- for (let e of r) i = _d(i, e);
6672
+ for (let e of r) i = Td(i, e);
6574
6673
  return i;
6575
6674
  }
6576
- }, yd, bd = () => (yd === void 0 && (yd = new vd(fd())), yd), xd = (e) => {
6577
- yd = e;
6578
- }, Sd = (e) => {
6579
- let t = bd();
6675
+ }, Dd, Od = () => (Dd === void 0 && (Dd = new Ed(bd())), Dd), kd = (e) => {
6676
+ Dd = e;
6677
+ }, Ad = (e) => {
6678
+ let t = Od();
6580
6679
  if (t.enabled) try {
6581
6680
  t.record(e);
6582
6681
  } catch {}
6583
- }, Cd = /* @__PURE__ */ new Set([
6682
+ }, jd = /* @__PURE__ */ new Set([
6584
6683
  "count",
6585
6684
  "sum",
6586
6685
  "avg",
6587
6686
  "min",
6588
6687
  "max"
6589
- ]), wd = (e) => {
6688
+ ]), Md = (e) => {
6590
6689
  if (e.joins !== void 0 && e.joins.length > 0) return {
6591
6690
  maintainable: !1,
6592
6691
  reason: "joins are not maintainable in v1"
@@ -6608,7 +6707,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6608
6707
  reason: "v1 maintains exactly one aggregation"
6609
6708
  };
6610
6709
  let t = e.aggregations[0];
6611
- return Cd.has(t.op) ? t.op !== "count" && (t.column === void 0 || t.column.length === 0) ? {
6710
+ return jd.has(t.op) ? t.op !== "count" && (t.column === void 0 || t.column.length === 0) ? {
6612
6711
  maintainable: !1,
6613
6712
  reason: `op '${t.op}' requires a column`
6614
6713
  } : {
@@ -6622,7 +6721,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6622
6721
  maintainable: !1,
6623
6722
  reason: `op '${t.op}' is not maintainable`
6624
6723
  };
6625
- }, Td = "\0", $ = (e, t) => t === void 0 || t.length === 0 ? "" : t.map((t) => JSON.stringify(e[t] ?? null)).join(Td), Ed = (e, t) => t === void 0 ? 0 : Number(e[t] ?? 0), Dd = (e, t) => {
6724
+ }, Nd = "\0", $ = (e, t) => t === void 0 || t.length === 0 ? "" : t.map((t) => JSON.stringify(e[t] ?? null)).join(Nd), Pd = (e, t) => t === void 0 ? 0 : Number(e[t] ?? 0), Fd = (e, t) => {
6626
6725
  switch (e.op) {
6627
6726
  case "count": return t.count;
6628
6727
  case "sum": return t.sum ?? 0;
@@ -6630,10 +6729,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6630
6729
  case "min":
6631
6730
  case "max": return t.count > 0 ? t.extreme ?? null : null;
6632
6731
  }
6633
- }, Od = (e, t) => {
6732
+ }, Id = (e, t) => {
6634
6733
  let n = /* @__PURE__ */ new Map();
6635
6734
  for (let r of t) {
6636
- let t = $(r, e.groupBy), i = n.get(t), a = Ed(r, e.column);
6735
+ let t = $(r, e.groupBy), i = n.get(t), a = Pd(r, e.column);
6637
6736
  if (i === void 0) n.set(t, {
6638
6737
  count: 1,
6639
6738
  ...e.op === "sum" || e.op === "avg" ? { sum: a } : {},
@@ -6649,10 +6748,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6649
6748
  }
6650
6749
  }
6651
6750
  return n;
6652
- }, kd = (e, t) => [...t.entries()].map(([t, n]) => ({
6751
+ }, Ld = (e, t) => [...t.entries()].map(([t, n]) => ({
6653
6752
  groupKey: t,
6654
- value: Dd(e, n)
6655
- })), Ad = (e, t, n) => {
6753
+ value: Fd(e, n)
6754
+ })), Rd = (e, t, n) => {
6656
6755
  let r = new Map(t), i = /* @__PURE__ */ new Set(), a = (t) => {
6657
6756
  let n = $(t, e.groupBy), a = r.get(n);
6658
6757
  if (a === void 0) return;
@@ -6661,7 +6760,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6661
6760
  r.delete(n);
6662
6761
  return;
6663
6762
  }
6664
- let s = Ed(t, e.column);
6763
+ let s = Pd(t, e.column);
6665
6764
  e.op === "min" || e.op === "max" ? (a.extreme !== void 0 && s === a.extreme && i.add(n), r.set(n, {
6666
6765
  count: o,
6667
6766
  ...a.extreme === void 0 ? {} : { extreme: a.extreme }
@@ -6670,7 +6769,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6670
6769
  ...e.op === "sum" || e.op === "avg" ? { sum: (a.sum ?? 0) - s } : {}
6671
6770
  });
6672
6771
  }, o = (t) => {
6673
- let n = $(t, e.groupBy), i = r.get(n), a = Ed(t, e.column);
6772
+ let n = $(t, e.groupBy), i = r.get(n), a = Pd(t, e.column);
6674
6773
  if (i === void 0) {
6675
6774
  r.set(n, {
6676
6775
  count: 1,
@@ -6690,15 +6789,15 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6690
6789
  state: r,
6691
6790
  rescanGroups: [...i]
6692
6791
  };
6693
- }, jd = (e, t, n, r) => {
6792
+ }, zd = (e, t, n, r) => {
6694
6793
  if (n.length === 0) return t;
6695
- let i = new Set(n), a = Od(e, r.filter((t) => i.has($(t, e.groupBy)))), o = new Map(t);
6794
+ let i = new Set(n), a = Id(e, r.filter((t) => i.has($(t, e.groupBy)))), o = new Map(t);
6696
6795
  for (let e of i) {
6697
6796
  let t = a.get(e);
6698
6797
  t === void 0 ? o.delete(e) : o.set(e, t);
6699
6798
  }
6700
6799
  return o;
6701
- }, Md = class {
6800
+ }, Bd = class {
6702
6801
  shape;
6703
6802
  state = /* @__PURE__ */ new Map();
6704
6803
  groups = /* @__PURE__ */ new Map();
@@ -6706,7 +6805,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6706
6805
  this.shape = e;
6707
6806
  }
6708
6807
  seed(e) {
6709
- this.state = Od(this.shape, e), this.groups.clear();
6808
+ this.state = Id(this.shape, e), this.groups.clear();
6710
6809
  for (let t of e) {
6711
6810
  let e = $(t, this.shape.groupBy);
6712
6811
  this.groups.has(e) || this.groups.set(e, this.groupValues(t));
@@ -6718,14 +6817,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6718
6817
  let e = $(t, this.shape.groupBy);
6719
6818
  this.groups.has(e) || this.groups.set(e, this.groupValues(t));
6720
6819
  }
6721
- let n = Ad(this.shape, this.state, e);
6820
+ let n = Rd(this.shape, this.state, e);
6722
6821
  this.state = n.state;
6723
6822
  for (let e of this.groups.keys()) this.state.has(e) || this.groups.delete(e);
6724
6823
  return n.rescanGroups;
6725
6824
  }
6726
6825
  resolveRescan(e, t) {
6727
6826
  if (e.length === 0) return;
6728
- this.state = jd(this.shape, this.state, e, t);
6827
+ this.state = zd(this.shape, this.state, e, t);
6729
6828
  let n = new Set(e);
6730
6829
  for (let e of t) {
6731
6830
  let t = $(e, this.shape.groupBy);
@@ -6734,7 +6833,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6734
6833
  for (let e of n) this.state.has(e) || this.groups.delete(e);
6735
6834
  }
6736
6835
  materialize() {
6737
- return kd(this.shape, this.state).map((e) => ({
6836
+ return Ld(this.shape, this.state).map((e) => ({
6738
6837
  groupKey: e.groupKey,
6739
6838
  group: this.groups.get(e.groupKey) ?? {},
6740
6839
  value: e.value
@@ -6747,7 +6846,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6747
6846
  for (let r of t) n[r] = e[r];
6748
6847
  return n;
6749
6848
  }
6750
- }, Nd = F("_voltro_rebac_tuples", {
6849
+ }, Vd = F("_voltro_rebac_tuples", {
6751
6850
  id: M({ prefix: "rbct" }),
6752
6851
  subjectId: I(),
6753
6852
  relation: I(),
@@ -6759,7 +6858,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6759
6858
  "subjectId",
6760
6859
  "resourceType",
6761
6860
  "resourceId"
6762
- ]), Pd = async (e, t, n, r) => t === null ? [] : (await e.query({
6861
+ ]), Hd = async (e, t, n, r) => t === null ? [] : (await e.query({
6763
6862
  table: "_voltro_rebac_tuples",
6764
6863
  predicate: C(O("subjectId", t), O("resourceType", n), O("resourceId", r)),
6765
6864
  order: [],
@@ -6771,16 +6870,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6771
6870
  relation: e.relation,
6772
6871
  resourceType: e.resourceType,
6773
6872
  resourceId: e.resourceId
6774
- })), Fd = (e) => ({
6873
+ })), Ud = (e) => ({
6775
6874
  id: e.id,
6776
6875
  tenantId: e.tenantId,
6777
6876
  ...e.scopes === void 0 ? {} : { scopes: e.scopes }
6778
- }), Id = (e, t) => {
6779
- let n = t.getPolicy ?? Qc;
6877
+ }), Wd = (e, t) => {
6878
+ let n = t.getPolicy ?? $c;
6780
6879
  return (r, i) => {
6781
6880
  let a = e[i.tag];
6782
6881
  if (a === void 0) return r;
6783
- let s = n(a.resourceType), c = (e) => o.fail(new Yc({
6882
+ let s = n(a.resourceType), c = (e) => o.fail(new Xc({
6784
6883
  action: a.action,
6785
6884
  resourceType: a.resourceType,
6786
6885
  resourceId: e
@@ -6788,17 +6887,17 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6788
6887
  if (s === void 0) return c("");
6789
6888
  let l = a.resourceId(i.input);
6790
6889
  if (l === null || l === "") return c("");
6791
- let u = Fd(i.subject), d = {
6890
+ let u = Ud(i.subject), d = {
6792
6891
  type: a.resourceType,
6793
6892
  id: l,
6794
6893
  tenantId: i.subject.tenantId
6795
6894
  };
6796
- return o.flatMap(o.promise(async () => t.loadTuples(u.id, a.resourceType, l)), (e) => il(u, a.action, d, {
6895
+ return o.flatMap(o.promise(async () => t.loadTuples(u.id, a.resourceType, l)), (e) => al(u, a.action, d, {
6797
6896
  policy: s,
6798
6897
  tuples: e
6799
6898
  }) ? r : c(l));
6800
6899
  };
6801
- }, Ld = async (e, t, n) => t === null ? [] : (await e.query({
6900
+ }, Gd = async (e, t, n) => t === null ? [] : (await e.query({
6802
6901
  table: "_voltro_rebac_tuples",
6803
6902
  predicate: C(O("subjectId", t), O("resourceType", n)),
6804
6903
  order: [],
@@ -6810,18 +6909,18 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6810
6909
  relation: e.relation,
6811
6910
  resourceType: e.resourceType,
6812
6911
  resourceId: e.resourceId
6813
- })), Rd = (e) => {
6814
- let t = e.getPolicy ?? Qc;
6912
+ })), Kd = (e) => {
6913
+ let t = e.getPolicy ?? $c;
6815
6914
  return async (n, r, i, a) => {
6816
6915
  let o = t(r);
6817
6916
  if (o === void 0) return [];
6818
- let s = Fd(n);
6819
- return ol(s, i, r, a, {
6917
+ let s = Ud(n);
6918
+ return sl(s, i, r, a, {
6820
6919
  policy: o,
6821
6920
  tuples: await e.loadSubjectTuples(s.id, r)
6822
6921
  });
6823
6922
  };
6824
- }, zd = (e) => {
6923
+ }, qd = (e) => {
6825
6924
  if (typeof e.name != "string" || e.name.length === 0) throw Error("defineReaction: a non-empty `name` is required");
6826
6925
  if (e.watch === void 0 || typeof e.watch.table != "string" || e.watch.table.length === 0) throw Error(`reaction '${e.name}': watch.table is required`);
6827
6926
  if (e.act === void 0 || e.act.kind !== "agent" && e.act.kind !== "workflow") throw Error(`reaction '${e.name}': act must be { kind: 'agent' | 'workflow', … }`);
@@ -6829,14 +6928,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6829
6928
  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`);
6830
6929
  if (e.guards.costBudgetUsd !== void 0 && e.guards.costBudgetUsd < 0) throw Error(`reaction '${e.name}': guards.costBudgetUsd must be >= 0`);
6831
6930
  return e;
6832
- }, Bd = (e, t) => e === void 0 ? !0 : Array.isArray(e) ? e.includes(t) : e === t, Vd = (e) => e.new?.tenantId ?? e.old?.tenantId ?? null, Hd = class {
6931
+ }, Jd = (e, t) => e === void 0 ? !0 : Array.isArray(e) ? e.includes(t) : e === t, Yd = (e) => e.new?.tenantId ?? e.old?.tenantId ?? null, Xd = class {
6833
6932
  hits = /* @__PURE__ */ new Map();
6834
6933
  allow(e, t, n, r) {
6835
6934
  let i = r - n, a = (this.hits.get(e) ?? []).filter((e) => e > i);
6836
6935
  return a.length >= t ? (this.hits.set(e, a), !1) : (a.push(r), this.hits.set(e, a), !0);
6837
6936
  }
6838
- }, Ud = async (e, t, n) => {
6839
- if (t.table !== e.watch.table || !Bd(e.watch.on, t.op)) return "skipped-op";
6937
+ }, Zd = async (e, t, n) => {
6938
+ if (t.table !== e.watch.table || !Jd(e.watch.on, t.op)) return "skipped-op";
6840
6939
  if (e.when !== void 0 && !e.when(t)) return "skipped-when";
6841
6940
  let r = `${e.name}:${e.guards.dedupeKey(t)}`;
6842
6941
  if (await n.dedupe.has(r)) return "skipped-dedupe";
@@ -6845,26 +6944,26 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6845
6944
  let t = n.now?.() ?? Date.now();
6846
6945
  if (!n.rateLimiter.allow(e.name, i.limit, i.windowMs, t)) return "skipped-ratelimit";
6847
6946
  }
6848
- let a = Vd(t);
6947
+ let a = Yd(t);
6849
6948
  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, {
6850
6949
  id: a,
6851
6950
  via: "agent"
6852
6951
  }), await n.dedupe.add(r), "acted");
6853
- }, Wd = F("_voltro_wakeups", {
6952
+ }, Qd = F("_voltro_wakeups", {
6854
6953
  id: M({ prefix: "wakeup" }),
6855
6954
  tenantId: I(),
6856
6955
  kind: I(),
6857
6956
  refId: I(),
6858
6957
  wakeAt: L(),
6859
6958
  status: I()
6860
- }).index(["status", "wakeAt"]).index(["tenantId"]), Gd = async (e) => {
6861
- let t = e.now?.() ?? /* @__PURE__ */ new Date(), n = await wu(e.store, t, e.batchLimit ?? 100);
6959
+ }).index(["status", "wakeAt"]).index(["tenantId"]), $d = async (e) => {
6960
+ let t = e.now?.() ?? /* @__PURE__ */ new Date(), n = await Mu(e.store, t, e.batchLimit ?? 100);
6862
6961
  if (n.length === 0) return 0;
6863
6962
  let r = 0;
6864
- for (let t of n) if (await bu(e.store, t)) try {
6963
+ for (let t of n) if (await Ou(e.store, t)) try {
6865
6964
  await e.adapter.wake(t), r++;
6866
6965
  } catch (n) {
6867
- await xu(e.store, t), e.log?.warn("wake: adapter failed — released for retry", {
6966
+ await ku(e.store, t), e.log?.warn("wake: adapter failed — released for retry", {
6868
6967
  tenantId: t.tenantId,
6869
6968
  kind: t.kind,
6870
6969
  refId: t.refId,
@@ -6872,11 +6971,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6872
6971
  });
6873
6972
  }
6874
6973
  return r > 0 && e.log?.info("wake: woke due deployments", { count: r }), r;
6875
- }, Kd = (e, t = 1e3) => {
6974
+ }, ef = (e, t = 1e3) => {
6876
6975
  let n = !1, r, i = async () => {
6877
6976
  if (!n) {
6878
6977
  try {
6879
- await Gd(e);
6978
+ await $d(e);
6880
6979
  } catch (t) {
6881
6980
  e.log?.warn("wake: tick failed", { reason: t instanceof Error ? t.message : String(t) });
6882
6981
  }
@@ -6886,10 +6985,10 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6886
6985
  return i(), { stop: () => {
6887
6986
  n = !0, r !== void 0 && clearTimeout(r);
6888
6987
  } };
6889
- }, qd = (e) => ({ wake: async () => {
6988
+ }, tf = (e) => ({ wake: async () => {
6890
6989
  await e.start();
6891
- } }), Jd = (e) => new Promise((t) => setTimeout(t, e)), Yd = (e) => {
6892
- let t = e.fetchImpl ?? fetch, n = e.now ?? Date.now, r = e.sleep ?? Jd, i = e.spawnImpl ?? Yt, 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 () => {
6990
+ } }), nf = (e) => new Promise((t) => setTimeout(t, e)), rf = (e) => {
6991
+ let t = e.fetchImpl ?? fetch, n = e.now ?? Date.now, r = e.sleep ?? nf, i = e.spawnImpl ?? Zt, 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 () => {
6893
6992
  try {
6894
6993
  let n = await t(e.healthUrl);
6895
6994
  return d(n);
@@ -6943,11 +7042,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6943
7042
  },
6944
7043
  stop: m
6945
7044
  };
6946
- }, Xd = async (e) => {
7045
+ }, af = async (e) => {
6947
7046
  if (e.signals.connectedClients() > 0 || e.signals.inFlightRequests() > 0 || e.signals.activeWorkflowExecutions() > 0) return !1;
6948
- let t = (e.now?.() ?? /* @__PURE__ */ new Date()).getTime() + (e.wakeLookaheadMs ?? 3e4), n = await Tu(e.store);
7047
+ let t = (e.now?.() ?? /* @__PURE__ */ new Date()).getTime() + (e.wakeLookaheadMs ?? 3e4), n = await Nu(e.store);
6949
7048
  return !(n !== null && n.wakeAt.getTime() <= t);
6950
- }, Zd = (e, t = Date.now) => {
7049
+ }, of = (e, t = Date.now) => {
6951
7050
  let n;
6952
7051
  return {
6953
7052
  update: (r) => {
@@ -6959,7 +7058,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6959
7058
  n = void 0;
6960
7059
  }
6961
7060
  };
6962
- }, Qd = () => {
7061
+ }, sf = () => {
6963
7062
  let e = 0, t = 0;
6964
7063
  return {
6965
7064
  onRequestStart: () => {
@@ -6977,8 +7076,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6977
7076
  inFlightRequests: () => e,
6978
7077
  openConnections: () => t
6979
7078
  };
6980
- }, $d = (e) => ({ run: async (t) => (e.onActivity?.(), await e.ensureAwake(), t()) }), ef = (e, t, n, r) => new Promise((i, a) => {
6981
- let o = bt.request({
7079
+ }, cf = (e) => ({ run: async (t) => (e.onActivity?.(), await e.ensureAwake(), t()) }), lf = (e, t, n, r) => new Promise((i, a) => {
7080
+ let o = xt.request({
6982
7081
  host: n,
6983
7082
  port: r,
6984
7083
  method: e.method,
@@ -6988,8 +7087,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
6988
7087
  t.writeHead(e.statusCode ?? 502, e.headers), e.pipe(t), e.on("end", i), e.on("error", a);
6989
7088
  });
6990
7089
  o.on("error", a), e.pipe(o);
6991
- }), tf = (e, t, n, r, i) => new Promise((a, o) => {
6992
- let s = bt.request({
7090
+ }), uf = (e, t, n, r, i) => new Promise((a, o) => {
7091
+ let s = xt.request({
6993
7092
  host: r,
6994
7093
  port: i,
6995
7094
  method: e.method,
@@ -7003,21 +7102,21 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7003
7102
  };
7004
7103
  t.on("close", s), r.on("close", s), r.on("error", o);
7005
7104
  }), s.on("error", o), s.end();
7006
- }), nf = (e) => {
7007
- let t = $d({
7105
+ }), df = (e) => {
7106
+ let t = cf({
7008
7107
  ensureAwake: () => e.supervisor.start(),
7009
7108
  ...e.onActivity === void 0 ? {} : { onActivity: e.onActivity }
7010
- }), n = e.activity, r = bt.createServer((r, i) => {
7011
- n?.onRequestStart(), i.on("close", () => n?.onRequestEnd()), t.run(() => ef(r, i, e.targetHost, e.targetPort)).catch((t) => {
7109
+ }), n = e.activity, r = xt.createServer((r, i) => {
7110
+ n?.onRequestStart(), i.on("close", () => n?.onRequestEnd()), t.run(() => lf(r, i, e.targetHost, e.targetPort)).catch((t) => {
7012
7111
  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");
7013
7112
  });
7014
7113
  });
7015
7114
  return r.on("upgrade", (r, i, a) => {
7016
- n?.onConnect(), i.on("close", () => n?.onDisconnect()), t.run(() => tf(r, i, a, e.targetHost, e.targetPort)).catch((t) => {
7115
+ n?.onConnect(), i.on("close", () => n?.onDisconnect()), t.run(() => uf(r, i, a, e.targetHost, e.targetPort)).catch((t) => {
7017
7116
  e.log?.warn("wake-router: upgrade proxy failed", { reason: t instanceof Error ? t.message : String(t) }), i.destroy();
7018
7117
  });
7019
7118
  }), r;
7020
- }, rf = async (e) => {
7119
+ }, ff = async (e) => {
7021
7120
  try {
7022
7121
  return (await e.query({
7023
7122
  table: "_voltro_workflow_runs",
@@ -7034,15 +7133,15 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7034
7133
  } catch {
7035
7134
  return 0;
7036
7135
  }
7037
- }, af = async (e) => {
7038
- let t = qd(e.supervisor), n = await Gd({
7136
+ }, pf = async (e) => {
7137
+ let t = tf(e.supervisor), n = await $d({
7039
7138
  store: e.store,
7040
7139
  adapter: t,
7041
7140
  ...e.now === void 0 ? {} : { now: e.now },
7042
7141
  ...e.log === void 0 ? {} : { log: e.log }
7043
7142
  });
7044
7143
  n > 0 && e.idleGate.reset();
7045
- let r = await Xd({
7144
+ let r = await af({
7046
7145
  store: e.store,
7047
7146
  signals: e.signals,
7048
7147
  ...e.wakeLookaheadMs === void 0 ? {} : { wakeLookaheadMs: e.wakeLookaheadMs },
@@ -7052,12 +7151,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7052
7151
  woke: n,
7053
7152
  stopped: i
7054
7153
  };
7055
- }, of = async (e) => {
7056
- let t = Zd(e.idleGraceMs ?? 6e4), n = e.tickMs ?? 1e3, r = Qd(), i = 0, a = e.signals === void 0, o = e.signals ?? {
7154
+ }, mf = async (e) => {
7155
+ let t = of(e.idleGraceMs ?? 6e4), n = e.tickMs ?? 1e3, r = sf(), i = 0, a = e.signals === void 0, o = e.signals ?? {
7057
7156
  connectedClients: () => r.openConnections(),
7058
7157
  inFlightRequests: () => r.inFlightRequests(),
7059
7158
  activeWorkflowExecutions: () => i
7060
- }, s = nf({
7159
+ }, s = df({
7061
7160
  supervisor: e.supervisor,
7062
7161
  targetHost: e.targetHost,
7063
7162
  targetPort: e.targetPort,
@@ -7076,7 +7175,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7076
7175
  let l = !1, u, d = e.firedRetentionMs ?? 10 * 6e4, f = 0, p = async () => {
7077
7176
  if (!l) {
7078
7177
  try {
7079
- if (a && (i = await rf(e.store)), await af({
7178
+ if (a && (i = await ff(e.store)), await pf({
7080
7179
  store: e.store,
7081
7180
  supervisor: e.supervisor,
7082
7181
  signals: o,
@@ -7084,7 +7183,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7084
7183
  ...e.wakeLookaheadMs === void 0 ? {} : { wakeLookaheadMs: e.wakeLookaheadMs },
7085
7184
  ...e.log === void 0 ? {} : { log: e.log }
7086
7185
  }), f++ % 60 == 0) {
7087
- let t = await Du(e.store, { firedOlderThan: new Date(Date.now() - d) });
7186
+ let t = await Fu(e.store, { firedOlderThan: new Date(Date.now() - d) });
7088
7187
  t > 0 && e.log?.info("orchestrator: pruned fired wakeups", { count: t });
7089
7188
  }
7090
7189
  } catch (t) {
@@ -7099,14 +7198,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7099
7198
  l = !0, u !== void 0 && clearTimeout(u), await new Promise((e) => s.close(() => e()));
7100
7199
  }
7101
7200
  };
7102
- }, sf = (e) => e, cf = class extends y.TaggedError()("AnalyticsError", {
7201
+ }, hf = (e) => e, gf = class extends y.TaggedError()("AnalyticsError", {
7103
7202
  provider: y.String,
7104
7203
  operation: y.String,
7105
7204
  cause: y.String
7106
- }) {}, lf = class extends y.TaggedError()("AnalyticsCapabilityNotSupported", {
7205
+ }) {}, _f = class extends y.TaggedError()("AnalyticsCapabilityNotSupported", {
7107
7206
  provider: y.String,
7108
7207
  capability: y.String
7109
- }) {}, uf = class extends n.Tag("@voltro/AnalyticsSink")() {}, df = (e, t) => ({
7208
+ }) {}, vf = class extends n.Tag("@voltro/AnalyticsSink")() {}, yf = (e, t) => ({
7110
7209
  info: e.info,
7111
7210
  track: (n) => e.track(n.tenantId === void 0 ? {
7112
7211
  ...n,
@@ -7125,20 +7224,20 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7125
7224
  tenantId: t
7126
7225
  } : n),
7127
7226
  ...e.mirror === void 0 ? {} : { mirror: e.mirror }
7128
- }), ff = () => o.gen(function* () {
7129
- let e = yield* uf, t = yield* o.serviceOption(z), n = h.match(t, {
7227
+ }), bf = () => o.gen(function* () {
7228
+ let e = yield* vf, t = yield* o.serviceOption(et), n = h.match(t, {
7130
7229
  onNone: () => null,
7131
7230
  onSome: (e) => e.tenantId ?? null
7132
7231
  });
7133
- return n === null ? e : df(e, n);
7134
- }), pf = "noop", mf = () => {
7135
- let e = (e) => o.fail(new lf({
7136
- provider: pf,
7232
+ return n === null ? e : yf(e, n);
7233
+ }), xf = "noop", Sf = () => {
7234
+ let e = (e) => o.fail(new _f({
7235
+ provider: xf,
7137
7236
  capability: e
7138
7237
  }));
7139
7238
  return {
7140
7239
  info: {
7141
- provider: pf,
7240
+ provider: xf,
7142
7241
  capabilities: {
7143
7242
  track: !0,
7144
7243
  aggregate: !1,
@@ -7152,8 +7251,8 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7152
7251
  timeseries: () => e("timeseries"),
7153
7252
  topN: () => e("topN")
7154
7253
  };
7155
- }, hf = (e) => {
7156
- if (e.length === 0) return mf();
7254
+ }, Cf = (e) => {
7255
+ if (e.length === 0) return Sf();
7157
7256
  if (e.length === 1) return e[0];
7158
7257
  let t = {
7159
7258
  provider: "compose",
@@ -7170,7 +7269,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7170
7269
  discard: !0
7171
7270
  }), r = (t, n) => {
7172
7271
  let r = e.find((e) => e.info.capabilities[t]);
7173
- return r === void 0 ? o.fail(new lf({
7272
+ return r === void 0 ? o.fail(new _f({
7174
7273
  provider: "compose",
7175
7274
  capability: t
7176
7275
  })) : n(r);
@@ -7193,11 +7292,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7193
7292
  topN: (e) => r("topN", (t) => t.topN(e)),
7194
7293
  ...a === void 0 ? {} : { mirror: a }
7195
7294
  };
7196
- }, gf = (e) => {
7295
+ }, wf = (e) => {
7197
7296
  let t = e.filter((e) => e.dispose !== void 0);
7198
7297
  return {
7199
7298
  kind: "compose",
7200
- build: (t) => hf(e.map((e) => e.build(t))),
7299
+ build: (t) => Cf(e.map((e) => e.build(t))),
7201
7300
  tables: e.flatMap((e) => e.tables ?? []),
7202
7301
  initialize: (t) => o.forEach(e, (e) => e.initialize ? e.initialize(t) : o.void, {
7203
7302
  concurrency: 1,
@@ -7208,15 +7307,15 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7208
7307
  discard: !0
7209
7308
  }) } : {}
7210
7309
  };
7211
- }, _f = {
7310
+ }, Tf = {
7212
7311
  kind: "noop",
7213
- build: () => mf()
7214
- }, vf = {
7312
+ build: () => Sf()
7313
+ }, Ef = {
7215
7314
  tables: [],
7216
7315
  detach: () => {}
7217
- }, yf = (e) => {
7316
+ }, Df = (e) => {
7218
7317
  let { store: t, sink: n, log: r } = e, i = n.mirror;
7219
- if (i === void 0 || i.tables.length === 0) return vf;
7318
+ if (i === void 0 || i.tables.length === 0) return Ef;
7220
7319
  let a = e.run ?? ((e) => o.runPromise(e)), s = i.primaryKey ?? "id", c = new Set(i.tables), l = (e) => {
7221
7320
  if (e.op === "delete") {
7222
7321
  let t = e.old;
@@ -7240,11 +7339,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7240
7339
  tables: i.tables,
7241
7340
  detach: u
7242
7341
  };
7243
- }, bf = (e) => {
7342
+ }, Of = (e) => {
7244
7343
  let t = typeof e.refresh == "string" ? { interval: e.refresh } : e.refresh, n = e.strategy ?? "replace";
7245
7344
  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`);
7246
7345
  if (e.incremental !== void 0) {
7247
- let t = wd({
7346
+ let t = Md({
7248
7347
  aggregations: [{
7249
7348
  op: e.incremental.op,
7250
7349
  ...e.incremental.column === void 0 ? {} : { column: e.incremental.column }
@@ -7266,47 +7365,47 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7266
7365
  build: e.build,
7267
7366
  ...e.incremental === void 0 ? {} : { incremental: e.incremental }
7268
7367
  };
7269
- }, xf = (e) => typeof e == "object" && !!e && e._voltroAggregate === !0, Sf = class extends y.TaggedError()("AggregateStale", {
7368
+ }, kf = (e) => typeof e == "object" && !!e && e._voltroAggregate === !0, Af = class extends y.TaggedError()("AggregateStale", {
7270
7369
  name: y.String,
7271
7370
  ageMs: y.Number,
7272
7371
  maxAgeMs: y.Number
7273
- }) {}, Cf = class extends y.TaggedError()("AggregateNotFound", { name: y.String }) {}, wf = class extends y.TaggedError()("AggregateError", {
7372
+ }) {}, jf = class extends y.TaggedError()("AggregateNotFound", { name: y.String }) {}, Mf = class extends y.TaggedError()("AggregateError", {
7274
7373
  name: y.String,
7275
7374
  operation: y.String,
7276
7375
  cause: y.String
7277
- }) {}, Tf = class extends n.Tag("@voltro/AggregateRegistry")() {}, Ef = (e) => o.gen(function* () {
7278
- return (yield* Tf).getHandle(e);
7279
- }), Df = (e, t, n) => {
7376
+ }) {}, Nf = class extends n.Tag("@voltro/AggregateRegistry")() {}, Pf = (e) => o.gen(function* () {
7377
+ return (yield* Nf).getHandle(e);
7378
+ }), Ff = (e, t, n) => {
7280
7379
  if (e.crossTenant || !t.has(e.table) || n == null) return e;
7281
7380
  let r = O("tenantId", n);
7282
7381
  return {
7283
7382
  ...e,
7284
7383
  predicate: e.predicate ? C(e.predicate, r) : r
7285
7384
  };
7286
- }, Of = (e, t, n) => n === "" && !e.crossTenant && t.has(e.table), kf = (e) => e?.type === "user" && e.tenantId === "", Af = (e, t) => {
7385
+ }, If = (e, t, n) => n === "" && !e.crossTenant && t.has(e.table), Lf = (e) => e?.type === "user" && e.tenantId === "", Rf = (e, t) => {
7287
7386
  if (e.includeDeleted || !t.has(e.table)) return e;
7288
7387
  let n = de("deletedAt");
7289
7388
  return {
7290
7389
  ...e,
7291
7390
  predicate: e.predicate ? C(e.predicate, n) : n
7292
7391
  };
7293
- }, jf = (e, t) => t, Mf = (t) => o.runPromiseExit(t).then((t) => {
7392
+ }, zf = (e, t) => t, Bf = (t) => o.runPromiseExit(t).then((t) => {
7294
7393
  if (c.isSuccess(t)) return t.value;
7295
7394
  let n = e.failureOption(t.cause);
7296
7395
  throw h.isSome(n) ? n.value : e.squash(t.cause);
7297
- }), Nf = (e, t) => e.pipe(o.provideService(z, t)), Pf = async (e, t, n) => {
7298
- let r = await o.runPromise(at(t, e.guards, n));
7396
+ }), Vf = (e, t) => e.pipe(o.provideService(et, t)), Hf = async (e, t, n) => {
7397
+ let r = await o.runPromise(ot(t, e.guards, n));
7299
7398
  if (r) throw r;
7300
- }, Ff = async (e) => {
7399
+ }, Uf = async (e) => {
7301
7400
  if (Dr() === void 0) return e;
7302
- let t = await Mf(kr(e.subject, (e) => {
7401
+ let t = await Bf(kr(e.subject, (e) => {
7303
7402
  console.error("[voltro] row filter failed to load", e);
7304
7403
  }));
7305
7404
  return {
7306
7405
  ...e,
7307
7406
  rowFilter: t
7308
7407
  };
7309
- }, If = async (t) => {
7408
+ }, Wf = async (t) => {
7310
7409
  let n = `${t.kind}.${t.name}`, r = Date.now(), i = "ok";
7311
7410
  try {
7312
7411
  if (t.interceptor) {
@@ -7335,28 +7434,28 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7335
7434
  status: i
7336
7435
  });
7337
7436
  }
7338
- }, Lf = /* @__PURE__ */ new Set([1213, 1205]), Rf = /* @__PURE__ */ new Set([
7437
+ }, Gf = /* @__PURE__ */ new Set([1213, 1205]), Kf = /* @__PURE__ */ new Set([
7339
7438
  "ER_LOCK_DEADLOCK",
7340
7439
  "ER_LOCK_WAIT_TIMEOUT",
7341
7440
  "40001",
7342
7441
  "40P01"
7343
- ]), zf = (e) => {
7442
+ ]), qf = (e) => {
7344
7443
  let t = e;
7345
7444
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
7346
7445
  let e = t;
7347
- if (typeof e.errno == "number" && Lf.has(e.errno) || typeof e.code == "string" && Rf.has(e.code) || typeof e.sqlState == "string" && Rf.has(e.sqlState)) return !0;
7446
+ if (typeof e.errno == "number" && Gf.has(e.errno) || typeof e.code == "string" && Kf.has(e.code) || typeof e.sqlState == "string" && Kf.has(e.sqlState)) return !0;
7348
7447
  t = e.cause;
7349
7448
  }
7350
7449
  return !1;
7351
- }, Bf = 3, Vf = (e) => new Promise((t) => setTimeout(t, e)), Hf = async (e, t) => {
7352
- let n = t?.delay ?? ((e) => Vf(e * 20 + Math.floor(Math.random() * 30)));
7450
+ }, Jf = 3, Yf = (e) => new Promise((t) => setTimeout(t, e)), Xf = async (e, t) => {
7451
+ let n = t?.delay ?? ((e) => Yf(e * 20 + Math.floor(Math.random() * 30)));
7353
7452
  for (let t = 1;; t++) try {
7354
7453
  return await e();
7355
7454
  } catch (e) {
7356
- if (t >= Bf || !zf(e)) throw e;
7455
+ if (t >= Jf || !qf(e)) throw e;
7357
7456
  await n(t);
7358
7457
  }
7359
- }, Uf = (e) => (t, n, r) => If({
7458
+ }, Zf = (e) => (t, n, r) => Wf({
7360
7459
  name: t.descriptor.name,
7361
7460
  kind: "mutation",
7362
7461
  input: n,
@@ -7364,11 +7463,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7364
7463
  ...e.interceptor ? { interceptor: e.interceptor } : {},
7365
7464
  ...e.recordMetric ? { recordMetric: e.recordMetric } : {},
7366
7465
  runExecutor: async () => {
7367
- await Pf(t.descriptor, r.subject, n);
7368
- let i = await Ff(r), a = [], s = await Hf(async () => (a.length = 0, e.store.transactional(async (s) => {
7466
+ await Hf(t.descriptor, r.subject, n);
7467
+ let i = await Uf(r), a = [], s = await Xf(async () => (a.length = 0, e.store.transactional(async (s) => {
7369
7468
  let c = e.undoCapture?.(s), l = c ? c.tx : s, u = e.buildContext(i, l, { afterCommit: (e) => {
7370
7469
  a.push(e);
7371
- } }), d = t.executor(n, u), f = o.isEffect(d) ? await e.runEffect(Nf(d, r.subject), u.store) : await d;
7470
+ } }), d = t.executor(n, u), f = o.isEffect(d) ? await e.runEffect(Vf(d, r.subject), u.store) : await d;
7372
7471
  return c && await c.persist(u.store, {
7373
7472
  tag: t.descriptor.name,
7374
7473
  subject: r.subject,
@@ -7378,33 +7477,33 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7378
7477
  for (let e of a) await e();
7379
7478
  return s;
7380
7479
  }
7381
- }), Wf = (e) => e && typeof e == "object" && "descriptor" in e ? e.descriptor : e, Gf = (e) => typeof e == "object" && !!e && !Array.isArray(e) && "table" in e && "order" in e, Kf = (e) => {
7480
+ }), Qf = (e) => e && typeof e == "object" && "descriptor" in e ? e.descriptor : e, $f = (e) => typeof e == "object" && !!e && !Array.isArray(e) && "table" in e && "order" in e, ep = (e) => {
7382
7481
  let t = e.descriptor.source;
7383
7482
  return t == null ? [] : typeof t == "string" ? [t] : [...t];
7384
- }, qf = (e, t) => (n) => () => {
7483
+ }, tp = (e, t) => (n) => () => {
7385
7484
  let r = e.descriptor.guards;
7386
- return !r || r.length === 0 ? Promise.resolve(null) : o.runPromise(at(n, r, t));
7387
- }, Jf = (e) => (t, n) => (r) => {
7388
- let i = e.buildContext(r), a = qf(t, n)(r.subject), s = async () => {
7485
+ return !r || r.length === 0 ? Promise.resolve(null) : o.runPromise(ot(n, r, t));
7486
+ }, np = (e) => (t, n) => (r) => {
7487
+ let i = e.buildContext(r), a = tp(t, n)(r.subject), s = async () => {
7389
7488
  let i = await a();
7390
7489
  if (i) throw i;
7391
- let s = e.buildContext(await Ff(r)), c = t.executor(n, s);
7392
- return o.isEffect(c) ? o.runPromise(e.provideEffect(Nf(c, r.subject), s.store)) : Wf(await Promise.resolve(c));
7490
+ let s = e.buildContext(await Uf(r)), c = t.executor(n, s);
7491
+ return o.isEffect(c) ? o.runPromise(e.provideEffect(Vf(c, r.subject), s.store)) : Qf(await Promise.resolve(c));
7393
7492
  }, c = (n) => {
7394
- let i = Wf(n);
7395
- return Gf(i) ? e.finalize(i, r) : {
7493
+ let i = Qf(n);
7494
+ return $f(i) ? e.finalize(i, r) : {
7396
7495
  __voltroComputed: !0,
7397
7496
  value: i,
7398
- dependentTables: Kf(t),
7497
+ dependentTables: ep(t),
7399
7498
  tenantId: r.subject?.tenantId ?? null,
7400
7499
  recompute: s
7401
7500
  };
7402
7501
  }, l = () => {
7403
7502
  let a = t.executor(n, i);
7404
- return o.isEffect(a) ? e.provideEffect(Nf(a, r.subject), i.store).pipe(o.map(c)) : a instanceof Promise ? o.promise(() => a).pipe(o.map(c)) : c(a);
7503
+ return o.isEffect(a) ? e.provideEffect(Vf(a, r.subject), i.store).pipe(o.map(c)) : a instanceof Promise ? o.promise(() => a).pipe(o.map(c)) : c(a);
7405
7504
  }, u = () => {
7406
7505
  let e = t.descriptor.guards;
7407
- return !e || e.length === 0 ? l() : at(r.subject, e, n).pipe(o.flatMap((e) => {
7506
+ return !e || e.length === 0 ? l() : ot(r.subject, e, n).pipe(o.flatMap((e) => {
7408
7507
  if (e) return o.fail(e);
7409
7508
  let t = l();
7410
7509
  return o.isEffect(t) ? t : o.succeed(t);
@@ -7423,14 +7522,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7423
7522
  traceId: r.traceId,
7424
7523
  ...r.spanId === void 0 ? {} : { spanId: r.spanId }
7425
7524
  });
7426
- }, Yf = (e) => async (t, n, r) => {
7427
- let i = await Ff(r), a = Jf(e)(t, n)(i), s = o.isEffect(a) ? await Mf(a) : a;
7525
+ }, rp = (e) => async (t, n, r) => {
7526
+ let i = await Uf(r), a = np(e)(t, n)(i), s = o.isEffect(a) ? await Bf(a) : a;
7428
7527
  return zr(s) ? s.value : e.queryRows(s);
7429
- }, Xf = (e) => (t, n, r, i) => {
7528
+ }, ip = (e) => (t, n, r, i) => {
7430
7529
  let a = !1, s;
7431
7530
  return (async () => {
7432
7531
  try {
7433
- let c = await Ff(r), l = Jf(e)(t, n)(c), u = o.isEffect(l) ? await Mf(l) : l, d = (e) => i(e), f = zr(u) ? await e.subscribeComputed(u, d, c) : await e.subscribeDescriptor(u, d, c);
7532
+ let c = await Uf(r), l = np(e)(t, n)(c), u = o.isEffect(l) ? await Bf(l) : l, d = (e) => i(e), f = zr(u) ? await e.subscribeComputed(u, d, c) : await e.subscribeDescriptor(u, d, c);
7434
7533
  a ? f() : s = f;
7435
7534
  } catch (e) {
7436
7535
  i({
@@ -7441,7 +7540,7 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7441
7540
  })(), () => {
7442
7541
  a = !0, s?.();
7443
7542
  };
7444
- }, Zf = (e) => (t, n, r) => If({
7543
+ }, ap = (e) => (t, n, r) => Wf({
7445
7544
  name: t.descriptor.name,
7446
7545
  kind: "action",
7447
7546
  input: n,
@@ -7449,16 +7548,16 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7449
7548
  ...e.interceptor ? { interceptor: e.interceptor } : {},
7450
7549
  ...e.recordMetric ? { recordMetric: e.recordMetric } : {},
7451
7550
  runExecutor: async () => {
7452
- await Pf(t.descriptor, r.subject, n);
7453
- let i = e.buildContext(await Ff(r)), a = t.executor(n, i);
7454
- return o.isEffect(a) ? e.runEffect(Nf(a, r.subject), i.store) : a;
7551
+ await Hf(t.descriptor, r.subject, n);
7552
+ let i = e.buildContext(await Uf(r)), a = t.executor(n, i);
7553
+ return o.isEffect(a) ? e.runEffect(Vf(a, r.subject), i.store) : a;
7455
7554
  }
7456
- }), Qf = (e) => e instanceof Date ? e.toISOString() : typeof e == "string" && e.length > 0 ? e : null, $f = (e) => typeof e == "string" && e.length > 0 ? e : null, ep = [
7555
+ }), op = (e) => e instanceof Date ? e.toISOString() : typeof e == "string" && e.length > 0 ? e : null, sp = (e) => typeof e == "string" && e.length > 0 ? e : null, cp = [
7457
7556
  "updatedAt",
7458
7557
  "createdAt",
7459
7558
  "updatedBy",
7460
7559
  "createdBy"
7461
- ], tp = (e) => ep.some((t) => t in e), np = (e, t, n) => {
7560
+ ], lp = (e) => cp.some((t) => t in e), up = (e, t, n) => {
7462
7561
  let r = {
7463
7562
  table: t.table,
7464
7563
  id: t.id,
@@ -7473,14 +7572,14 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7473
7572
  found: !1
7474
7573
  };
7475
7574
  let i = t.column === void 0 ? void 0 : e[t.column];
7476
- if (!tp(e)) return {
7575
+ if (!lp(e)) return {
7477
7576
  ...r,
7478
7577
  value: i,
7479
7578
  lastWrite: null,
7480
7579
  attribution: "none",
7481
7580
  found: !0
7482
7581
  };
7483
- let a = $f(e.updatedBy) ?? $f(e.createdBy), o = Qf(e.updatedAt) ?? Qf(e.createdAt);
7582
+ let a = sp(e.updatedBy) ?? sp(e.createdBy), o = op(e.updatedAt) ?? op(e.createdAt);
7484
7583
  return {
7485
7584
  ...r,
7486
7585
  value: i,
@@ -7492,12 +7591,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7492
7591
  attribution: "audit",
7493
7592
  found: !0
7494
7593
  };
7495
- }, rp = (e, t) => {
7594
+ }, dp = (e, t) => {
7496
7595
  let n = e.map((e) => {
7497
7596
  let n = e.newValue ?? e.value, r = t.column !== void 0 && n && typeof n == "object" ? n[t.column] : e.newValue ?? e.value;
7498
7597
  return {
7499
- actor: { id: $f(e.actor) ?? $f(e.changedBy) },
7500
- at: Qf(e.at) ?? Qf(e.changedAt),
7598
+ actor: { id: sp(e.actor) ?? sp(e.changedBy) },
7599
+ at: op(e.at) ?? op(e.changedAt),
7501
7600
  ...e.traceId === void 0 ? {} : { traceId: e.traceId },
7502
7601
  value: r
7503
7602
  };
@@ -7512,12 +7611,12 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7512
7611
  history: n,
7513
7612
  found: n.length > 0
7514
7613
  };
7515
- }, ip = (e) => {
7614
+ }, fp = (e) => {
7516
7615
  let t = e.new?.id;
7517
7616
  if (typeof t == "string") return t;
7518
7617
  let n = e.old?.id;
7519
7618
  return typeof n == "string" ? n : void 0;
7520
- }, ap = (e) => {
7619
+ }, pp = (e) => {
7521
7620
  let t = {};
7522
7621
  if (e.op === "insert") for (let [n, r] of Object.entries(e.new ?? {})) t[n] = {
7523
7622
  from: void 0,
@@ -7537,11 +7636,11 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7537
7636
  return {
7538
7637
  table: e.table,
7539
7638
  op: e.op,
7540
- id: ip(e),
7639
+ id: fp(e),
7541
7640
  fields: t
7542
7641
  };
7543
- }, op = (e) => {
7544
- let t = e.map(ap);
7642
+ }, mp = (e) => {
7643
+ let t = e.map(pp);
7545
7644
  return {
7546
7645
  rows: t,
7547
7646
  summary: {
@@ -7550,21 +7649,21 @@ var K = /* @__PURE__ */ new Map(), Yr = (e, t) => {
7550
7649
  deletes: t.filter((e) => e.op === "delete").length
7551
7650
  }
7552
7651
  };
7553
- }, sp = class extends Error {
7652
+ }, hp = class extends Error {
7554
7653
  constructor() {
7555
7654
  super("voltro:preview-rollback"), this.name = "PreviewRollback";
7556
7655
  }
7557
- }, cp = async (e, t) => {
7656
+ }, gp = async (e, t) => {
7558
7657
  let n, r = !1;
7559
7658
  try {
7560
7659
  await e.transactional(async (e) => {
7561
- throw n = await t(e), r = !0, new sp();
7660
+ throw n = await t(e), r = !0, new hp();
7562
7661
  });
7563
7662
  } catch (e) {
7564
- if (!(e instanceof sp)) throw e;
7663
+ if (!(e instanceof hp)) throw e;
7565
7664
  }
7566
7665
  if (!r) throw Error("preview: handler did not complete");
7567
7666
  return n;
7568
- }, lp = "framework-runtime";
7667
+ }, _p = "framework-runtime";
7569
7668
  //#endregion
7570
- export { wo as API_KEYS_TABLE, Yc as AccessDenied, wf as AggregateError, Md as AggregateMaintainer, Cf as AggregateNotFound, Tf as AggregateRegistry, Sf as AggregateStale, lf as AnalyticsCapabilityNotSupported, cf as AnalyticsError, uf as AnalyticsSink, X as CONNECTIONS_TABLE, Js as CONNECTION_GRANTS_TABLE, $l as CircuitBreaker, Zl as CircuitOpen, _c as ConnectionNotConnected, Aa as DEFAULT_MAX_RPC_BODY_BYTES, hc as DEFAULT_REFRESH_SKEW_MS, wr as DEFAULT_ROW_FILTER_RETRY, ku as DORMANCY_WAKEUP_TENANT, Pi as DeleteBuilder, Ir as Dispatcher, Ss as EVENT_CLIENT_QUEUE_SIZE, Cs as EVENT_LATEST_QUEUE_SIZE, zo as EffectStore, _s as EventBus, kc as GRANT_TTL_MS, vn as InMemoryDataStore, an as IndexedMatcher, ks as InstanceMembership, Zt as LinearScanMatcher, p as MetricBoundaries, pf as NOOP_ANALYTICS_PROVIDER, Or as NO_ROW_FILTER, Di as NoRowFound, Ns as OUTBOX_ATTEMPTS_TABLE, Bs as OUTBOX_ATTEMPT_LOG_CAP, Y as OUTBOX_TABLE, Oi as OptimisticLockError, Jc as REBAC_ADMIN_SCOPE, gc as REFRESH_LEASE_MS, lp as RUNTIME_NAME, Hd as ReactionRateLimiter, ta as ReplicatedDataStore, Cr as RowFilterUnavailable, Ou as SCHEDULE_SUBJECT, Ro as SYSTEM_SUBJECT, Mi as SelectBuilder, bl as SsrfBlockedError, Li as StoreOperationFailed, cn as SubscriptionRegistry, Ri as TableValidationFailed, Ii as TenantScopeViolation, vd as TimelineRecorder, Zu as UndoBoundaryError, $u as UndoStack, Ni as UpdateBuilder, Dl as VOLTRO_AUDIT_MIXIN_ID, kl as VOLTRO_EXPIRES_MIXIN_ID, Ol as VOLTRO_SOFT_DELETE_MIXIN_ID, Al as VOLTRO_TENANT_MIXIN_ID, Yo as WorkflowPayloadError, Zr as _connectionStreamCount, Qr as _resetConnectionSubjectsForTest, Xs as _voltroConnectionGrantsTable, qs as _voltroConnectionsTable, Nd as _voltroRebacTuplesTable, Bu as _voltroScheduleClaimsTable, zu as _voltroScheduleRunsTable, Vu as _voltroTracesTable, Hu as _voltroUndoLogTable, Wd as _voltroWakeupsTable, ds as _voltroWorkflowEventDeliveriesTable, us as _voltroWorkflowEventsTable, Wi as actingUserId, Lo as apiKeyManagementRoutes, Vi as applyDefined, Ad as applyDelta, td as applyInverse, nd as applyInverses, Mr as applyRowFilter, Nr as applyRowFilterToDescriptor, Af as applySoftDeleteScope, Df as applyTenantScope, ud as applyUndoInvocation, al as assertCan, ec as assertConnectionCipherConfigured, yf as attachAnalyticsMirror, Ha as awaitServerListening, zs as backoffMs, Nc as beginOAuthConnect, Wr as bindConnectionSubject, Es as bindEvent, ka as bindMutation, va as bindStream, _a as bindSubscription, fa as bindSubscriptionUntyped, Od as buildIvmState, op as buildPreview, Id as buildRebacInterceptor, Rd as buildRebacReadFilter, Yi as buildSubjectKey, qa as buildTracingLayer, Yl as cacheScopeLeaks, co as cachedBackend, il as can, _u as cancelWakeup, on as canonicalize, wd as classifyShape, xc as clearConnectionRefreshFlights, el as clearResourcePolicies, ee as clearRetentions, nu as clearSystemStoreHandle, fu as compileCron, Pc as completeOAuthConnect, gf as composeAnalytics, hf as composeAnalyticsSinks, Ac as connectionCallbackPath, $s as connectionLabel, $r as connectionSubjectsSnapshot, rf as countRunningWorkflows, _r as counter, Wl as crud, ul as currentRequestLoader, ea as currentRoutingContext, oi as currentTraceContext, Po as dataStoreApiKeyStore, go as dataStoreIdempotencyStore, xo as dataStoreKvStore, mi as decryptField, bf as defineAggregate, Qs as defineConnection, as as defineEventTrigger, jf as defineExecutor, Is as defineOutboxHandler, zd as defineReaction, Zc as defineResourcePolicy, du as defineSchedule, sf as defineSubscriber, Pr as deliveredRowCount, si as deriveKey, ap as diffChange, Ba as drainForShutdown, Ws as drainOutbox, wu as dueWakeups, rl as effectiveRelations, Fl as emptySchemaRegistry, bi as enableGraphObservation, pi as encryptField, ll as enterRequestLoader, no as envSecretsBackend, ar as eventMetricTagCacheSizeForTests, pc as exchangeAuthorizationCode, ri as externalSpanFromTraceparent, bn as extractDbCause, sn as fingerprintFor, lc as forgetCredential, Xl as formatCacheScopeLeaks, Jl as formatServerOnlyLeaks, ti as formatTraceparent, ed as forwardChangeFromCdc, Fo as frameworkApiKeyStrategy, vr as gauge, Eo as generateApiKeyToken, Rc as getConnectionResolver, Gr as getConnectionSubject, q as getFieldCipher, Qc as getResourcePolicy, Dr as getRowFilter, ru as getSystemStoreHandle, bd as getTimelineRecorder, hl as getTupleSource, $ as groupKeyOf, yr as histogramMetric, rp as historyProvenance, lo as httpSecretsBackend, Jt as inspectWorkflow, gl as installPolicyGuardResolver, Xr as interruptConnectionStreams, Yu as invertChange, xf as isAggregateDefinition, Of as isEmptyTenantScopedRead, xn as isForeignKeyViolation, Xd as isIdleNow, wa as isInfraError, xi as isObservingGraph, kf as isOrglessUserSubject, Sn as isQueryTimeout, Qu as isSafeToApply, lu as isScheduleDefinition, os as isWorkflowEventTriggerDefinition, Dd as ivmValue, np as lastWriteProvenance, uc as listConnectionStates, $c as listResourcePolicies, pe as listRetentions, Pd as loadResourceTuples, Ld as loadSubjectTuples, au as localityAwareSelector, Zf as makeActionRunner, Mu as makeAdvisoryLockCoordinator, ci as makeAesCipher, ko as makeApiKeyService, El as makeApiKeyUsageBuffer, No as makeApiKeyUsageFlusher, Cn as makeAppAccess, So as makeAsyncKv, Ts as makeBufferGapDetector, to as makeBufferingSpanProcessor, tc as makeConnectionRegistry, Bc as makeConnectionResolver, Vc as makeConnectionsFacade, Ru as makeCoordinatedScheduler, vl as makeDataLoader, qc as makeDisconnectConnectionExecutor, Ho as makeEffectStoreLayer, xs as makeEventPublisher, fs as makeEventsFacade, li as makeFieldCipher, Fi as makeFluentStore, Zd as makeIdleGate, ts as makeLazyWorkflowFacade, Wc as makeListConnectionsExecutor, Da as makeMutationOutputCodec, Uf as makeMutationRunner, Yf as makeOneShotQueryRunner, Rs as makeOutboxFacade, $o as makePostCommitWorkflowFacade, qd as makeProcessAdapter, Jf as makeQueryDescriptorProducer, qf as makeQueryReauthorizer, Xf as makeQuerySubscriber, Qd as makeRouterActivity, jl as makeSchemaRegistry, Gc as makeStartConnectionExecutor, Kc as makeSubmitTokenExecutor, qu as makeUndoCapture, $d as makeWakeGate, nf as makeWakeProxyServer, Qo as makeWorkflowFacade, es as makeWorkflowFacadeWithCallerContext, ns as makeWorkflowHandlers, rs as makeWorkflowLayers, Go as makeWorkflowRunHandle, vu as markWakeupFired, kd as materializeIvm, Ao as memoryApiKeyStore, su as memoryReplicationAdapter, Ji as memoryRywPositionStore, pu as nextFiring, Tu as nextWakeup, Yd as nodeProcessSupervisor, mf as noopAnalytics, _f as noopAnalyticsSpec, Co as noopKv, Ei as observeStore, wi as observedGraph, qr as onBindConnectionSubject, Fa as onProcessShutdown, Fs as outboxAttemptsTable, Ms as outboxTable, ni as parseTraceparent, Xo as payloadPropertyNames, Ki as powerOfTwoSelector, cp as previewInRollback, ac as projectConnectionState, Du as pruneWakeups, ys as publishEvent, tl as rebacPolicyGraph, sr as recordEventDelivered, cr as recordEventDropped, or as recordEventPublished, lr as recordEventSubscribers, ur as recordSample, hr as recordScheduleRun, mr as recordSubscriptionActive, fr as recordSubscriptionDelivery, Ci as recordTableAccess, Sd as recordTimelineEvent, gr as recordWorkflowRun, Bl as redactColumns, hd as redactRow, Xi as redisRywPositionStore, dd as redoUndoInvocation, mc as refreshAccessToken, Yr as registerConnectionStream, Ce as registerRetention, gu as registerWakeup, xu as releaseWakeup, qi as replicaHealth, ma as resetComputedQueryCacheWarnings, ir as resetEventMetricTagCacheForTests, Ti as resetObservedGraph, ao as resetSecretsBackend, wc as resolveConnection, zc as resolveConnectionForSubject, ou as resolveCurrentRegion, wn as resolveDependentTables, Mc as resolveRedirectUri, jd as resolveRescan, kr as resolveRowFilterScope, Ar as resolveRowFilterScopeFor, oo as resolveSecret, so as resolveSecretSync, uo as resolveSecretsBackend, fd as resolveTimelineMode, Te as retentionTtlMsFromEnv, _d as reverseEventOverRows, sl as revokedIds, iu as runAsSystem, af as runOrchestratorTick, Mf as runProvidedEffect, Ud as runReaction, of as runSingleNodeOrchestrator, Kd as runWakeLoop, Hf as runWithDeadlockRetry, Si as runWithObservedProcedure, dl as runWithRequestLoader, $i as runWithRoutingContext, ai as runWithTraceContext, jc as sanitizeRedirectTo, Lu as scheduleCoordinated, Gl as schemaPropertyNames, ql as serverOnlyLeaks, Lc as setConnectionResolver, di as setFieldCipher, Er as setRowFilter, io as setSecretsBackend, tu as setSystemStoreHandle, xd as setTimelineRecorderForTest, ml as setTupleSource, Xt as settleHandlerBody, To as sha256Hex, za as shutdownGraceMsFromEnv, Au as singleCoordinator, xr as snapshotMetrics, Sr as snapshotMetricsSync, Tl as ssrfGuardHttpClientLayer, wl as ssrfReason, ja as startRpcServer, Pu as startScheduler, sc as storeCredential, Fc as sweepExpiredGrants, Me as sweepRetention, Xu as synthesizeInverse, yl as tracingHttpClientLayer, is as triggerWorkflow, bu as tryClaimWakeup, Kr as unbindConnectionSubject, Uu as undoCaptureEnabled, cd as undoLogExecutor, Ef as useAggregate, ff as useAnalytics, ol as visibleRows, Gd as wakeDueOnce, Ff as withRowFilter, Uo as workflowToRpc, Ku as wrapCaptureStore, Ll as wrapStoreWithBootCodec, Gi as wrapStoreWithMixinBehaviour };
7669
+ export { To as API_KEYS_TABLE, Xc as AccessDenied, Mf as AggregateError, Bd as AggregateMaintainer, jf as AggregateNotFound, Nf as AggregateRegistry, Af as AggregateStale, _f as AnalyticsCapabilityNotSupported, gf as AnalyticsError, vf as AnalyticsSink, X as CONNECTIONS_TABLE, Ys as CONNECTION_GRANTS_TABLE, su as CircuitBreaker, au as CircuitOpen, vc as ConnectionNotConnected, ja as DEFAULT_MAX_RPC_BODY_BYTES, gc as DEFAULT_REFRESH_SKEW_MS, wr as DEFAULT_ROW_FILTER_RETRY, Lu as DORMANCY_WAKEUP_TENANT, Pi as DeleteBuilder, Ir as Dispatcher, Cs as EVENT_CLIENT_QUEUE_SIZE, ws as EVENT_LATEST_QUEUE_SIZE, Bo as EffectStore, vs as EventBus, Ac as GRANT_TTL_MS, yn as InMemoryDataStore, sn as IndexedMatcher, As as InstanceMembership, $t as LinearScanMatcher, p as MetricBoundaries, xf as NOOP_ANALYTICS_PROVIDER, Or as NO_ROW_FILTER, Di as NoRowFound, Ps as OUTBOX_ATTEMPTS_TABLE, Vs as OUTBOX_ATTEMPT_LOG_CAP, Y as OUTBOX_TABLE, Oi as OptimisticLockError, Yc as REBAC_ADMIN_SCOPE, _c as REFRESH_LEASE_MS, _p as RUNTIME_NAME, Xd as ReactionRateLimiter, ta as ReplicatedDataStore, Cr as RowFilterUnavailable, Iu as SCHEDULE_SUBJECT, zo as SYSTEM_SUBJECT, Mi as SelectBuilder, xl as SsrfBlockedError, Li as StoreOperationFailed, un as SubscriptionRegistry, Ri as TableValidationFailed, Ii as TenantScopeViolation, Ed as TimelineRecorder, ad as UndoBoundaryError, sd as UndoStack, Ni as UpdateBuilder, Ol as VOLTRO_AUDIT_MIXIN_ID, Al as VOLTRO_EXPIRES_MIXIN_ID, kl as VOLTRO_SOFT_DELETE_MIXIN_ID, jl as VOLTRO_TENANT_MIXIN_ID, Xo as WorkflowPayloadError, Zr as _connectionStreamCount, Qr as _resetConnectionSubjectsForTest, Zs as _voltroConnectionGrantsTable, Js as _voltroConnectionsTable, Vd as _voltroRebacTuplesTable, Ju as _voltroScheduleClaimsTable, qu as _voltroScheduleRunsTable, Yu as _voltroTracesTable, Xu as _voltroUndoLogTable, Qd as _voltroWakeupsTable, fs as _voltroWorkflowEventDeliveriesTable, ds as _voltroWorkflowEventsTable, Wi as actingUserId, Ro as apiKeyManagementRoutes, Vi as applyDefined, Rd as applyDelta, ld as applyInverse, ud as applyInverses, ru as applyPluginRefRules, Mr as applyRowFilter, Nr as applyRowFilterToDescriptor, Rf as applySoftDeleteScope, Ff as applyTenantScope, vd as applyUndoInvocation, ol as assertCan, tc as assertConnectionCipherConfigured, Df as attachAnalyticsMirror, Ua as awaitServerListening, Bs as backoffMs, Pc as beginOAuthConnect, Wr as bindConnectionSubject, Ds as bindEvent, Aa as bindMutation, ya as bindStream, va as bindSubscription, pa as bindSubscriptionUntyped, Id as buildIvmState, mp as buildPreview, Wd as buildRebacInterceptor, Kd as buildRebacReadFilter, Yi as buildSubjectKey, Ja as buildTracingLayer, Xl as cacheScopeLeaks, lo as cachedBackend, al as can, Tu as cancelWakeup, cn as canonicalize, Md as classifyShape, Sc as clearConnectionRefreshFlights, tl as clearResourcePolicies, ee as clearRetentions, uu as clearSystemStoreHandle, iu as collectPluginRefRules, bu as compileCron, Fc as completeOAuthConnect, wf as composeAnalytics, Cf as composeAnalyticsSinks, jc as connectionCallbackPath, ec as connectionLabel, $r as connectionSubjectsSnapshot, ff as countRunningWorkflows, _r as counter, Gl as crud, dl as currentRequestLoader, ea as currentRoutingContext, oi as currentTraceContext, Fo as dataStoreApiKeyStore, _o as dataStoreIdempotencyStore, So as dataStoreKvStore, mi as decryptField, Of as defineAggregate, $s as defineConnection, os as defineEventTrigger, zf as defineExecutor, Ls as defineOutboxHandler, qd as defineReaction, Qc as defineResourcePolicy, yu as defineSchedule, hf as defineSubscriber, Pr as deliveredRowCount, si as deriveKey, pp as diffChange, Va as drainForShutdown, Gs as drainOutbox, Mu as dueWakeups, il as effectiveRelations, Il as emptySchemaRegistry, bi as enableGraphObservation, pi as encryptField, ul as enterRequestLoader, ro as envSecretsBackend, ar as eventMetricTagCacheSizeForTests, mc as exchangeAuthorizationCode, ri as externalSpanFromTraceparent, xn as extractDbCause, ln as fingerprintFor, uc as forgetCredential, Zl as formatCacheScopeLeaks, Yl as formatServerOnlyLeaks, ti as formatTraceparent, eu as formatUnresolvedSources, cd as forwardChangeFromCdc, Io as frameworkApiKeyStrategy, vr as gauge, Do as generateApiKeyToken, zc as getConnectionResolver, Gr as getConnectionSubject, q as getFieldCipher, $c as getResourcePolicy, Dr as getRowFilter, du as getSystemStoreHandle, Od as getTimelineRecorder, gl as getTupleSource, $ as groupKeyOf, yr as histogramMetric, dp as historyProvenance, uo as httpSecretsBackend, Xt as inspectWorkflow, _l as installPolicyGuardResolver, Xr as interruptConnectionStreams, rd as invertChange, kf as isAggregateDefinition, If as isEmptyTenantScopedRead, Sn as isForeignKeyViolation, af as isIdleNow, Ta as isInfraError, xi as isObservingGraph, Lf as isOrglessUserSubject, Cn as isQueryTimeout, od as isSafeToApply, _u as isScheduleDefinition, tu as isSoftDelete, ss as isWorkflowEventTriggerDefinition, Fd as ivmValue, up as lastWriteProvenance, dc as listConnectionStates, el as listResourcePolicies, pe as listRetentions, Hd as loadResourceTuples, Gd as loadSubjectTuples, pu as localityAwareSelector, ap as makeActionRunner, Bu as makeAdvisoryLockCoordinator, ci as makeAesCipher, Ao as makeApiKeyService, Dl as makeApiKeyUsageBuffer, Po as makeApiKeyUsageFlusher, wn as makeAppAccess, Co as makeAsyncKv, Es as makeBufferGapDetector, no as makeBufferingSpanProcessor, nc as makeConnectionRegistry, Vc as makeConnectionResolver, Hc as makeConnectionsFacade, Ku as makeCoordinatedScheduler, yl as makeDataLoader, Jc as makeDisconnectConnectionExecutor, Uo as makeEffectStoreLayer, Ss as makeEventPublisher, ps as makeEventsFacade, li as makeFieldCipher, Fi as makeFluentStore, of as makeIdleGate, ns as makeLazyWorkflowFacade, Gc as makeListConnectionsExecutor, Oa as makeMutationOutputCodec, Zf as makeMutationRunner, rp as makeOneShotQueryRunner, zs as makeOutboxFacade, es as makePostCommitWorkflowFacade, tf as makeProcessAdapter, np as makeQueryDescriptorProducer, tp as makeQueryReauthorizer, ip as makeQuerySubscriber, sf as makeRouterActivity, Ml as makeSchemaRegistry, Kc as makeStartConnectionExecutor, qc as makeSubmitTokenExecutor, td as makeUndoCapture, cf as makeWakeGate, df as makeWakeProxyServer, $o as makeWorkflowFacade, ts as makeWorkflowFacadeWithCallerContext, rs as makeWorkflowHandlers, is as makeWorkflowLayers, Ko as makeWorkflowRunHandle, Eu as markWakeupFired, Ld as materializeIvm, jo as memoryApiKeyStore, hu as memoryReplicationAdapter, Ji as memoryRywPositionStore, xu as nextFiring, Nu as nextWakeup, rf as nodeProcessSupervisor, Sf as noopAnalytics, Tf as noopAnalyticsSpec, wo as noopKv, Ei as observeStore, wi as observedGraph, qr as onBindConnectionSubject, Ia as onProcessShutdown, Is as outboxAttemptsTable, Ns as outboxTable, ni as parseTraceparent, Zo as payloadPropertyNames, Ki as powerOfTwoSelector, gp as previewInRollback, oc as projectConnectionState, Fu as pruneWakeups, bs as publishEvent, nl as rebacPolicyGraph, sr as recordEventDelivered, cr as recordEventDropped, or as recordEventPublished, lr as recordEventSubscribers, ur as recordSample, hr as recordScheduleRun, mr as recordSubscriptionActive, fr as recordSubscriptionDelivery, Ci as recordTableAccess, Ad as recordTimelineEvent, gr as recordWorkflowRun, Vl as redactColumns, Cd as redactRow, Xi as redisRywPositionStore, yd as redoUndoInvocation, hc as refreshAccessToken, Yr as registerConnectionStream, Ce as registerRetention, wu as registerWakeup, ku as releaseWakeup, qi as replicaHealth, ha as resetComputedQueryCacheWarnings, ir as resetEventMetricTagCacheForTests, Ti as resetObservedGraph, oo as resetSecretsBackend, Tc as resolveConnection, Bc as resolveConnectionForSubject, mu as resolveCurrentRegion, Tn as resolveDependentTables, Nc as resolveRedirectUri, zd as resolveRescan, kr as resolveRowFilterScope, Ar as resolveRowFilterScopeFor, so as resolveSecret, co as resolveSecretSync, fo as resolveSecretsBackend, bd as resolveTimelineMode, Te as retentionTtlMsFromEnv, Td as reverseEventOverRows, cl as revokedIds, nu as rulesFor, fu as runAsSystem, pf as runOrchestratorTick, Bf as runProvidedEffect, Zd as runReaction, mf as runSingleNodeOrchestrator, ef as runWakeLoop, Xf as runWithDeadlockRetry, Si as runWithObservedProcedure, fl as runWithRequestLoader, $i as runWithRoutingContext, ai as runWithTraceContext, Mc as sanitizeRedirectTo, Gu as scheduleCoordinated, Kl as schemaPropertyNames, Jl as serverOnlyLeaks, Rc as setConnectionResolver, di as setFieldCipher, Er as setRowFilter, ao as setSecretsBackend, lu as setSystemStoreHandle, kd as setTimelineRecorderForTest, hl as setTupleSource, Qt as settleHandlerBody, Eo as sha256Hex, Ba as shutdownGraceMsFromEnv, Ru as singleCoordinator, xr as snapshotMetrics, Sr as snapshotMetricsSync, El as ssrfGuardHttpClientLayer, Tl as ssrfReason, Ma as startRpcServer, Hu as startScheduler, cc as storeCredential, Ic as sweepExpiredGrants, Me as sweepRetention, id as synthesizeInverse, bl as tracingHttpClientLayer, as as triggerWorkflow, Ou as tryClaimWakeup, Kr as unbindConnectionSubject, Zu as undoCaptureEnabled, gd as undoLogExecutor, $l as unresolvedSources, Pf as useAggregate, bf as useAnalytics, sl as visibleRows, $d as wakeDueOnce, Uf as withRowFilter, Wo as workflowToRpc, ed as wrapCaptureStore, Rl as wrapStoreWithBootCodec, Gi as wrapStoreWithMixinBehaviour };