@voltro/cli 0.47.0 → 0.49.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.
Files changed (101) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/dist/{apiBuild-FpHCWiv6.js → apiBuild-QmYHaCF4.js} +1 -1
  3. package/dist/apiBuild-dZbHdqMg.js +2 -0
  4. package/dist/bin.js +1 -1
  5. package/dist/{build-zVygXxGB.js → build-Bi4O_g7T.js} +6 -6
  6. package/dist/{checkCommand-D0dAKciE.js → checkCommand-D8vjQXQt.js} +3 -3
  7. package/dist/{checkCommand-B2Fw73lu.js → checkCommand-udbQpphy.js} +1 -1
  8. package/dist/{codegenCommand-BTtsnRus.js → codegenCommand-DApSH7hK.js} +39 -46
  9. package/dist/{codemodRunner-DSZjgyCL.js → codemodRunner-De1_316I.js} +562 -492
  10. package/dist/{commands-BrFKxnYW.js → commands-a5PxCaIg.js} +68 -60
  11. package/dist/{dashboardCommand-D9SjDc8E.js → dashboardCommand-DaoUUqJS.js} +1 -1
  12. package/dist/dataCommand-CJv_OMoS.js +1156 -0
  13. package/dist/dataProfile-Du3ztYxv.js +51 -0
  14. package/dist/{dbCommand-jbrmzwW_.js → dbCommand-Bf7Cy0mn.js} +5 -5
  15. package/dist/dbCommand-Bnl7MSGC.js +2 -0
  16. package/dist/declaredSchemaGates-BlcwObhb.js +25 -0
  17. package/dist/{dev-RjB7eE_B.js → dev-C31Nvlbv.js} +31 -30
  18. package/dist/{dev-CaIfZnw5.js → dev-DFVuzOj7.js} +1 -1
  19. package/dist/{doctorCommand-D7X29cw6.js → doctorCommand-B3uraeAe.js} +32 -14
  20. package/dist/doctorCommand-CPL6EhrW.js +2 -0
  21. package/dist/doctorDecidedSchema-BlbWgCD_.js +23 -0
  22. package/dist/{dormancyCommand-BGOP27fz.js → dormancyCommand-QUXQ9yoz.js} +1 -1
  23. package/dist/{embeddingsCommand-D72E22bw.js → embeddingsCommand-Zw1-rYSF.js} +1 -1
  24. package/dist/{envCommand-BHSxz6wC.js → envCommand-DtaJ4xEf.js} +1 -1
  25. package/dist/{evolveCommand-C2ofGGlz.js → evolveCommand-JDD3hE1i.js} +2 -2
  26. package/dist/{frameworkTableAssembly-BvZ0Lil_.js → frameworkTableAssembly-BwJVEKLr.js} +96 -119
  27. package/dist/frameworkTableAssembly-CVDB2hCq.js +2 -0
  28. package/dist/index.js +1 -1
  29. package/dist/{infoCommand-CuNl9cbh.js → infoCommand-COsUC1DB.js} +1 -1
  30. package/dist/{migrate-odCPGHPq.js → migrate-D3MK9BpK.js} +4 -4
  31. package/dist/{runtimeTrace-C_OKr0jY.js → runtimeTrace-Di6fcndp.js} +1 -1
  32. package/dist/{sdkgen-D9trW7sl.js → sdkgen-CIi5gM17.js} +1 -1
  33. package/dist/serveCommand-CzSDngKm.js +2 -0
  34. package/dist/serveCommand-N3udT49p.js +2362 -0
  35. package/dist/serveEntry.js +5 -5
  36. package/dist/{subcommandNames-CKG5Dz3a.js → subcommandNames-DpYs3DXr.js} +12 -2
  37. package/dist/{updateCommand-BlyXavoG.js → updateCommand-2BfbeMvp.js} +1 -1
  38. package/dist/updateCommand-CtYm7aKH.js +2 -0
  39. package/dist/{webhooksCommand-BqcWcbuW.js → webhooksCommand-CwX9IzvJ.js} +1 -1
  40. package/package.json +29 -17
  41. package/templates/AGENTS.md +1 -1
  42. package/templates/agent-docs/_index.md +1 -1
  43. package/templates/agent-docs/cli.md +117 -4
  44. package/templates/agent-docs/database/migrations.md +19 -5
  45. package/templates/agent-docs/whats-new.md +51 -14
  46. package/templates/apps/api-ai/package.json +7 -7
  47. package/templates/apps/api-auth/package.json +8 -8
  48. package/templates/apps/api-backend/package.json +7 -7
  49. package/templates/apps/api-backend-deactivation/package.json +7 -7
  50. package/templates/apps/api-backend-mail/package.json +8 -8
  51. package/templates/apps/api-backend-mariadb/package.json +9 -9
  52. package/templates/apps/api-backend-sqlite/package.json +8 -8
  53. package/templates/apps/api-backend-storage/package.json +8 -8
  54. package/templates/apps/api-cms/package.json +10 -10
  55. package/templates/apps/api-collab/package.json +8 -8
  56. package/templates/apps/api-data-advanced/package.json +8 -8
  57. package/templates/apps/api-durable/package.json +8 -8
  58. package/templates/apps/api-feature-flags/package.json +9 -9
  59. package/templates/apps/api-governance/package.json +8 -8
  60. package/templates/apps/api-kv/package.json +8 -8
  61. package/templates/apps/api-moderation/package.json +8 -8
  62. package/templates/apps/api-observability/package.json +8 -8
  63. package/templates/apps/api-ratelimit/package.json +8 -8
  64. package/templates/apps/api-rbac/package.json +8 -8
  65. package/templates/apps/api-rest/package.json +7 -7
  66. package/templates/apps/api-saas/package.json +11 -11
  67. package/templates/apps/api-saas-starter/package.json +10 -10
  68. package/templates/apps/api-search/package.json +8 -8
  69. package/templates/apps/api-status/package.json +8 -8
  70. package/templates/apps/api-versioning/package.json +8 -8
  71. package/templates/apps/api-webhooks/package.json +9 -9
  72. package/templates/apps/changelog/package.json +6 -6
  73. package/templates/apps/edge-functions/package.json +2 -2
  74. package/templates/apps/frontend-admin/package.json +8 -8
  75. package/templates/apps/frontend-app/package.json +9 -9
  76. package/templates/apps/frontend-auth/package.json +8 -8
  77. package/templates/apps/frontend-blank/package.json +7 -7
  78. package/templates/apps/frontend-cms/package.json +9 -9
  79. package/templates/apps/frontend-collab/package.json +10 -10
  80. package/templates/apps/frontend-contact/package.json +7 -7
  81. package/templates/apps/frontend-dashboard/package.json +7 -7
  82. package/templates/apps/frontend-docs/package.json +7 -7
  83. package/templates/apps/frontend-i18n/package.json +6 -6
  84. package/templates/apps/frontend-landing/package.json +7 -7
  85. package/templates/apps/frontend-portal/package.json +8 -8
  86. package/templates/apps/frontend-saas/package.json +8 -8
  87. package/templates/apps/frontend-spa/package.json +7 -7
  88. package/templates/apps/frontend-ssr/package.json +7 -7
  89. package/templates/apps/frontend-ssr-api/package.json +8 -8
  90. package/templates/apps/frontend-static-blog/package.json +6 -6
  91. package/templates/apps/frontend-status/package.json +8 -8
  92. package/templates/apps/mobile-app/package.json +4 -4
  93. package/dist/apiBuild-BsooZpw2.js +0 -2
  94. package/dist/dataCommand-Dl11q14e.js +0 -975
  95. package/dist/dataProfile-Cm0YVKSy.js +0 -18
  96. package/dist/dbCommand-BUD4Fd8v.js +0 -2
  97. package/dist/doctorCommand-5zv6PN-G.js +0 -2
  98. package/dist/frameworkTableAssembly-DDKtwsy2.js +0 -2
  99. package/dist/serveCommand-BU0wfV6V.js +0 -1931
  100. package/dist/serveCommand-Bwrn_9Fn.js +0 -2
  101. package/dist/updateCommand-CT5AvVg7.js +0 -2
@@ -1,1931 +0,0 @@
1
- import { t as e } from "./nodeEnvironment-cGFAj1J8.js";
2
- import { t } from "./frameworkInspectState-CX2250XB.js";
3
- import { r as n, t as r } from "./appModuleLoader-C9r9mxZt.js";
4
- import { t as i } from "./bootRefusal-pgvDxlrU.js";
5
- import { n as a, r as o } from "./startupRunner-CEqQq7ax.js";
6
- import { t as ee } from "./interruptedReplace-C1ZI84xi.js";
7
- import { $ as s, $t as c, A as l, At as u, Bt as d, C as f, Cn as p, Ct as m, D as h, Dt as g, E as _, En as te, Et as v, F as ne, Ft as re, G as ie, Gt as ae, H as y, Ht as oe, I as se, It as ce, J as le, Jt as b, K as x, Kt as ue, L as S, Lt as de, M as fe, Mt as pe, N as me, Nt as he, O as ge, Ot as _e, P as ve, Pt as ye, Q as be, Qt as xe, R as C, Rt as Se, S as Ce, St as we, T as Te, Tn as Ee, Tt as w, U as De, V as Oe, W as ke, Wt as Ae, X as je, Xt as Me, Y as Ne, Yt as T, Z as Pe, Zt as Fe, _ as E, _n as Ie, _t as D, an as Le, at as Re, b as ze, bn as Be, bt as Ve, c as He, cn as Ue, ct as We, dn as Ge, dt as Ke, en as qe, et as Je, f as Ye, fn as Xe, ft as Ze, g as Qe, gt as $e, h as et, hn as tt, ht as nt, i as rt, in as it, it as at, j as ot, jt as st, k as ct, kt as lt, ln as ut, lt as dt, m as ft, mn as pt, mt, nn as ht, nt as gt, o as O, on as _t, ot as k, p as A, pn as vt, pt as yt, q as bt, qt as xt, r as St, rn as Ct, rt as wt, sn as j, st as Tt, t as Et, tn as Dt, tt as Ot, u as kt, un as At, ut as jt, v as Mt, vn as Nt, vt as M, w as N, wn as Pt, wt as Ft, x as It, xn as Lt, xt as Rt, y as zt, yn as Bt, yt as Vt, zt as Ht } from "./dev-RjB7eE_B.js";
8
- import { n as Ut } from "./cliArgs-D4p8n7EE.js";
9
- import { r as P } from "./appPort-B_HpJ_ck.js";
10
- import { ht as Wt, pt as Gt } from "./webDev-B4IEMB0n.js";
11
- import { r as F } from "./dialectDriver-czCHYpeH.js";
12
- import { i as Kt, n as qt } from "./connectionConfig-Bk9IC7D0.js";
13
- import { c as Jt, n as I, o as Yt } from "./seedRunner-Dgsiwk_e.js";
14
- import { C as Xt, S as Zt, _ as Qt, d as $t, g as en, l as tn, m as nn, r as rn, u as an, v as on } from "./frameworkTableAssembly-BvZ0Lil_.js";
15
- import { S as sn, c as cn, n as ln, p as un, s as dn, x as fn } from "./fileConventions-Cof68_BL.js";
16
- import { h as pn, o as mn } from "./inspect-B7U7Cl_Z.js";
17
- import { n as hn } from "./mssqlClusterPatch-_4cE_nun.js";
18
- import { i as gn, n as _n, r as vn, t as yn } from "./webhookDiscovery-CphsQe59.js";
19
- import { t as bn } from "./inspectMetrics-CfdKLh6t.js";
20
- import { r as xn, u as Sn } from "./apiBuild-FpHCWiv6.js";
21
- import { t as Cn } from "./bootTiming-BdyP9nYw.js";
22
- import { t as wn } from "./dataProfile-Cm0YVKSy.js";
23
- import Tn, { basename as En, join as Dn } from "node:path";
24
- import { createWriteStream as On, existsSync as kn } from "node:fs";
25
- import { pathToFileURL as An } from "node:url";
26
- import { createLogger as L } from "@voltro/logger";
27
- import { AuthMiddleware as jn, ConnectionInfoMiddleware as Mn, actionToRpc as R, anonymousSubject as Nn, isWireReachable as Pn, mutationToRpc as Fn, queryToRpc as z, streamToRpc as In, wireErrorUnion as Ln, workflowCancelDescriptor as Rn, workflowDomainEventsQueryDescriptor as B, workflowEventDeliveriesQueryDescriptor as V, workflowResumeDescriptor as zn, workflowRunEventsQueryDescriptor as Bn, workflowRunQueryDescriptor as Vn, workflowRunStepsQueryDescriptor as Hn, workflowRunsQueryDescriptor as Un, workflowSignalDescriptor as Wn, workflowUpdateDescriptor as Gn } from "@voltro/protocol";
28
- import { allRegisteredTables as Kn, and as H, connectionIdentity as qn, ensureTableRegistered as Jn, eq as U, or as Yn } from "@voltro/database";
29
- import { Cause as Xn, Effect as W, Layer as G, ManagedRuntime as Zn } from "effect";
30
- import { SqlClient as Qn } from "@effect/sql";
31
- import { declaredSnapshot as $n, describeOutcome as er, pendingFileMigrationIds as tr, runPlannedMigrations as nr } from "@voltro/database/sql";
32
- import { AggregateRegistry as rr, CostRegistry as ir, DORMANCY_WAKEUP_TENANT as ar, Dispatcher as or, ExpectationRegistry as sr, ExperimentRegistry as cr, apiKeyManagementRoutes as lr, attachAnalyticsMirror as ur, attachExpectations as dr, attachExperiments as fr, attachFinops as pr, awaitServerListening as mr, bindMutation as K, bindStream as hr, bindSubscription as q, buildTracingLayer as gr, cancelWakeup as _r, compileCron as vr, dataStoreApiKeyStore as yr, formatServerOnlyLeaks as br, formatUnresolvedSources as xr, frameworkApiKeyStrategy as Sr, getResourcePolicy as Cr, installPolicyGuardResolver as wr, loadResourceTuples as Tr, makeActionRunner as Er, makeAdvisoryLockCoordinator as Dr, makeApiKeyService as Or, makeApiKeyUsageBuffer as kr, makeApiKeyUsageFlusher as Ar, makeAsyncKv as jr, makeAuthMiddlewareLayers as Mr, makeCoordinatedScheduler as Nr, makeEffectStoreLayer as Pr, makeLazyWorkflowFacade as Fr, makeMutationOutputCodec as Ir, makeMutationRunner as Lr, makeOneShotQueryRunner as Rr, makeQueryDescriptorProducer as zr, makeQueryFinalizer as Br, makeQueryReauthorizer as Vr, makeQuerySubscriber as Hr, makeSchemaRegistry as Ur, makeWorkflowFacade as J, makeWorkflowFacadeWithCallerContext as Wr, makeWorkflowLayers as Gr, noopKv as Kr, onProcessShutdown as qr, recordSubscriptionDelivery as Jr, recordWorkflowRun as Yr, registerDefaultTupleSource as Xr, registerWakeup as Zr, resolveSecretsBackend as Qr, runProvidedEffect as Y, setSecretsBackend as $r, setSystemStoreHandle as ei, shutdownGraceMsFromEnv as ti, singleCoordinator as ni, startRpcServer as ri, startScheduler as ii, stripForbiddenForWire as ai, undoCaptureEnabled as oi, unresolvedSources as si, withScopedRequest as ci, workflowToRpc as li, wrapStoreWithBootCodec as ui } from "@voltro/runtime";
33
- import di, { tmpdir as fi } from "node:os";
34
- import { RpcGroup as pi } from "@effect/rpc";
35
- import { appStorageProvider as mi, durabilityNotice as hi, fromNodeReadable as gi, getObjectStream as _i, putObjectStream as vi, toNodeReadable as yi } from "@voltro/plugin-storage";
36
- import { isEnvContract as bi } from "@voltro/env";
37
- import { assertProductionSessionSecret as xi } from "@voltro/protocol/session";
38
- import X from "node:fs/promises";
39
- import { createHash as Si, timingSafeEqual as Ci } from "node:crypto";
40
- import { buildDeliverWebhookExecute as wi, buildWebhooksService as Ti, defaultIncomingPath as Ei, deliverWebhookWorkflow as Di, makeDeferredEmitHandler as Oi, mountIncomingWebhook as ki } from "@voltro/plugin-webhooks";
41
- import { getAuthSessionStrategy as Ai } from "@voltro/plugin-auth";
42
- import { registerEmailTemplates as ji } from "@voltro/plugin-mail";
43
- import { channelFor as Mi, getBroadcastPlugin as Ni } from "@voltro/plugin-broadcast";
44
- import { packBundle as Pi, runExport as Fi, runImport as Ii, storageBlobSink as Li, storageRefsBlobSource as Ri, unpackBundle as zi, unpackBundleToDir as Bi } from "@voltro/data-transfer";
45
- //#region src/serveDrain.ts
46
- var Vi = () => Math.max(500, Math.floor(ti() * .6)), Hi = (e) => new Promise((t) => setTimeout(t, e)), Ui = (e) => {
47
- let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), r = 0;
48
- e.on("connection", (e) => {
49
- t.add(e), e.once("close", () => {
50
- t.delete(e), n.delete(e);
51
- });
52
- }), e.on("upgrade", (e, t) => {
53
- n.add(t);
54
- }), e.on("request", (e, t) => {
55
- r += 1, t.once("close", () => {
56
- --r;
57
- });
58
- });
59
- let i, a = async (t = {}) => {
60
- let n = t.budgetMs ?? Vi();
61
- i ??= new Promise((t) => {
62
- e.close(() => {
63
- t();
64
- });
65
- }), e.closeIdleConnections();
66
- let a = Date.now() + n;
67
- for (; r > 0 && Date.now() < a;) await Hi(25), e.closeIdleConnections();
68
- e.closeIdleConnections();
69
- }, o = async () => {
70
- i ??= new Promise((t) => {
71
- e.close(() => {
72
- t();
73
- });
74
- });
75
- for (let e of t) if (n.has(e)) try {
76
- e.write(Buffer.from([
77
- 136,
78
- 2,
79
- 3,
80
- 233
81
- ]));
82
- } catch {}
83
- else e.destroy();
84
- for (let e = 0; t.size > 0 && e < 250; e += 25) await Hi(25);
85
- for (let e of t) e.destroy();
86
- await i;
87
- };
88
- return {
89
- activeRequests: () => r,
90
- drainRequests: a,
91
- finish: o,
92
- drain: async (e = {}) => {
93
- await a(e), await o();
94
- }
95
- };
96
- }, Wi = "/_voltro/admin/import", Gi = "/_voltro/admin/export", Z = (e, t) => ({
97
- status: e,
98
- contentType: "application/json; charset=utf-8",
99
- body: JSON.stringify(t)
100
- }), Ki = (e) => {
101
- let t = e.authorization ?? e.Authorization, n = t ? /^Bearer\s+(.+)$/i.exec(t) : null;
102
- return n ? n[1] : null;
103
- }, qi = (e, t) => Ci(Si("sha256").update(e).digest(), Si("sha256").update(t).digest()), Ji = (e, t) => {
104
- if (e.method.toUpperCase() !== "POST") return Z(405, { error: "method not allowed" });
105
- if (!t || t.length < 16) return Z(503, { error: "data transfer misconfigured (no/weak secret)" });
106
- let n = Ki(e.headers);
107
- return !n || !qi(n, t) ? Z(401, { error: "unauthorized" }) : null;
108
- }, Yi = /^[A-Za-z0-9_-]{8,64}$/, Xi = (e) => Yi.test(e), Zi = () => Tn.join(di.tmpdir(), "voltro-import-uploads"), Qi = (e) => Tn.join(Zi(), e), $i = (e) => Tn.join(Qi(e), "archive.bin"), ea = (e) => Tn.join(Qi(e), "meta.json"), ta = async (e = Date.now()) => {
109
- let t = 0;
110
- try {
111
- for (let n of await X.readdir(Zi())) {
112
- let r = await X.stat(Qi(n)).catch(() => null);
113
- r !== null && (e - r.mtimeMs <= 864e5 || (await X.rm(Qi(n), {
114
- recursive: !0,
115
- force: !0
116
- }).catch(() => void 0), t++));
117
- }
118
- } catch {}
119
- return t;
120
- }, na = async (e) => {
121
- if (!Xi(e)) return {
122
- bytes: 0,
123
- key: null
124
- };
125
- let t = await X.stat($i(e)).catch(() => null);
126
- if (t === null) return {
127
- bytes: 0,
128
- key: null
129
- };
130
- let n = await X.readFile(ea(e), "utf8").then((e) => JSON.parse(e), () => ({}));
131
- return {
132
- bytes: t.size,
133
- key: n.key ?? null
134
- };
135
- }, ra = async (e) => {
136
- if (!Xi(e.id)) return {
137
- reason: "bad-id",
138
- message: `upload id must match ${String(Yi)}`
139
- };
140
- let t = await na(e.id);
141
- return t.key !== null && t.key !== e.key ? {
142
- reason: "key-mismatch",
143
- message: "this upload id already holds a different bundle. Use a new upload id, or delete the partial upload."
144
- } : e.offset === t.bytes ? (await X.mkdir(Qi(e.id), { recursive: !0 }), t.key === null && await X.writeFile(ea(e.id), JSON.stringify({
145
- key: e.key,
146
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
147
- })), await new Promise((t, n) => {
148
- let r = On($i(e.id), { flags: "a" });
149
- r.on("error", n), r.on("finish", () => t()), r.end(Buffer.from(e.bytes));
150
- }), { total: t.bytes + e.bytes.byteLength }) : {
151
- reason: "offset-mismatch",
152
- message: `chunk starts at ${e.offset} but the server holds ${t.bytes} byte(s)`,
153
- expectedOffset: t.bytes
154
- };
155
- }, ia = async (e) => {
156
- let t = await X.stat($i(e));
157
- return {
158
- path: $i(e),
159
- bytes: t.size
160
- };
161
- }, aa = async (e) => {
162
- Xi(e) && await X.rm(Qi(e), {
163
- recursive: !0,
164
- force: !0
165
- }).catch(() => void 0);
166
- }, Q = L({ scope: "voltro:admin-import" }), oa = "VBUNDLE2", sa = (e) => {
167
- let t = e.req.headers["x-import-rollback-key"];
168
- if (e.mode !== "replace") return { options: {} };
169
- if (typeof t != "string" || t.length === 0) return Q.warn("admin.import: no rollback capture — this run empties the target first, and nothing was asked to be kept. Send `x-import-rollback-key: <storage key>` (voltro data import --rollback-key <key>) to have the instance store the target's current rows before deleting them."), { options: {} };
170
- if (e.deps.putArchive === void 0) return {
171
- options: {},
172
- refusal: Z(409, {
173
- error: "rollback capture requested but this instance has no object storage configured",
174
- hint: "A capture written to the pod would not survive the failure it exists for. Configure storage (the same one the storage-push export uses), or re-send without `x-import-rollback-key` to accept that a run which does not finish can leave the target emptied. Note that CONFIGURED is not the same question as SURVIVES: a `filesystem` provider pointed at a container directory with no volume behind it passes this check and dies with the pod. The run says so when it can observe it — the capture path being on the same filesystem as `/`."
175
- })
176
- };
177
- let n = Dn(fi(), `voltro-rollback-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`), r = e.deps.putArchive;
178
- return {
179
- key: t,
180
- options: {
181
- rollbackDir: n,
182
- onRollbackCaptured: async () => {
183
- let e = hi(n);
184
- e !== void 0 && Q.warn(`admin.import: ${e}`), await r(t, () => Pi({ dir: n })), Q.info("admin.import: rollback capture stored", { bundleKey: t });
185
- }
186
- }
187
- };
188
- }, ca = async function* (e) {
189
- yield e;
190
- }, la = (e) => async (t) => {
191
- let n = Ji(t, e.secret);
192
- if (n) return n;
193
- let r = t.headers["x-import-mode"], i = t.headers["x-import-on-conflict"], a = t.headers["x-import-atomic"], o = a === "0" || a === "false" ? !1 : a === "1" || a === "true" || r === "replace", ee = t.headers["x-import-force"] === "1" || t.headers["x-import-force"] === "true", s = sa({
194
- req: t,
195
- mode: r,
196
- deps: e
197
- });
198
- if (s.refusal !== void 0) return s.refusal;
199
- let c = t.headers["x-import-dry-run"] === "1" || t.headers["x-import-dry-run"] === "true", l = (t.headers["x-import-tables"] ?? "").split(",").map((e) => e.trim()).filter(Boolean), u = t.headers["x-import-upload-id"], d;
200
- if (u !== void 0 && u !== "") {
201
- if (ta(), t.headers["x-import-probe"] === "1") return Z(200, {
202
- uploadId: u,
203
- bytes: (await na(u)).bytes
204
- });
205
- let e = t.headers["x-import-upload-key"] ?? "", n = Number(t.headers["x-import-chunk-offset"] ?? "0");
206
- if (e === "" || !Number.isFinite(n) || n < 0) return Z(400, { error: "a chunked upload needs x-import-upload-key and a numeric x-import-chunk-offset" });
207
- let r = await ra({
208
- id: u,
209
- key: e,
210
- offset: n,
211
- bytes: t.rawBody
212
- });
213
- if ("reason" in r) return Q.warn("admin.import chunk refused", {
214
- uploadId: u,
215
- reason: r.reason
216
- }), Z(409, {
217
- error: "chunk refused",
218
- reason: r.reason,
219
- message: r.message,
220
- ...r.expectedOffset === void 0 ? {} : { expectedOffset: r.expectedOffset }
221
- });
222
- if (t.headers["x-import-chunk-final"] !== "1") return Z(202, {
223
- uploadId: u,
224
- bytes: r.total
225
- });
226
- d = (await ia(u)).path;
227
- }
228
- let f = t.rawBody.byteLength >= 8 && Buffer.from(t.rawBody.subarray(0, 8)).toString("latin1") === oa, p, m;
229
- if (d !== void 0) {
230
- let { createReadStream: e } = await import("node:fs");
231
- p = e(d), m = "chunked";
232
- } else if (f) p = ca(t.rawBody), m = "upload";
233
- else {
234
- let n;
235
- try {
236
- n = JSON.parse(Buffer.from(t.rawBody).toString("utf8") || "{}");
237
- } catch {
238
- return Z(400, { error: "body must be a packed bundle archive or { bundleKey } JSON" });
239
- }
240
- if (typeof n.bundleKey != "string" || !n.bundleKey) return Z(400, { error: "body.bundleKey (string) is required for the storage transport" });
241
- if (!e.openArchive) return Z(501, { error: "storage transport not configured on this instance" });
242
- p = e.openArchive(n.bundleKey), m = "storage";
243
- }
244
- let h = await import("node:os"), g = await import("node:fs/promises"), _ = await import("node:path"), te = await g.mkdtemp(_.join(h.tmpdir(), "voltro-admin-import-"));
245
- try {
246
- e.assetSink ? await zi(p, {
247
- dir: te,
248
- blobs: e.assetSink
249
- }) : await Bi(p, te);
250
- let t = await W.runPromiseExit(Ii({
251
- store: e.store,
252
- bundleDir: te,
253
- ...r ? { mode: r } : {},
254
- ...i ? { onConflict: i } : {},
255
- atomic: o,
256
- ...s.options,
257
- recordInterruption: !0,
258
- via: "api",
259
- ...c ? { dryRun: c } : {},
260
- ...l.length > 0 ? { tables: l } : {},
261
- ...e.snapshot ? { targetSnapshot: e.snapshot } : {},
262
- ...e.dialect ? { targetDialect: e.dialect } : {},
263
- force: ee,
264
- onWarn: (e) => Q.warn("admin.import", { message: e }),
265
- ...e.assetSink ? { assetsAlreadyRestored: !0 } : {}
266
- }));
267
- if (t._tag === "Failure") {
268
- let e = t.cause._tag === "Fail" ? t.cause.error : void 0;
269
- if (e && e._tag === "SchemaDriftError") {
270
- let t = e;
271
- return Q.warn("admin.import refused (schema drift)", {
272
- transport: m,
273
- bundle: t.bundleFingerprint.slice(0, 16),
274
- target: t.targetFingerprint.slice(0, 16)
275
- }), Z(409, {
276
- error: "schema drift",
277
- bundleFingerprint: t.bundleFingerprint,
278
- targetFingerprint: t.targetFingerprint,
279
- diff: t.diff,
280
- hint: "each line above would break the load: a table or column the bundle carries that the target cannot take, or a column the target requires that the bundle has no value for. Fix the target schema, re-export against it, or resend with x-import-force: 1 to write anyway."
281
- });
282
- }
283
- let n = typeof e?.reason == "string" ? e.reason : void 0;
284
- if (n !== void 0 && e._tag === "ImportModeError") return Q.warn("admin.import refused (mode)", {
285
- transport: m,
286
- mode: e.mode
287
- }), Z(409, {
288
- error: "import mode refused",
289
- mode: e.mode,
290
- message: n
291
- });
292
- throw Error(n ?? String(e?.message ?? e ?? "import failed"));
293
- }
294
- let n = t.value, a = n.manifest.tables.reduce((e, t) => e + t.rowCount, 0), u = n.rowsWritten;
295
- return Q.info(c ? "admin.import (dry run — nothing written)" : "admin.import", {
296
- transport: m,
297
- tables: n.tablesWritten,
298
- rows: u,
299
- carried: a,
300
- mode: r ?? "upsert",
301
- atomic: o,
302
- ...n.tablesSkipped > 0 ? {
303
- skippedTables: n.tablesSkipped,
304
- skippedRows: n.rowsSkipped
305
- } : {}
306
- }), c || e.refreshSubscriptions?.(`data import: ${n.tablesWritten} table(s), mode ${r ?? "upsert"}`), Z(200, {
307
- tables: n.tablesWritten,
308
- rows: u,
309
- carried: a,
310
- transport: m,
311
- ...n.tablesSkipped > 0 ? {
312
- skippedTables: n.tablesSkipped,
313
- skippedRows: n.rowsSkipped,
314
- fullyResumed: n.fullyResumed
315
- } : {},
316
- ...c ? {
317
- dryRun: !0,
318
- wrote: !1
319
- } : {}
320
- });
321
- } catch (e) {
322
- return Q.warn("admin.import failed", {
323
- transport: m,
324
- error: e?.message ?? String(e)
325
- }), Z(500, {
326
- error: "import failed",
327
- message: e?.message ?? String(e)
328
- });
329
- } finally {
330
- await g.rm(te, {
331
- recursive: !0,
332
- force: !0
333
- }), u !== void 0 && u !== "" && d !== void 0 && await aa(u);
334
- }
335
- }, ua = L({ scope: "voltro:admin-export" }), da = async (e) => {
336
- let t = [];
337
- for await (let n of e) t.push(Buffer.from(n));
338
- return new Uint8Array(Buffer.concat(t));
339
- }, fa = (e) => typeof e.tenant == "string" && e.tenant ? {
340
- kind: "tenant",
341
- tenantId: e.tenant
342
- } : Array.isArray(e.tables) && e.tables.length ? {
343
- kind: "tables",
344
- tables: e.tables.filter((e) => typeof e == "string")
345
- } : { kind: "all" }, pa = (e) => async (t) => {
346
- let n = Ji(t, e.secret);
347
- if (n) return n;
348
- let r;
349
- try {
350
- r = JSON.parse(Buffer.from(t.rawBody).toString("utf8") || "{}");
351
- } catch {
352
- return Z(400, { error: "body must be JSON: { profile?, tenant?, tables?, consistency?, compression?, bundleKey? }" });
353
- }
354
- let i = {};
355
- if (typeof r.profile == "string" && r.profile) {
356
- if (!e.loadProfile) return Z(501, { error: "server-side profiles not configured on this instance" });
357
- try {
358
- i = await e.loadProfile(r.profile);
359
- } catch (e) {
360
- return Z(400, {
361
- error: `profile '${r.profile}' could not be loaded`,
362
- message: e?.message ?? String(e)
363
- });
364
- }
365
- }
366
- let a = r.consistency === "snapshot" ? "snapshot" : i.consistency ?? "live", o = (typeof r.compression == "string" ? r.compression : void 0) ?? i.compression, ee = i.scope ?? fa(r), s = typeof r.bundleKey == "string" && r.bundleKey.length > 0, c = r.assets === !0 && e.assetSource ? { blobs: e.assetSource } : {}, l = await import("node:os"), u = await import("node:fs/promises"), d = await import("node:path"), f = await u.mkdtemp(d.join(l.tmpdir(), "voltro-admin-export-"));
367
- try {
368
- let t = await W.runPromise(Fi({
369
- store: e.store,
370
- snapshot: e.snapshot,
371
- dialect: e.dialect,
372
- outDir: f,
373
- ...i.subset ? { subset: i.subset } : {
374
- scope: ee,
375
- ...e.tenantTables && e.tenantTables.length > 0 ? { tenantTables: e.tenantTables } : {}
376
- },
377
- consistency: a,
378
- ...o ? { compression: o } : {},
379
- ...i.masking ? { masking: i.masking } : {}
380
- })), n = t.tables.reduce((e, t) => e + t.rowCount, 0), l = t.masking?.transformed.length ?? 0;
381
- if (s) {
382
- if (!e.putArchive) return Z(501, { error: "storage transport not configured on this instance" });
383
- let i = r.bundleKey;
384
- return await e.putArchive(i, () => Pi({
385
- dir: f,
386
- ...c
387
- })), ua.info("admin.export", {
388
- transport: "storage",
389
- tables: t.tables.length,
390
- rows: n,
391
- masked: l,
392
- bundleKey: i
393
- }), Z(200, {
394
- bundleKey: i,
395
- tables: t.tables.length,
396
- rows: n,
397
- masked: l,
398
- transport: "storage"
399
- });
400
- }
401
- let u = await da(Pi({
402
- dir: f,
403
- ...c
404
- }));
405
- return ua.info("admin.export", {
406
- transport: "download",
407
- tables: t.tables.length,
408
- rows: n,
409
- masked: l,
410
- bytes: u.byteLength
411
- }), {
412
- status: 200,
413
- contentType: "application/octet-stream",
414
- body: u,
415
- headers: {
416
- "x-export-tables": String(t.tables.length),
417
- "x-export-rows": String(n),
418
- "x-export-masked": String(l)
419
- }
420
- };
421
- } catch (e) {
422
- return ua.warn("admin.export failed", { error: e?.message ?? String(e) }), Z(500, {
423
- error: "export failed",
424
- message: e?.message ?? String(e)
425
- });
426
- } finally {
427
- await u.rm(f, {
428
- recursive: !0,
429
- force: !0
430
- });
431
- }
432
- }, ma = (e, t, n = {}) => (async function* () {
433
- let r = await W.runPromise(_i(e, t).pipe(W.timeout(n.openTimeout ?? "30 seconds"))), i = await yi(r.stream), a = n.stallMs ?? 12e4, o, ee = () => {
434
- o && clearTimeout(o), o = setTimeout(() => i.destroy(/* @__PURE__ */ Error(`storage read stalled for ${a}ms reading '${t}'`)), a);
435
- };
436
- try {
437
- ee();
438
- for await (let e of i) ee(), yield e instanceof Uint8Array ? e : new Uint8Array(e);
439
- } finally {
440
- o && clearTimeout(o), i.destroy();
441
- }
442
- })(), ha = {
443
- get: async () => void 0,
444
- set: async () => {},
445
- setWithTags: async () => {},
446
- remove: async () => !1,
447
- has: async () => !1,
448
- clear: async () => {},
449
- invalidateTag: async () => 0,
450
- wrap: async (e, t, n) => n()
451
- }, ga = async (e) => {
452
- d(e.appProcedures ?? e.discovered, {
453
- defaultDeny: e.security?.defaultDeny ?? !0,
454
- commandHint: "`voltro serve`"
455
- }), ei({
456
- dataStore: e.store,
457
- schemaRegistry: e.schemaRegistry
458
- });
459
- let t = (e.discovered.budgets?.length ?? 0) > 0, n, r = new or({
460
- store: e.store,
461
- ...e.snapshotCache ? { cache: e.snapshotCache } : {},
462
- ...e.reactive === void 0 ? {} : { reactive: e.reactive },
463
- ...t ? { recordCost: (e) => n?.record(e) } : {},
464
- recordDelivery: (e) => Jr({
465
- label: e.label,
466
- kind: e.kind,
467
- durationMs: e.durationMs,
468
- rowCount: e.rowCount
469
- })
470
- }), i = e.cache ?? ha, a = e.kv ?? Kr, o, ee = () => void 0, c, l, u, f, p, m, h, _ = ue({
471
- store: e.store,
472
- warn: (e, t) => {
473
- process.stderr.write(`[workflow] ${e} ${JSON.stringify(t)}\n`);
474
- }
475
- }), te = _.remember, ae = _.resolve, oe = xt({
476
- authority: e.authority,
477
- getStore: () => e.store
478
- }), S = (e.discovered.workflows?.length ?? 0) > 0 ? Fr(() => o) : void 0, de = (e.discovered.workflows?.length ?? 0) > 0 || (e.discovered.eventTriggers?.length ?? 0) > 0, he = de || (e.discovered.workflowWorkers?.length ?? 0) > 0 || e.scheduleCoordination === "cluster", ge = e.tenantIsolation === "namespace", _e = (e.log ?? L({ scope: "voltro:serve" })).child("webhooks"), ve, ye, C = e.discovered.webhooks;
479
- if (C && C.outgoing.length > 0 && e.workflowEngineLayer !== void 0) {
480
- e.workflowEngineLayer;
481
- let t = ut({
482
- store: e.store,
483
- schemaRegistry: e.schemaRegistry,
484
- cache: i,
485
- kv: a
486
- }), n = C.outgoing.map((e) => e.descriptor);
487
- ye = Di.toLayer(wi(t, { events: n })), ve = Ti(t, async (e) => {
488
- let t = u;
489
- if (t === void 0) {
490
- _e.error("webhook delivery skipped — the workflow runtime was never built. This is a framework defect, not a configuration problem: report it with your engine setting. Deliveries are NOT queued and will not be retried.", {
491
- deliveryId: e.deliveryId,
492
- targetId: e.targetId
493
- });
494
- return;
495
- }
496
- t.runPromise(Di.execute(e)).catch((t) => {
497
- _e.error("deliverWebhook workflow crashed", {
498
- deliveryId: e.deliveryId,
499
- targetId: e.targetId
500
- }, t);
501
- });
502
- }, { events: n });
503
- }
504
- let Se = /* @__PURE__ */ new Map();
505
- if (C) for (let e of C.incoming) {
506
- let t = e.descriptor.path ?? Ei(e.descriptor.id), n = `VOLTRO_WEBHOOK_SECRET_${e.descriptor.id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`, r = ki(e.descriptor, {
507
- resolveSecret: async () => process.env[n] ?? null,
508
- resolveWorkflows: () => S === void 0 ? void 0 : Wr(S, {
509
- traceId: `incoming:${e.descriptor.id}`,
510
- source: `incoming:${e.descriptor.id}`
511
- }),
512
- log: (e) => {
513
- let t = {
514
- webhookId: e.webhookId,
515
- status: e.status,
516
- signatureOk: String(e.signatureOk),
517
- idempotency: e.idempotency,
518
- durationMs: e.durationMs
519
- };
520
- e.status >= 500 ? _e.error("incoming delivery failed", t) : e.status >= 400 ? _e.warn("incoming delivery rejected", t) : _e.info("incoming delivery handled", t);
521
- }
522
- });
523
- Se.set(t, { handle: r });
524
- }
525
- wr(), Xr((t) => Tr(e.store, t.subjectId, t.resourceType, t.resourceId)) || L({ scope: "voltro:serve" }).info("policy guards: using the app-registered tuple source");
526
- let Ce = [], Te = [...e.discovered.outboxHandlers ?? [], ..._n((C?.outgoing.length ?? 0) + (C?.incoming.length ?? 0) + (C?.providers.length ?? 0), []) ? [{
527
- file: "<framework>/webhooks",
528
- id: "voltro-webhook-emit",
529
- definition: Oi(() => ve)
530
- }] : []], Ee = Te.length > 0 ? Fe({
531
- handlers: Te,
532
- store: e.store,
533
- log: (e.log ?? L({ scope: "voltro:serve" })).child("outbox"),
534
- onChange: (t) => e.store.onChange((e) => t({
535
- table: e.table,
536
- op: e.op
537
- })),
538
- onShutdown: (e) => {
539
- Ce.push(e);
540
- }
541
- }) : void 0, w = T({
542
- definitions: (e.discovered.connections ?? []).map((e) => e.definition),
543
- store: e.store,
544
- publicUrl: b(e.port ?? 4e3),
545
- log: (e.log ?? L({ scope: "voltro:serve" })).child("connections")
546
- });
547
- ot({
548
- events: e.discovered.events ?? [],
549
- rpcTags: [
550
- ...e.discovered.queries.map((e) => e.descriptor.name),
551
- ...e.discovered.mutations.map((e) => e.descriptor.name),
552
- ...e.discovered.actions.map((e) => e.descriptor.name),
553
- ...(e.discovered.streams ?? []).map((e) => e.descriptor.name)
554
- ]
555
- });
556
- let Ae = (e.log ?? L({ scope: "voltro:serve" })).child("events"), je = e.broadcastNamespace ?? Qe(e.plugins, void 0), Me = E(e.plugins, je, Ae), Ne = e.membership?.instanceId ?? process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, Ie = e.membership ?? Mt(e.plugins, {
557
- instanceId: Ne,
558
- namespace: je,
559
- meta: { mode: "serve" },
560
- logger: Ae
561
- }), D = fe({
562
- events: e.discovered.events ?? [],
563
- origin: Ne,
564
- ...Me.publishRemote === void 0 ? {} : { publishRemote: Me.publishRemote }
565
- }), Le = (e.discovered.events ?? []).length > 0 ? await Me.attach(D.bus) : null, Re = Ue({
566
- store: e.store,
567
- schemaRegistry: e.schemaRegistry,
568
- cache: i,
569
- kv: a,
570
- ...ve === void 0 ? {} : { webhooksService: ve },
571
- ...S === void 0 ? {} : { workflowsProxy: S },
572
- eventTriggers: e.discovered.eventTriggers ?? [],
573
- namespaceIsolationOn: ge,
574
- ...e.ensureTenantProvisioned === void 0 ? {} : { ensureTenantProvisioned: e.ensureTenantProvisioned },
575
- ...e.resolveResidentStore === void 0 ? {} : { resolveResidentStore: e.resolveResidentStore },
576
- ...Ee === void 0 ? {} : { outbox: { nudge: Ee.nudge } },
577
- ...w.active ? { connections: { registry: w.registry } } : {},
578
- eventBus: D.bus
579
- }), ze = G.succeed(rr, g), Be = G.succeed(sr, Rt), He = G.succeed(ir, Ve), Ge = G.succeed(cr, we), qe = (t, n) => {
580
- let r = t.pipe(W.provide(Pr(n)));
581
- return (e.baseLayer ? r.pipe(W.provide(e.baseLayer)) : r).pipe(W.provide(ze)).pipe(W.provide(Be)).pipe(W.provide(He)).pipe(W.provide(Ge));
582
- }, Ye = (e, t) => {
583
- let n = qe(e, t);
584
- return Y(n);
585
- }, Xe = bn(), et = le(e.plugins ?? [], Xe), tt = Oe({
586
- plugins: e.plugins ?? [],
587
- metrics: Xe,
588
- log: e.log ?? L({ scope: "voltro:serve" })
589
- }), nt = x(e.plugins ?? [], Xe), rt = e.security?.defaultDeny ?? !0, at = Lr({
590
- store: e.store,
591
- defaultDeny: rt,
592
- recordMetric: (e) => {
593
- Xe.record(e);
594
- },
595
- ...et.mutation === void 0 ? {} : { interceptor: et.mutation },
596
- buildContext: (e, t, n) => Re(e, t, n),
597
- runEffect: Ye,
598
- undoCapture: s()
599
- }), ct = be();
600
- {
601
- let t = Je();
602
- t !== void 0 && (e.log ?? L({ scope: "voltro:serve" })).info(t);
603
- }
604
- let lt = Pe({
605
- store: e.store,
606
- ...e.approvals === void 0 ? {} : { defaultExpiryMs: e.approvals.defaultExpiryMs }
607
- }), ft = Er({
608
- defaultDeny: rt,
609
- buildContext: (e) => Re(e),
610
- runEffect: Ye,
611
- recordMetric: (e) => {
612
- Xe.record(e);
613
- },
614
- ...et.action === void 0 ? {} : { interceptor: et.action }
615
- }), pt = Br({
616
- tenantScopedTables: e.tenantScopedTables,
617
- softDeleteScopedTables: e.softDeleteScopedTables
618
- }), mt = {
619
- defaultDeny: rt,
620
- buildContext: (e) => Re(e),
621
- finalize: (e, t) => pt(e, t.subject),
622
- provideEffect: qe,
623
- ...et.query === void 0 ? {} : { interceptor: et.query }
624
- }, gt = zr(mt), O = Rr({
625
- ...mt,
626
- queryRows: (t, n) => e.store.query(t).then((e) => ai(t.table, e, n.subject))
627
- }), _t = Hr({
628
- ...mt,
629
- subscribeDescriptor: (e, t, n) => r.subscribe(e, t, n),
630
- subscribeComputed: (e, t, n) => r.subscribeComputed(e, t, n)
631
- }), k = (e) => e.filter((e) => Pn(e.descriptor)), A = {};
632
- for (let t of [
633
- ...k(e.discovered.queries),
634
- ...ct.queries,
635
- ...lt.queries,
636
- ...w.queries
637
- ]) A[t.descriptor.name] = (e) => q(gt(t, e), r, `subscription.${t.descriptor.name}`, void 0, void 0, Vr(t, e));
638
- for (let t of [
639
- ...k(e.discovered.mutations),
640
- ...ct.mutations,
641
- ...lt.mutations,
642
- ...w.mutations
643
- ]) {
644
- let n = Ir(t.descriptor.output);
645
- A[t.descriptor.name] = (r) => K(async (e, n) => at(t, e, n), r, `mutation.${t.descriptor.name}`, n, e.idempotency, Ln(t.descriptor, "mutation"));
646
- }
647
- for (let t of [...k(e.discovered.actions), ...w.actions]) {
648
- let n = Ir(t.descriptor.output);
649
- A[t.descriptor.name] = (r) => K(async (e, n) => ft(t, e, n), r, `action.${t.descriptor.name}`, n, e.idempotency, Ln(t.descriptor, "action"));
650
- }
651
- let vt = () => `public-${Math.random().toString(36).slice(2, 10)}`, yt = [
652
- ...e.discovered.queries.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
653
- descriptor: e.descriptor,
654
- invoke: (t, n) => O(e, t, {
655
- subject: n.subject,
656
- traceId: vt()
657
- }),
658
- subscribe: (t, n, r) => _t(e, t, {
659
- subject: n.subject,
660
- traceId: vt()
661
- }, r)
662
- })),
663
- ...e.discovered.mutations.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
664
- descriptor: e.descriptor,
665
- invoke: (t, n) => at(e, t, {
666
- subject: n.subject,
667
- traceId: vt()
668
- })
669
- })),
670
- ...e.discovered.actions.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
671
- descriptor: e.descriptor,
672
- invoke: (t, n) => ft(e, t, {
673
- subject: n.subject,
674
- traceId: vt()
675
- })
676
- }))
677
- ], bt = {
678
- candidates: ce({
679
- queries: e.discovered.queries,
680
- mutations: e.discovered.mutations,
681
- actions: e.discovered.actions,
682
- descriptorOf: (e) => e.descriptor,
683
- runQuery: (e, t, n) => Promise.resolve(O(e, t, n)),
684
- runMutation: (e, t, n) => Promise.resolve(at(e, t, n)),
685
- runAction: (e, t, n) => Promise.resolve(ft(e, t, n))
686
- }),
687
- policy: e.agents?.tools ?? {},
688
- mcpEnabled: e.agents?.mcp === !0,
689
- resolveSubject: (t) => e.resolveSubject(t, -1).then((e) => e.subject)
690
- }, St = ht({
691
- ...e.restRoutes === void 0 ? {} : { restRoutes: e.restRoutes },
692
- publicApiEntries: yt,
693
- store: e.store,
694
- resolveSubject: (t) => e.resolveSubject(t, -1).then((e) => e.subject),
695
- ...e.idempotency === void 0 ? {} : { idempotency: e.idempotency },
696
- log: e.log ?? L({ scope: "voltro:serve" })
697
- }), Ct = e.dataTransferSecret ?? process.env.VOLTRO_DATA_TRANSFER_SECRET, wt = async (e, t) => {
698
- let { Readable: n } = await import("node:stream"), r = mi(), i = gi("storage", () => n.from(t()));
699
- await W.runPromise(vi(r, e, i, { contentType: "application/octet-stream" }));
700
- }, Tt = Ct && Ct.length >= 16 ? [{
701
- method: "POST",
702
- path: Wi,
703
- handle: la({
704
- secret: Ct,
705
- store: e.store,
706
- ...e.dataTransferSnapshot ? { snapshot: e.dataTransferSnapshot } : {},
707
- ...e.dataTransferDialect ? { dialect: e.dataTransferDialect } : {},
708
- assetSink: Li(mi()),
709
- openArchive: (e) => ma(mi(), e),
710
- refreshSubscriptions: (e) => {
711
- r.refreshAll(e);
712
- },
713
- putArchive: wt,
714
- ...e.dataTransferDialect ? { dialect: e.dataTransferDialect } : {}
715
- })
716
- }, {
717
- method: "POST",
718
- path: Gi,
719
- handle: pa({
720
- secret: Ct,
721
- store: e.store,
722
- snapshot: e.dataTransferSnapshot ?? { tables: [] },
723
- dialect: e.dataTransferDialect ?? "memory",
724
- tenantTables: [...e.tenantScopedTables],
725
- loadProfile: wn,
726
- assetSource: Ri(mi(), e.store),
727
- putArchive: wt
728
- })
729
- }] : [], Et = [
730
- ...e.httpRoutes ?? [],
731
- ...St.httpRoutes,
732
- ...Tt,
733
- ...w.httpRoutes
734
- ];
735
- Object.assign(A, D.handlers);
736
- for (let t of k(e.discovered.streams ?? [])) A[t.descriptor.name] = (n) => hr((r) => ci(r, (r) => {
737
- let i = Re(r), a = t.executor(n, i);
738
- if (W.isEffect(a)) {
739
- let t = a.pipe(W.provide(Pr(i.store)));
740
- return (e.baseLayer ? t.pipe(W.provide(e.baseLayer)) : t).pipe(W.provide(ze)).pipe(W.provide(Be)).pipe(W.provide(He)).pipe(W.provide(Ge));
741
- }
742
- return typeof a == "object" && a && typeof a.then == "function" ? W.promise(() => a) : a;
743
- }), `stream.${t.descriptor.name}`);
744
- for (let t of e.discovered.workflows ?? []) A[t.definition.name] = (e) => K(async (e, n) => {
745
- let r = n;
746
- return Wr(S, {
747
- subject: r.subject,
748
- traceId: r.traceId,
749
- source: "workflow-rpc"
750
- }).start(t.definition.name, e);
751
- }, e, `workflow.${t.definition.name}`);
752
- de && (A[Vn.name] = (e) => q(gt({
753
- descriptor: Vn,
754
- executor: (e) => {
755
- let t = e.id;
756
- return {
757
- table: "_voltro_workflow_runs",
758
- order: [{
759
- column: "startedAt",
760
- direction: "desc"
761
- }],
762
- predicate: Yn(U("id", t), U("executionId", t)),
763
- take: 1,
764
- skip: void 0,
765
- projection: void 0
766
- };
767
- }
768
- }, e), r, `subscription.${Vn.name}`), A[Un.name] = (e) => q(gt({
769
- descriptor: Un,
770
- executor: (e) => {
771
- let t = e, n = [...t.tag === void 0 ? [] : [U("tag", t.tag)], ...t.status === void 0 ? [] : [U("status", t.status)]], r = Number.isFinite(t.limit) && t.limit !== void 0 ? Math.min(Math.max(Math.floor(t.limit), 1), 500) : 100;
772
- return {
773
- table: "_voltro_workflow_runs",
774
- order: [{
775
- column: "startedAt",
776
- direction: "desc"
777
- }],
778
- predicate: n.length === 0 ? void 0 : n.length === 1 ? n[0] : H(...n),
779
- take: r,
780
- skip: void 0,
781
- projection: void 0
782
- };
783
- }
784
- }, e), r, `subscription.${Un.name}`), A[Hn.name] = (e) => q(gt({
785
- descriptor: Hn,
786
- executor: (e) => {
787
- let t = e.runId;
788
- return {
789
- table: "_voltro_workflow_run_steps",
790
- order: [{
791
- column: "startedAt",
792
- direction: "asc"
793
- }],
794
- predicate: U("runId", t),
795
- take: 1e3,
796
- skip: void 0,
797
- projection: void 0
798
- };
799
- }
800
- }, e), r, `subscription.${Hn.name}`), A[Bn.name] = (e) => q(gt({
801
- descriptor: Bn,
802
- executor: (e) => {
803
- let t = e.runId;
804
- return {
805
- table: "_voltro_workflow_run_events",
806
- order: [{
807
- column: "occurredAt",
808
- direction: "asc"
809
- }],
810
- predicate: U("runId", t),
811
- take: 1e3,
812
- skip: void 0,
813
- projection: void 0
814
- };
815
- }
816
- }, e), r, `subscription.${Bn.name}`), A[B.name] = (e) => q(gt({
817
- descriptor: B,
818
- executor: (e) => {
819
- let t = e;
820
- return {
821
- table: "_voltro_workflow_events",
822
- order: [{
823
- column: "occurredAt",
824
- direction: "desc"
825
- }],
826
- predicate: t.name === void 0 ? void 0 : U("name", t.name),
827
- take: Math.max(1, Math.min(500, t.limit ?? 100)),
828
- skip: void 0,
829
- projection: void 0
830
- };
831
- }
832
- }, e), r, `subscription.${B.name}`), A[V.name] = (e) => q(gt({
833
- descriptor: V,
834
- executor: (e) => {
835
- let t = e.eventId;
836
- return {
837
- table: "_voltro_workflow_event_deliveries",
838
- order: [{
839
- column: "createdAt",
840
- direction: "asc"
841
- }],
842
- predicate: U("eventId", t),
843
- take: 500,
844
- skip: void 0,
845
- projection: void 0
846
- };
847
- }
848
- }, e), r, `subscription.${V.name}`), A[Rn.name] = (t) => K(async (t, n) => {
849
- let r = t;
850
- return await j(e.store, n.subject, { executionId: r.executionId }), await S.cancel(r.workflowName, r.executionId), await Ft(r.workflowName, r.executionId, "workflow.cancel"), { ok: !0 };
851
- }, t, `action.${Rn.name}`), A[zn.name] = (t) => K(async (t, n) => {
852
- let r = t;
853
- return await j(e.store, n.subject, { executionId: r.executionId }), await S.resume(r.workflowName, r.executionId), { ok: !0 };
854
- }, t, `action.${zn.name}`), A[Wn.name] = (t) => K(async (t, n) => {
855
- let r = t;
856
- return await j(e.store, n.subject, { id: r.id }), S.signal({ id: r.id }, r.signalName, r.payload);
857
- }, t, `action.${Wn.name}`), A[Gn.name] = (t) => K(async (t, n) => {
858
- let r = t;
859
- return await j(e.store, n.subject, { id: r.id }), S.update({ id: r.id }, r.updateName, r.payload, r.timeoutMs === void 0 ? void 0 : { timeoutMs: r.timeoutMs });
860
- }, t, `action.${Gn.name}`));
861
- let Dt = [
862
- ...k(e.discovered.queries).map((e) => z(e.descriptor)),
863
- ...k(e.discovered.mutations).map((e) => Fn(e.descriptor)),
864
- ...k(e.discovered.actions).map((e) => R(e.descriptor)),
865
- ...ct.queries.map((e) => z(e.descriptor)),
866
- ...ct.mutations.map((e) => Fn(e.descriptor)),
867
- ...lt.queries.map((e) => z(e.descriptor)),
868
- ...lt.mutations.map((e) => Fn(e.descriptor)),
869
- ...w.queries.map((e) => z(e.descriptor)),
870
- ...w.mutations.map((e) => Fn(e.descriptor)),
871
- ...w.actions.map((e) => R(e.descriptor)),
872
- ...k(e.discovered.streams ?? []).map((e) => In(e.descriptor)),
873
- ...D.rpcs,
874
- ...(e.discovered.workflows ?? []).map((e) => li(e.definition)),
875
- ...de ? [
876
- z(Vn),
877
- z(Un),
878
- z(Hn),
879
- z(Bn),
880
- z(B),
881
- z(V),
882
- R(Rn),
883
- R(zn),
884
- R(Wn),
885
- R(Gn)
886
- ] : []
887
- ], Ot = pi.make(...Dt).middleware(jn).middleware(Mn), kt = Mr({ resolveSubject: ({ headers: t, clientId: n }) => e.resolveSubject(t, n) }), At = e.dormancyTenantId ?? ar, Nt = e.dormancy === "sleep" ? {
888
- register: (t, n, r) => Zr(e.store, {
889
- tenantId: r ?? At,
890
- kind: "workflow",
891
- refId: t,
892
- wakeAt: n
893
- }),
894
- cancel: (t, n) => _r(e.store, {
895
- tenantId: n ?? At,
896
- kind: "workflow",
897
- refId: t
898
- }).then(() => {})
899
- } : void 0, M = he ? await import("@voltro/workflow") : void 0, N = M?.makeWorkflowRunRecorder({
900
- store: e.store,
901
- ...e.workflowRecording === void 0 ? {} : { recording: e.workflowRecording },
902
- ...Nt === void 0 ? {} : { wakeups: Nt }
903
- }), Pt = async (t, n) => {
904
- await M.closeWorkflowChildrenForParent({
905
- store: e.store,
906
- parentExecutionId: t,
907
- parentStatus: n,
908
- recorder: N,
909
- log: { warn: (e, t) => {
910
- process.stderr.write(`[workflow] ${e} ${t ? JSON.stringify(t) : ""}\n`);
911
- } },
912
- interruptChild: async (t, n) => {
913
- let r = (e.discovered.workflows ?? []).find((e) => e.definition.name === t);
914
- if (!r) throw Error(`Unknown child workflow: ${t}`);
915
- if (!u) throw Error("Workflow runtime is not ready");
916
- await u.runPromise(r.definition.interrupt(n));
917
- }
918
- });
919
- }, Ft = async (t, n, r) => {
920
- let i = (await e.store.query({
921
- table: "_voltro_workflow_runs",
922
- order: [],
923
- predicate: U("executionId", n),
924
- projection: void 0,
925
- skip: void 0,
926
- take: 1
927
- }))[0];
928
- if (i === void 0) return;
929
- let a = await e.store.update("_voltro_workflow_runs", i.id, {
930
- status: "cancelled",
931
- cancelled: !0,
932
- completedAt: /* @__PURE__ */ new Date()
933
- }), o = i.subject?.tenantId ?? void 0;
934
- a && await N.recordEvent({
935
- runId: i.id,
936
- eventType: "run-cancelled",
937
- payload: {
938
- reason: r,
939
- workflowName: t,
940
- executionId: n,
941
- ...o == null ? {} : { tenantId: o }
942
- }
943
- }), a && await Pt(n, "cancelled");
944
- }, It = [
945
- ...Gr(e.discovered.workflows ?? [], {
946
- buildContext: (t, n) => e.buildContextForWorkflow?.(t, n) ?? Re({
947
- subject: t.subject,
948
- traceId: t.traceId
949
- }, e.store, void 0, `workflow:${n.workflowName}`, { parentExecutionId: n.executionId }),
950
- resolveStartContext: ae,
951
- ...oe === void 0 ? {} : { resolveAuthority: oe }
952
- }, (t, n, r) => {
953
- let i = M.getWorkflowVersionMetadata(t.definition);
954
- return M.wrapWorkflowExecuteWithRunRecording({
955
- name: t.definition.name,
956
- store: e.store,
957
- subject: r.subject,
958
- source: r.source ?? null,
959
- traceId: r.traceId,
960
- workflowVersion: i.version,
961
- workflowCompatibleVersions: i.compatibleWith,
962
- workflowPatches: i.patches,
963
- parentExecutionId: r?.parentExecutionId ?? null,
964
- parentClosePolicy: r?.parentClosePolicy ?? null,
965
- onParentClose: ({ executionId: e, status: t }) => Pt(e, t),
966
- ...dt(t.definition),
967
- onTerminal: async ({ executionId: e }) => {
968
- await l?.gate.release(e);
969
- },
970
- recorder: N,
971
- pluginWorkflowStepLayer: nt,
972
- recordRun: Yr
973
- }, n);
974
- }),
975
- ...e.discovered.workflowWorkers ?? [],
976
- ...ye === void 0 ? [] : [ye]
977
- ], Lt = [...(e.discovered.workflows ?? []).map((e) => e.definition.name).filter(Boolean), ...ye === void 0 ? [] : ["voltro.deliverWebhook"]], zt = It.length > 0 ? G.mergeAll(...It) : G.empty;
978
- if (((e.discovered.workflows?.length ?? 0) > 0 || (e.discovered.workflowWorkers?.length ?? 0) > 0 || e.scheduleCoordination === "cluster" || ye !== void 0) && e.workflowEngineLayer !== void 0) {
979
- let t = zt.pipe(G.provideMerge(e.workflowEngineLayer));
980
- u = Zn.make(e.baseLayer === void 0 ? t : t.pipe(G.provideMerge(e.baseLayer))), await u.runPromise(W.void), (e.log ?? L({ scope: "voltro:serve" })).child("workflow").info(`workflow runtime ready — ${Lt.length} entity type(s) registered`, { entities: Lt });
981
- let n = await import("@voltro/workflow/cluster"), r = (e) => u.runPromise(n.redriveFailedRun(e)), i = (e) => u.runPromise(n.resumeRunFromStep(e));
982
- m = await Bt({
983
- provider: Ni(e.plugins ?? [])?.broadcast?.provider,
984
- crossReplica: Ni(e.plugins ?? [])?.broadcast?.crossReplica ?? !1,
985
- namespace: je,
986
- replicaId: crypto.randomUUID(),
987
- pollStorage: () => u.runPromise(n.pollWorkflowStorage),
988
- onChange: (t) => e.store.onChange((e) => t({
989
- table: e.table,
990
- op: e.op,
991
- ...e.origin === void 0 ? {} : { origin: e.origin }
992
- })),
993
- log: (e.log ?? L({ scope: "voltro:serve" })).child("workflow")
994
- }), f = async (t) => {
995
- let n = await De({
996
- store: e.store,
997
- workflows: e.discovered.workflows ?? [],
998
- runRedrive: r
999
- }, t.runId);
1000
- return n.statusReset && await N.recordEvent({
1001
- runId: t.runId,
1002
- eventType: "run-redriven",
1003
- payload: {
1004
- reason: "inspect.redrive",
1005
- activitiesReset: n.outcome.activitiesReset
1006
- }
1007
- }), {
1008
- redriven: n.outcome.redriven,
1009
- activitiesReset: n.outcome.activitiesReset,
1010
- reason: n.outcome.reason
1011
- };
1012
- }, p = async (t) => {
1013
- let n = await ke({
1014
- store: e.store,
1015
- workflows: e.discovered.workflows ?? [],
1016
- runResume: i
1017
- }, t.runId, t.step);
1018
- return n.statusReset && await N.recordEvent({
1019
- runId: t.runId,
1020
- eventType: "run-redriven",
1021
- payload: {
1022
- reason: "inspect.resume-from-step",
1023
- step: n.stepName,
1024
- activitiesReset: n.outcome.activitiesReset
1025
- }
1026
- }), {
1027
- redriven: n.outcome.redriven,
1028
- stepName: n.stepName,
1029
- activitiesReset: n.outcome.activitiesReset,
1030
- reason: n.outcome.reason
1031
- };
1032
- };
1033
- let a = (e.scheduleCoordination ?? "single") === "advisoryLock" ? Dr(e.store, e.scheduleReplicaId ?? `pid-${process.pid}`) : ni, s = Nr({
1034
- coordinator: a,
1035
- replicaId: e.scheduleReplicaId ?? `pid-${process.pid}`
1036
- }), d = {
1037
- info: (e, t) => {
1038
- process.stdout.write(`[flow-control] ${e} ${t ? JSON.stringify(t) : ""}\n`);
1039
- },
1040
- warn: (e, t) => {
1041
- process.stderr.write(`[flow-control] ${e} ${t ? JSON.stringify(t) : ""}\n`);
1042
- },
1043
- error: (e, t) => {
1044
- process.stderr.write(`[flow-control] ERROR ${e} ${t ? JSON.stringify(t) : ""}\n`);
1045
- }
1046
- }, h, g = () => {
1047
- if (h !== void 0) return h;
1048
- if (o !== void 0 && N !== void 0) return h = ne({
1049
- store: e.store,
1050
- log: I,
1051
- workflows: e.discovered.workflows ?? [],
1052
- workflowsProxy: o,
1053
- workflowRuntime: u,
1054
- workflowRunRecorder: N,
1055
- closeChildrenForParent: Pt
1056
- }), h;
1057
- };
1058
- ee = g, l = $e({
1059
- store: e.store,
1060
- onChange: (t) => e.store.onChange((e) => t({
1061
- table: e.table,
1062
- op: e.op
1063
- })),
1064
- ...e.scheduling === void 0 ? {} : {
1065
- disarmWhenIdle: e.scheduling.disarmWhenIdle,
1066
- drainIntervalMs: e.scheduling.admissionDrainMs,
1067
- cancelSweepIntervalMs: e.scheduling.cancelSweepMs,
1068
- stalenessSweepIntervalMs: e.scheduling.stalenessSweepMs
1069
- },
1070
- workflows: e.discovered.workflows ?? [],
1071
- facade: () => o,
1072
- cancelRunWithReason: g,
1073
- recordRunEvent: () => N?.recordEvent,
1074
- ...e.workflowStaleness === void 0 ? {} : { staleness: e.workflowStaleness },
1075
- ...e.workflowSuspendSignalHintMs === void 0 ? {} : { suspendSignalHintMs: e.workflowSuspendSignalHintMs },
1076
- scheduleCoordinated: s,
1077
- onAbandoned: async (t) => {
1078
- await We({
1079
- workflows: e.discovered.workflows ?? [],
1080
- facade: () => o,
1081
- log: d,
1082
- ...t
1083
- });
1084
- },
1085
- log: d
1086
- });
1087
- let _ = l;
1088
- _ !== void 0 && qr(() => _.stop()), c = Ze({
1089
- store: e.store,
1090
- onChange: (t) => e.store.onChange((e) => t({
1091
- table: e.table,
1092
- op: e.op
1093
- })),
1094
- ...e.scheduling === void 0 ? {} : {
1095
- disarmWhenIdle: e.scheduling.disarmWhenIdle,
1096
- tickIntervalMs: e.scheduling.inferenceTickMs
1097
- },
1098
- enabled: (e.discovered.workflows?.length ?? 0) > 0,
1099
- resumeSignal: () => u === void 0 || M === void 0 ? void 0 : async ({ executionId: t, workflowName: n, signalName: r, payload: i }) => {
1100
- await u.runPromise(M.completeSuspendingSignal({
1101
- store: e.store,
1102
- target: Ke(t, n),
1103
- signalName: r,
1104
- payload: i
1105
- }));
1106
- },
1107
- runEffect: (e) => u.runPromise(e),
1108
- scheduleCoordinated: s,
1109
- log: d
1110
- });
1111
- let v = c;
1112
- v !== void 0 && qr(() => v.stop()), o = (e.discovered.workflows?.length ?? 0) > 0 ? J({
1113
- workflows: e.discovered.workflows ?? [],
1114
- runEffect: (e) => u.runPromise(e),
1115
- onEnqueue: () => m?.publishWake(),
1116
- ..._ === void 0 ? {} : {
1117
- admitStart: _.gate.admitStart,
1118
- startPayloadSchema: _.gate.startPayloadSchema,
1119
- parkDelayedStart: _.gate.parkDelayed
1120
- },
1121
- rememberStartContext: te,
1122
- signal: async (t, n, r) => {
1123
- let i = await M.sendWorkflowSignal({
1124
- store: e.store,
1125
- recorder: N,
1126
- target: t,
1127
- signalName: n,
1128
- payload: r
1129
- });
1130
- return await u.runPromise(M.completeSuspendingSignal({
1131
- store: e.store,
1132
- target: t,
1133
- signalName: n,
1134
- payload: r
1135
- })).catch(() => {}), i;
1136
- },
1137
- update: (t, n, r, i) => M.sendWorkflowUpdate({
1138
- store: e.store,
1139
- recorder: N,
1140
- target: t,
1141
- updateName: n,
1142
- payload: r,
1143
- ...i === void 0 ? {} : { options: i }
1144
- }),
1145
- listRuns: (t) => y(e.store, t),
1146
- retry: (t, n) => ie({
1147
- store: e.store,
1148
- workflows: e.discovered.workflows ?? [],
1149
- runPromise: (e) => u.runPromise(e)
1150
- }, t, n),
1151
- redrive: (t) => De({
1152
- store: e.store,
1153
- workflows: e.discovered.workflows ?? [],
1154
- runRedrive: r
1155
- }, t).then((e) => e.outcome)
1156
- }) : void 0;
1157
- }
1158
- let Vt = G.mergeAll(Ot.toLayer(A), kt), Ht = it(A, e.discovered.queries.map((e) => e.descriptor.name), de), Ut = G.mergeAll(Ot.toLayer(Ht), kt), P = e.observability, Wt = await gr({
1159
- ...e.appName === void 0 ? {} : { serviceName: e.appName },
1160
- ...P && P.spanProcessors.length > 0 ? { extraSpanProcessors: P.spanProcessors } : {},
1161
- ...P && P.metricReaders.length > 0 ? { extraMetricReaders: P.metricReaders } : {},
1162
- ...P && Object.keys(P.resourceAttributes).length > 0 ? { resourceAttributes: P.resourceAttributes } : {},
1163
- ...P && P.sampler !== void 0 ? { sampler: P.sampler } : {}
1164
- }), Gt = !1, F = e.store.ping ? () => e.store.ping().then(() => !0).catch(() => !1) : void 0, { server: Kt, shutdown: qt } = ri({
1165
- group: Ot,
1166
- handlersLayer: Vt,
1167
- httpHandlersLayer: Ut,
1168
- port: e.port ?? 4e3,
1169
- ...e.host === void 0 ? {} : { host: e.host },
1170
- path: e.path ?? "/ws",
1171
- tracerLayer: Wt.layer,
1172
- security: re(e),
1173
- ...tt,
1174
- healthCheck: {
1175
- isReady: () => Gt,
1176
- ...F ? { ping: F } : {}
1177
- },
1178
- ...Et.length > 0 ? { httpRoutes: Et } : {},
1179
- ...e.getStore === void 0 ? {} : { getStore: e.getStore },
1180
- ...Se.size > 0 ? { webhookRoutes: Se } : {},
1181
- ...e.inspectRoute === void 0 ? {} : { inspectRoute: e.inspectRoute }
1182
- }), Jt = Ui(Kt);
1183
- if (await mr(Kt), (e.discovered.schedules?.length ?? 0) > 0) {
1184
- let t = (e.scheduleCoordination ?? "single") === "advisoryLock" ? Dr(e.store, e.scheduleReplicaId ?? `pid-${process.pid}`) : ni;
1185
- h = await ii(e.discovered.schedules ?? [], {
1186
- store: e.store,
1187
- coordinator: t,
1188
- defaultTrigger: e.scheduleDefaultTrigger ?? "self",
1189
- replicaId: e.scheduleReplicaId ?? `pid-${process.pid}`,
1190
- armSelf: e.scheduleArmSelf ?? !0,
1191
- dormancy: e.dormancy ?? "always-on",
1192
- ...e.dormancyTenantId === void 0 ? {} : { dormancyTenantId: e.dormancyTenantId },
1193
- buildContext: ({ traceId: t, scheduleName: n, subject: r }) => Re({
1194
- subject: r,
1195
- traceId: t
1196
- }, e.store, void 0, `schedule:${n}`),
1197
- log: {
1198
- info: (e, t) => {
1199
- process.stdout.write(`[schedule] ${e} ${t ? JSON.stringify(t) : ""}\n`);
1200
- },
1201
- warn: (e, t) => {
1202
- process.stderr.write(`[schedule] ${e} ${t ? JSON.stringify(t) : ""}\n`);
1203
- },
1204
- error: (e, t) => {
1205
- process.stderr.write(`[schedule] ERROR ${e} ${t ? JSON.stringify(t) : ""}\n`);
1206
- },
1207
- debug: () => {}
1208
- },
1209
- ...e.scheduleFireInterceptor === void 0 ? {} : { interceptFire: e.scheduleFireInterceptor },
1210
- ...e.onScheduleRunEvent === void 0 ? {} : { onRunEvent: e.onScheduleRunEvent }
1211
- }), e.onSchedulerReady?.(h);
1212
- }
1213
- let I = e.log ?? L({ scope: "voltro:serve" }), Yt, Xt;
1214
- if ((e.discovered.subscribers?.length ?? 0) > 0 && (Yt = xe(e.discovered.subscribers ?? [], e.store, I.child("subscribe"), e.schemaRegistry, D.bus)), (e.discovered.reactions?.length ?? 0) > 0) {
1215
- let t = I.child("reaction"), n = async (n, r) => {
1216
- if (n.kind === "workflow") {
1217
- if (S === void 0) {
1218
- t.warn("reaction workflow act skipped — no workflow engine in this app", { workflow: n.workflow });
1219
- return;
1220
- }
1221
- let e = n.payload === void 0 ? r.new ?? r.old ?? {} : n.payload(r);
1222
- await Wr(S, {
1223
- traceId: `reaction:${n.workflow}`,
1224
- source: `reaction:${n.workflow}`
1225
- }).start(n.workflow, e);
1226
- return;
1227
- }
1228
- await pe(n.agent, r, {
1229
- findAgentSend: (t) => e.discovered.actions.find((e) => e.descriptor.name === `${t}.send`),
1230
- runAction: (e, t, n) => Promise.resolve(ft(e, t, n)),
1231
- makeSubject: (e) => Nn(e),
1232
- now: () => Date.now(),
1233
- log: t
1234
- });
1235
- }, r = async (n, r) => {
1236
- try {
1237
- let { requireAiBudget: t } = await import("@voltro/ai");
1238
- return (await W.runPromise(W.either(t(e.store, {
1239
- tenantId: n,
1240
- limitUsd: r
1241
- }))))._tag === "Right";
1242
- } catch (e) {
1243
- return t.warn("reaction budget check failed — refusing the act", { tenantId: n }, e), !1;
1244
- }
1245
- }, i = jt(e.store, { onError: (e) => t.warn("reaction: rate-slot claim failed; refusing the act", { cause: String(e) }) });
1246
- Xt = st(e.discovered.reactions ?? [], e.store, {
1247
- runAct: n,
1248
- checkBudget: r,
1249
- claimRateSlot: (e) => i.claim(e)
1250
- }, t);
1251
- }
1252
- let Zt;
1253
- (e.discovered.aggregates?.length ?? 0) > 0 && (Zt = await v({
1254
- discovered: e.discovered.aggregates ?? [],
1255
- store: e.store,
1256
- log: I.child("aggregate"),
1257
- ...e.analytics === void 0 ? {} : { analytics: e.analytics },
1258
- ...e.aggregateStorage === void 0 ? {} : { storage: e.aggregateStorage },
1259
- ...e.aggregateCoordinator === void 0 ? {} : { coordinator: e.aggregateCoordinator }
1260
- }), ze = G.succeed(rr, Zt.registry));
1261
- let Qt;
1262
- (e.discovered.expectations?.length ?? 0) > 0 && (Qt = dr({
1263
- discovered: e.discovered.expectations ?? [],
1264
- store: e.store,
1265
- log: I.child("expectation")
1266
- }), Be = G.succeed(sr, Qt.registry)), (e.discovered.budgets?.length ?? 0) > 0 && (n = pr({
1267
- discovered: e.discovered.budgets ?? [],
1268
- log: I.child("finops")
1269
- }), He = G.succeed(ir, n.registry));
1270
- let $t;
1271
- return (e.discovered.experiments?.length ?? 0) > 0 && ($t = fr({
1272
- discovered: e.discovered.experiments ?? [],
1273
- store: e.store,
1274
- log: I.child("experiment")
1275
- }), Ge = G.succeed(cr, $t.registry)), Gt = !0, e.bootTiming?.mark("ready"), {
1276
- dispatcher: r,
1277
- server: Kt,
1278
- scheduler: h,
1279
- eventsSnapshot: me(D.bus, D.declared),
1280
- membersSnapshot: () => ({
1281
- members: Ie.membership.list(),
1282
- capturedAt: Date.now()
1283
- }),
1284
- agentTools: () => bt,
1285
- rpcMetrics: () => Xe,
1286
- webhooksService: () => ve,
1287
- runCanceller: () => ee(),
1288
- flowControlHealth: () => l?.cancelHealth(),
1289
- inferenceHealth: () => c?.health(),
1290
- workflowWriteActions: () => S === void 0 || N === void 0 ? void 0 : se({
1291
- store: e.store,
1292
- log: I,
1293
- workflows: e.discovered.workflows ?? [],
1294
- workflowsProxy: o,
1295
- workflowRuntime: u,
1296
- workflowRunRecorder: N,
1297
- closeChildrenForParent: Pt
1298
- }),
1299
- redriveWorkflowRun: (e) => f ? f(e) : Promise.reject(/* @__PURE__ */ Error("redrive: this app registers no workflows")),
1300
- resumeWorkflowRunFromStep: (e) => p ? p(e) : Promise.reject(/* @__PURE__ */ Error("resume-from-step: this app registers no workflows")),
1301
- close: async () => {
1302
- Gt = !1, await Jt.drainRequests();
1303
- for (let e of Ce) try {
1304
- await e();
1305
- } catch (e) {
1306
- I.warn("serve: teardown step failed", {}, e);
1307
- }
1308
- await Le?.detach(), await Ie.detach(), Zt?.detach(), Qt?.detach(), n?.detach(), $t?.detach(), Xt?.(), Yt?.(), await h?.shutdown(), r.close(), await m?.detach(), await u?.dispose(), await qt(), await Jt.finish();
1309
- }
1310
- };
1311
- }, $ = L({ scope: "voltro:serve" }), _a = (e, t, n) => (e === "production" || e === "staging") && t !== "memory" && n !== "0", va = Ut, ya = async (e) => {
1312
- let t = Sn(process.cwd());
1313
- if (kn(t)) {
1314
- let n;
1315
- try {
1316
- let e = await import(An(t).href);
1317
- typeof e.runServe == "function" ? n = e.runServe : $.warn("serve bundle has no runServe export — using the standard serve path");
1318
- } catch (e) {
1319
- $.warn("serve bundle failed to load — using the standard serve path", {}, e);
1320
- }
1321
- if (n) return $.info("serve: booting from the precompiled serve bundle"), n(e);
1322
- }
1323
- return ba(e);
1324
- }, ba = async (s) => {
1325
- let d = Cn();
1326
- e("serve");
1327
- try {
1328
- xi();
1329
- } catch (e) {
1330
- throw i(e instanceof Error ? e.message : String(e));
1331
- }
1332
- let g = process.cwd(), v = await He(g), ne = P({
1333
- kind: "api",
1334
- configPort: v?.port,
1335
- env: process.env,
1336
- flagPort: va(s, "--port")
1337
- });
1338
- for (let e of ne.warnings) $.warn(e);
1339
- let ie = ne.port;
1340
- $r(Qr(v?.secrets)), await Wt({
1341
- rawEnv: v?.env,
1342
- appType: "api",
1343
- root: g,
1344
- log: $,
1345
- generateTypes: !1
1346
- }), d.mark("config");
1347
- let y = (process.env.DB_DIALECT ?? v?.store ?? "memory").toLowerCase(), se = (y === "mariadb" || y === "postgres" || y === "mssql") && (process.env.CDC ?? "1") !== "0", ce = y === "mariadb" ? "mariadb" : y === "mssql" ? "mssql" : void 0, le = xn(g);
1348
- if (!r() && kn(le)) try {
1349
- let e = await import(An(le).href);
1350
- if (e.modules) {
1351
- let t = {};
1352
- for (let [n, r] of Object.entries(e.modules)) t[Dn(g, n)] = r;
1353
- n(t), $.info("precompiled api bundle loaded", { modules: Object.keys(t).length });
1354
- }
1355
- } catch (e) {
1356
- $.warn("precompiled api bundle failed to load — falling back to source", {}, e);
1357
- }
1358
- let b = await Ye(g), x = await kt(b, { cdc: se && ce !== void 0 }), ue = Ht(x);
1359
- {
1360
- let e = /* @__PURE__ */ new Set([
1361
- ...x.queries.filter((e) => e.descriptor.overridesPlugin === !0).map((e) => e.descriptor.name),
1362
- ...x.mutations.filter((e) => e.descriptor.overridesPlugin === !0).map((e) => e.descriptor.name),
1363
- ...x.actions.filter((e) => e.descriptor.overridesPlugin === !0).map((e) => e.descriptor.name)
1364
- ]);
1365
- Zt(Xt(v?.plugins ?? []), [
1366
- ...x.queries.map((e) => e.descriptor.name),
1367
- ...x.mutations.map((e) => e.descriptor.name),
1368
- ...x.actions.map((e) => e.descriptor.name),
1369
- ...x.streams.map((e) => e.descriptor.name)
1370
- ], e);
1371
- let t = ae(x.serverOnlyLeaks, Ae(process.env, "strict"), br, "`voltro serve`");
1372
- if (t.action === "fail") throw i(t.message ?? "");
1373
- t.action === "warn" && $.warn(t.message ?? "");
1374
- }
1375
- let fe = b.filter((e) => yn.test(e)), pe = fe.length > 0 ? await vn(fe, $.child("webhooks")) : {
1376
- outgoing: [],
1377
- incoming: [],
1378
- providers: []
1379
- }, me = gn(x.events), be = pe.outgoing.length + pe.incoming.length + pe.providers.length + me.length === 0 ? void 0 : {
1380
- ...pe,
1381
- outgoing: [...pe.outgoing, ...me]
1382
- }, xe = an({
1383
- nodeEnv: process.env.NODE_ENV,
1384
- cdcDialect: ce,
1385
- declared: v?.schema
1386
- }), we = $t({
1387
- gates: xe,
1388
- runtime: {
1389
- traces: ve(),
1390
- undo: oi()
1391
- }
1392
- });
1393
- if (we !== void 0) throw i(`serve: ${we}`);
1394
- let De = rn({
1395
- mix: x.featureMix,
1396
- plugins: v?.plugins ?? [],
1397
- gates: xe,
1398
- ...ce ? { cdcDialect: ce } : {}
1399
- }), Oe = v?.analytics !== void 0 && v.analytics.kind !== "noop" && y !== "memory" ? (await F(y)).makeSqlLayer(O()) : void 0, ke = await qe({
1400
- spec: v?.analytics,
1401
- sqlLayer: Oe,
1402
- log: $
1403
- }), T = (() => {
1404
- let e = new Set(x.tables.map((e) => e.tableName)), t = [...x.tables];
1405
- for (let n of [...De, ...ke.tables]) e.has(n.tableName) || (e.add(n.tableName), t.push(n));
1406
- return t;
1407
- })();
1408
- for (let e of T) Jn(e);
1409
- {
1410
- let e = xr(si(Be(x), Lt(T)));
1411
- e !== void 0 && $.warn(e);
1412
- }
1413
- let Pe = (process.env.NODE_ENV ?? "").toLowerCase();
1414
- if (_a(Pe, y, process.env.VOLTRO_AUTO_MIGRATE)) {
1415
- let e = (await F(y)).makeSqlLayer(O()), t = await W.runPromise(Qn.SqlClient.pipe(W.flatMap((e) => tr(e, g)), W.provide(e), W.catchAll(() => W.succeed([]))));
1416
- t.length > 0 && ($.error(`serve: refusing to boot — ${t.length} pending file-based migration(s) have never run against this database. They perform the changes a schema diff cannot infer (data moves, backfills, table splits), so the declarative fingerprint check below cannot see them and would have let this process serve un-migrated data.`, { pending: t }), $.error("Run them from your pre-deploy job — `voltro db migrate .` (schema + files) or `voltro db files .` (files alone) — or set VOLTRO_AUTO_MIGRATE=0 to bypass every boot schema check. `voltro serve` never applies them itself: a rolling deploy would start N replicas and each would try."), process.exit(1));
1417
- let n = await W.runPromise(Qn.SqlClient.pipe(W.flatMap((e) => nr(e, T, {
1418
- appliedBy: `serve:${Pe}`,
1419
- environment: "prod",
1420
- dialectId: y
1421
- })), W.provide(e)));
1422
- n.kind === "prod-mismatch" && ($.error(er(n, y)), $.error(tn({
1423
- gates: xe,
1424
- nodeEnv: process.env.NODE_ENV,
1425
- cdcDialect: ce,
1426
- declared: v?.schema
1427
- })), $.error("serve: refusing to boot — apply the schema first (voltro db apply in a pre-deploy step), or set VOLTRO_AUTO_MIGRATE=0 to bypass this check."), process.exit(1)), $.info(er(n, y));
1428
- }
1429
- await Yt({
1430
- dialectId: y,
1431
- tables: T,
1432
- mode: Jt(v?.reactiveTriggers),
1433
- lockSchema: O().schema,
1434
- makeLayer: async () => (await F(y)).makeSqlLayer(O()),
1435
- log: {
1436
- info: (e, t) => $.info(e, t ?? {}),
1437
- warn: (e, t) => $.warn(e, t ?? {})
1438
- }
1439
- });
1440
- let Fe = Ur(T);
1441
- d.mark("discover");
1442
- let E = await rt(v, void 0);
1443
- {
1444
- let e = await ee(E);
1445
- if (e !== void 0) throw i(`serve: ${e}`);
1446
- }
1447
- let Ve = ui(E, y);
1448
- for (let e of tt({
1449
- dialect: String(v?.store ?? process.env.DB_DIALECT ?? "postgres"),
1450
- changeStrategy: (process.env.CDC ?? "1") === "0" ? "inline" : "cdc",
1451
- dbUrl: process.env.DB_URL,
1452
- crossReplicaBus: Ni(v?.plugins ?? [])?.broadcast.crossReplica === !0,
1453
- tables: x.tables.map((e) => ({
1454
- tableName: e.tableName,
1455
- isReactive: e.isReactive === !0
1456
- })),
1457
- querySources: x.queries.flatMap((e) => {
1458
- let t = e.descriptor.source;
1459
- return t === void 0 ? [] : typeof t == "string" ? [t] : [...t];
1460
- })
1461
- })) e.level === "warn" ? $.warn(e.message) : $.info(e.message);
1462
- {
1463
- let e = vt({
1464
- tables: Kn().map((e) => ({ tableName: e.tableName })),
1465
- queries: x.queries.map((e) => ({
1466
- name: e.descriptor.name,
1467
- source: e.descriptor.source
1468
- }))
1469
- }), t = pt(e);
1470
- t !== void 0 && $.warn(t);
1471
- }
1472
- v?.cache && !process.env.CACHE_BACKEND && (process.env.CACHE_BACKEND = v.cache), v?.cacheRedisUrl && !process.env.CACHE_REDIS_URL && (process.env.CACHE_REDIS_URL = v.cacheRedisUrl), v?.cacheRedisDriver && !process.env.CACHE_REDIS_DRIVER && (process.env.CACHE_REDIS_DRIVER = v.cacheRedisDriver), v?.cacheKeyPrefix && !process.env.CACHE_KEY_PREFIX && (process.env.CACHE_KEY_PREFIX = v.cacheKeyPrefix);
1473
- let { service: Ue, invalidationBus: We, snapshotCache: Ke, cache: Je, semantic: Ze, evictSource: $e, backend: it, stats: ot, dispose: st } = await Xe({
1474
- env: process.env,
1475
- semantic: v?.cacheSemantic ?? !1
1476
- });
1477
- Ze !== void 0 && $.info("semantic cache enabled — reactive eviction on live writes"), $.info(`cache backend resolved: ${it}` + (it === "redis" ? ` (driver ${process.env.CACHE_REDIS_DRIVER ?? "resp"})` : " — in-process, not cross-instance")), E.onChange((e) => {
1478
- if (W.runFork(We.publish(e.table)), $e !== void 0) {
1479
- let t = (e.new ?? e.old)?.id;
1480
- $e({
1481
- table: e.table,
1482
- op: e.op,
1483
- ...t === void 0 ? {} : { id: t }
1484
- });
1485
- }
1486
- }), v?.kv && !process.env.KV_BACKEND && (process.env.KV_BACKEND = v.kv), v?.kvRedisUrl && !process.env.KV_REDIS_URL && (process.env.KV_REDIS_URL = v.kvRedisUrl), v?.kvKeyPrefix && !process.env.KV_KEY_PREFIX && (process.env.KV_KEY_PREFIX = v.kvKeyPrefix);
1487
- let { kv: ut, service: dt } = await jr({ store: E });
1488
- Pt({
1489
- log: $,
1490
- max: qt(),
1491
- outOfPool: p(y, (process.env.CDC ?? "1") !== "0"),
1492
- readPools: t.replicationSnapshot()?.replicaCount ?? 0,
1493
- always: !0
1494
- }), d.mark("store");
1495
- let ht = ur({
1496
- store: E,
1497
- sink: ke.sink,
1498
- log: $
1499
- }), xt = Ge({
1500
- store: E,
1501
- dialect: y,
1502
- log: { info: (e) => $.info(e) }
1503
- }), j = v?.plugins ?? [], jt = process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, Rt, Bt;
1504
- y !== "memory" && (Rt = Zn.make((await F(y)).makeSqlLayer(O())), Bt = await Rt.runPromise(Qn.SqlClient));
1505
- let Ut = [
1506
- "postgres",
1507
- "mariadb",
1508
- "mysql",
1509
- "mssql"
1510
- ].includes(y) ? Dr(E, jt, $) : ni, _n = M(v?.scheduling), Sn = Nr({
1511
- maxIdleIntervalMs: _n.pollCeilingMs,
1512
- coordinator: Ut,
1513
- replicaId: jt,
1514
- log: $
1515
- }), wn = [], Tn = process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, On = Ni(v?.plugins ?? [])?.broadcast?.provider, L = Qe(v?.plugins, v?.name ?? En(g));
1516
- {
1517
- let e = et(v?.plugins, v?.name ?? En(g));
1518
- e !== void 0 && $.warn(e);
1519
- }
1520
- let jn = Mt(v?.plugins, {
1521
- instanceId: Tn,
1522
- namespace: L,
1523
- meta: { mode: "serve" },
1524
- logger: $
1525
- }), Mn = {
1526
- ...Bt ? { sql: Bt } : {},
1527
- instanceId: Tn,
1528
- membership: jn.membership,
1529
- ...On === void 0 ? {} : { broadcast: On },
1530
- broadcastChannels: { presence: Mi(L, "presence") },
1531
- scheduleCoordinated: (e, t, n) => {
1532
- let r = Sn(e, t, n);
1533
- return wn.push(r), r;
1534
- }
1535
- };
1536
- for (let e of j) e.bindDataStore?.(Ve, Mn);
1537
- l({
1538
- store: E,
1539
- ...ct(),
1540
- log: $
1541
- });
1542
- let R = j.filter((e) => typeof e.onChangeEvent == "function");
1543
- if (R.length > 0) {
1544
- let e = E.changeScope ?? "local";
1545
- E.onChange((t) => {
1546
- let n = ye(t, e);
1547
- for (let e of R) W.runFork(e.onChangeEvent(n).pipe(W.catchAllCause((t) => W.sync(() => $.warn(`plugin ${e.name} onChangeEvent failed`, { error: Xn.pretty(t) })))));
1548
- });
1549
- }
1550
- let Nn = Ne({
1551
- plugins: j,
1552
- appName: v?.name ?? "voltro-api",
1553
- appType: "api",
1554
- voltroVersion: process.env.npm_package_version ?? "0.0.0",
1555
- log: $
1556
- });
1557
- j.length && await Nn.activate(), d.mark("plugins");
1558
- let Pn = await Nn.gatherObservability(), Fn = {
1559
- info: (e, t) => process.stdout.write(`[broadcast] ${e} ${t ? JSON.stringify(t) : ""}\n`),
1560
- warn: (e, t) => process.stderr.write(`[broadcast] ${e} ${t ? JSON.stringify(t) : ""}\n`),
1561
- debug: () => {}
1562
- }, z, In = await A(E, v, y, L, Fn, (e, t) => {
1563
- z?.refreshAll(`broadcast gap: missed ${t} change(s) from ${e}`);
1564
- }), Ln = v?.apiKeys, Rn = (typeof Ln == "object" ? Ln.prefix : void 0) ?? "voltro_", B = Ln ? yr(E) : void 0, V = B ? kr({ flush: Ar(B) }) : void 0;
1565
- V && qr(() => V.shutdown());
1566
- let zn = B ? Or(B, {
1567
- prefix: Rn,
1568
- ...V ? { usage: V } : {}
1569
- }) : void 0, Bn = zn ? [Sr(zn, { prefix: Rn })] : [], Vn = St([...v?.auth?.strategies ?? [], ...Bn], Ai(v?.plugins ?? []), v?.auth?.anonymousTenantRequired ?? !1, v?.auth, () => Ve), Hn = [...v?.restRoutes ?? [], ...zn ? lr(zn, (typeof Ln == "object" ? Ln.managementPath : void 0) ?? "/v1/api-keys") : []], Un = Ct(v?.idempotency, E), Wn = j.map((e) => e.services).filter((e) => e !== void 0), Gn = G.mergeAll(_t({
1570
- analyticsLayer: ke.layer,
1571
- cacheService: Ue,
1572
- kvService: dt,
1573
- ...Ze === void 0 ? {} : { semanticCache: Ze },
1574
- pluginServices: Wn,
1575
- userLayers: v?.layers ?? []
1576
- }), Le(v?.http ?? {})), H = await Re({
1577
- files: b,
1578
- store: E,
1579
- log: $,
1580
- seedPolicy: "report",
1581
- seedPattern: fn,
1582
- loadSeedFiles: I,
1583
- startupPattern: sn,
1584
- loadStartupFiles: a,
1585
- runStartups: o,
1586
- emailPattern: k,
1587
- loadEmailFiles: Tt,
1588
- registerEmailTemplates: ji
1589
- });
1590
- (H.startupCount > 0 || H.emailCount > 0) && $.info("boot lifecycle", {
1591
- startups: H.startupCount,
1592
- emailTemplates: H.emailCount
1593
- }), H.startups !== void 0 && qr(async () => {
1594
- await H.startups.stop();
1595
- }), de({
1596
- demands: Se(ue),
1597
- isRegistered: (e) => Cr(e) !== void 0
1598
- });
1599
- let U = wt({
1600
- schedules: at({
1601
- schedules: x.schedules,
1602
- seeds: H.seeds,
1603
- store: E,
1604
- log: $.child("seeds")
1605
- }),
1606
- workflows: x.workflows ?? [],
1607
- log: $.child("workflow-schedules")
1608
- }), Yn = v?.scheduling ?? {}, rr = Yn.trigger ?? "self", ir = /* @__PURE__ */ new Set([
1609
- "postgres",
1610
- "mysql",
1611
- "mariadb",
1612
- "mssql"
1613
- ]), ar = Yn.coordination ?? (ir.has(y) ? "advisoryLock" : "single"), or = ar === "cluster" && ir.has(y), sr = or ? "cluster" : ar === "advisoryLock" && ir.has(y) ? "advisoryLock" : "single";
1614
- ar === "cluster" && !or && $.warn("scheduling.coordination=cluster needs a sql-backed store except sqlite — falling back to single"), ar === "advisoryLock" && !ir.has(y) && $.warn("scheduling.coordination=advisoryLock needs a SQL store (the claim-row gate) — falling back to single");
1615
- let cr, dr = x.workflows.length > 0 || x.workflowWorkers.length > 0 || x.eventTriggers.length > 0 || (be?.outgoing.length ?? 0) > 0 || or, fr;
1616
- if (dr) {
1617
- if (y === "mssql") {
1618
- let e = await hn(process.cwd());
1619
- e && $.warn(e);
1620
- }
1621
- let [{ WorkflowEngine: e }, { makeClusterCronLayer: t, workflowEngineLayer: n, resolveRunnerStorage: r, resolveFailoverTuning: i }] = await Promise.all([import("@effect/workflow"), import("@voltro/workflow/cluster")]), a = or ? U.filter((e) => (e.trigger ?? rr) === "self").map((e) => t({
1622
- name: e.name,
1623
- cron: vr(e),
1624
- execute: async () => {
1625
- await cr?.fireFromCluster(e.name);
1626
- }
1627
- })) : [];
1628
- fr = y === "memory" ? e.layerMemory : await (async () => {
1629
- let e = await F(y), t = r({ sqliteFamily: e.id === "sqlite" || e.id === "turso" });
1630
- return $.info(`workflow engine: cluster-${t}, dialect=${e.id}` + (t === "memory" ? " — single-process durable replay, no cross-pod shard handoff" + (e.id !== "sqlite" && e.id !== "turso" ? " (VOLTRO_WORKFLOW_RUNNER_STORAGE=memory: SqlRunnerStorage/cluster_runners + GET_LOCK skipped)" : "") : "")), n({
1631
- sqlClientLayer: e.makeSqlLayer(O()),
1632
- runnerStorage: t,
1633
- dialectId: e.id,
1634
- ...process.env.VOLTRO_WORKFLOW_RUNNER_PORT ? { runnerListenPort: Number(process.env.VOLTRO_WORKFLOW_RUNNER_PORT) } : {},
1635
- ...i(),
1636
- ...a.length > 0 ? { extraShardingLayers: a } : {}
1637
- });
1638
- })();
1639
- }
1640
- let pr = bt(j, bn()), mr = b.filter((e) => /\.subscribe\.tsx?$/.test(e)), K = mr.length > 0 ? await c(mr, $) : [], hr = b.filter((e) => /\.reaction\.tsx?$/.test(e)), q = hr.length > 0 ? await he(hr, $) : [], gr = b.filter((e) => un.test(e)), _r = gr.length > 0 ? await Me(gr, $) : [], wr = b.filter((e) => /\.aggregate\.tsx?$/.test(e)), Tr = wr.length > 0 ? await _e(wr, $) : [];
1641
- {
1642
- let e = xr(si(Be({ aggregates: Tr.map((e) => e.definition) }), Lt(T)));
1643
- e !== void 0 && $.warn(e);
1644
- }
1645
- let Er = lt();
1646
- if (Tr.length > 0 && y !== "memory") try {
1647
- let e = (await F(y)).makeSqlLayer(O());
1648
- Er = u(e);
1649
- } catch (e) {
1650
- $.warn("aggregate: SQL storage init failed — falling back to in-process", { err: String(e) });
1651
- }
1652
- let Mr = y === "memory" ? ni : Dr(E, `aggregate@${process.pid}`, $), Pr = b.filter((e) => dn.test(e)), Fr = Pr.length > 0 ? await Ft(Pr, $) : [], Ir = b.filter((e) => ln.test(e)), Lr = Ir.length > 0 ? await m(Ir, $) : [], Rr = b.filter((e) => cn.test(e)), zr = Rr.length > 0 ? await w(Rr, $) : [], Br = [], Vr = [], Hr = b.filter((e) => nn.test(e));
1653
- if (Hr.length > 0) {
1654
- let e = $.child("agent"), t = b.filter((e) => en.test(e));
1655
- t.length > 0 && await on(t, e);
1656
- let n = await Qt(Hr, e);
1657
- for (let e of n.agents) for (let t of Ot(e)) (t.kind === "action" ? Br : Vr).push({
1658
- file: t.file,
1659
- descriptor: t.descriptor,
1660
- executor: t.executor
1661
- });
1662
- n.agents.length > 0 && e.info("synthesized agent routes", { agents: n.agents.map((e) => e.descriptor.name) });
1663
- }
1664
- d.mark("workflow");
1665
- let J = () => {
1666
- let e = Y.workflowWriteActions();
1667
- if (e === void 0) throw Error("workflow actions: this app registers no workflows");
1668
- return e;
1669
- }, Wr = qn({
1670
- dialect: y,
1671
- ...O()
1672
- }), Gr = y === "memory" ? void 0 : (await F(y)).makeSqlLayer(O()), Kr = async () => gt({
1673
- sqlLayer: Gr,
1674
- declared: T,
1675
- log: $
1676
- }), Jr = {
1677
- kind: "api",
1678
- meta: {
1679
- name: v?.name ?? "voltro-api",
1680
- voltroVersion: Et,
1681
- port: ie,
1682
- mode: "start",
1683
- store: y,
1684
- cdc: se ? "on" : "off",
1685
- ...Wr === void 0 ? {} : { databaseId: Wr }
1686
- },
1687
- rpc: Ie(x, g),
1688
- workflows: Nt(x, g),
1689
- migrations: Kr,
1690
- events: () => Y.eventsSnapshot(),
1691
- agentTools: () => Y.agentTools(),
1692
- invariantChecks: () => ({
1693
- mode: "serve",
1694
- accessGate: ue,
1695
- config: v,
1696
- serverOnlyLeaks: x.serverOnlyLeaks,
1697
- migrations: Kr
1698
- }),
1699
- members: () => Y.membersSnapshot(),
1700
- inspectFireSchedule: async ({ name: e, trigger: t }) => {
1701
- if (!cr) throw Error("scheduler not started — this app registers no self-triggered schedules (all schedules are trigger:'external', or there are none).");
1702
- return { runId: await cr.fireNow(e, t) ?? null };
1703
- },
1704
- inspectBackfillSchedule: _({
1705
- getHandle: () => cr,
1706
- getSchedules: () => U
1707
- }),
1708
- ...be === void 0 ? {} : { webhooks: () => ge({
1709
- store: E,
1710
- discoveredWebhooks: be
1711
- }) },
1712
- plugins: () => ({
1713
- plugins: Nn.snapshot(),
1714
- capturedAt: Date.now()
1715
- }),
1716
- env: () => Gt(v?.name ?? En(g), {
1717
- ...v?.env !== void 0 && bi(v.env) ? { contract: v.env } : {},
1718
- plugins: v?.plugins ?? []
1719
- }),
1720
- dataCache: () => ze({
1721
- stats: ot,
1722
- backendKind: it
1723
- }),
1724
- subscriptions: () => It(() => z),
1725
- inspectTables: () => S(x.tables),
1726
- inspectRows: C({
1727
- store: E,
1728
- tables: x.tables,
1729
- mask: !0
1730
- }),
1731
- metrics: (e) => Y.rpcMetrics().snapshot(e),
1732
- cluster: () => zt({
1733
- store: E,
1734
- dialect: y,
1735
- useClusterCron: or,
1736
- scheduleCoordChoice: ar
1737
- }),
1738
- inspectSchedules: () => Te({
1739
- schedules: U,
1740
- defaultTrigger: rr,
1741
- coordination: sr
1742
- }),
1743
- inspectScheduleRuns: (e) => N(E, e),
1744
- ...f(E, {
1745
- controls: nt(x.workflows ?? []),
1746
- active: (x.workflows?.length ?? 0) > 0,
1747
- cancellation: () => Y.flowControlHealth()
1748
- }),
1749
- webhookActions: Ce(() => Y.webhooksService()),
1750
- inspectStartWorkflow: (e) => J().inspectStartWorkflow(e),
1751
- inspectCancelWorkflowRun: (e) => J().inspectCancelWorkflowRun(e),
1752
- inspectSuspendWorkflowRun: (e) => J().inspectSuspendWorkflowRun(e),
1753
- inspectResumeWorkflowRun: (e) => J().inspectResumeWorkflowRun(e),
1754
- inspectDiscardWorkflowRun: (e) => J().inspectDiscardWorkflowRun(e),
1755
- inspectRetryWorkflowRun: (e) => J().inspectRetryWorkflowRun(e),
1756
- inspectSignalWorkflowRun: (e) => J().inspectSignalWorkflowRun(e),
1757
- inspectUpdateWorkflowRun: (e) => J().inspectUpdateWorkflowRun(e),
1758
- inspectInferences: (e) => yt({
1759
- store: E,
1760
- active: (x.workflows?.length ?? 0) > 0,
1761
- dispatcher: () => Y.inferenceHealth()
1762
- }, e.limit === void 0 ? {} : { limit: e.limit }),
1763
- ...mt({
1764
- store: E,
1765
- cancelRun: async (e) => await Y.runCanceller()?.(e) ?? !1,
1766
- retryRun: async (e) => J().inspectRetryWorkflowRun({ runId: e }),
1767
- redriveRun: async (e) => Y.redriveWorkflowRun({ runId: e }),
1768
- log: $
1769
- }),
1770
- inspectRedriveWorkflowRun: (e) => Y.redriveWorkflowRun(e),
1771
- inspectResumeWorkflowRunFromStep: (e) => Y.resumeWorkflowRunFromStep(e)
1772
- }, Yr = (process.env.VOLTRO_TENANT_ISOLATION ?? v?.tenancy?.isolation) === "namespace", Xr = Yr && y !== "memory" ? await (async () => {
1773
- let e = await F(y);
1774
- return At({
1775
- tables: T,
1776
- sqlLayer: e.makeSqlLayer(O()),
1777
- dialect: y,
1778
- options: { retryFilter: e.retryFilter },
1779
- log: {
1780
- info: (e, t) => $.info(e, t),
1781
- error: (e, t, n) => $.error(e, t ?? {}, n)
1782
- }
1783
- });
1784
- })() : void 0, Zr = await ft({
1785
- input: v?.tenancy?.residency,
1786
- namespaceIsolationOn: Yr,
1787
- makeStoreForUrl: (e, t) => rt(v, void 0, Kt(O(), t)),
1788
- log: {
1789
- info: (e, t) => $.info(e, t),
1790
- warn: (e, t) => $.warn(e, t)
1791
- }
1792
- });
1793
- Zr !== void 0 && qr(async () => {
1794
- await Zr.close();
1795
- });
1796
- let Y = await ga({
1797
- bootTiming: d,
1798
- broadcastNamespace: L,
1799
- scheduling: (() => {
1800
- let e = _n;
1801
- return {
1802
- admissionDrainMs: e.admissionDrainMs,
1803
- inferenceTickMs: e.inferenceTickMs,
1804
- cancelSweepMs: e.cancelSweepMs,
1805
- stalenessSweepMs: e.stalenessSweepMs,
1806
- disarmWhenIdle: D({
1807
- changeScope: E.changeScope,
1808
- broadcastAttached: In !== void 0
1809
- })
1810
- };
1811
- })(),
1812
- ...v?.workflows?.staleness === void 0 ? {} : { workflowStaleness: v.workflows.staleness },
1813
- ...v?.workflows?.suspendSignalHintMs === void 0 ? {} : { workflowSuspendSignalHintMs: v.workflows.suspendSignalHintMs },
1814
- workflowRecording: Vt(v?.workflows?.recording),
1815
- membership: {
1816
- ...jn,
1817
- instanceId: Tn
1818
- },
1819
- security: {
1820
- defaultDeny: oe(v),
1821
- ...re(v)
1822
- },
1823
- approvals: { defaultExpiryMs: je(v) },
1824
- ...v?.plugins === void 0 ? {} : { plugins: v.plugins },
1825
- ...Un ? { idempotency: Un } : {},
1826
- restRoutes: Hn,
1827
- appProcedures: ue,
1828
- discovered: {
1829
- queries: [...x.queries, ...Vr],
1830
- mutations: x.mutations,
1831
- actions: [...x.actions, ...Br],
1832
- streams: x.streams,
1833
- events: x.events,
1834
- workflows: x.workflows,
1835
- workflowWorkers: x.workflowWorkers,
1836
- eventTriggers: x.eventTriggers,
1837
- schedules: U,
1838
- subscribers: K,
1839
- outboxHandlers: _r,
1840
- connections: x.connections,
1841
- reactions: q,
1842
- aggregates: Tr,
1843
- expectations: Fr,
1844
- budgets: Lr,
1845
- experiments: zr,
1846
- ...be === void 0 ? {} : { webhooks: be }
1847
- },
1848
- log: $,
1849
- analytics: ke.sink,
1850
- aggregateStorage: Er,
1851
- aggregateCoordinator: Mr,
1852
- store: E,
1853
- kv: ut,
1854
- cache: Je,
1855
- snapshotCache: Ke,
1856
- ...v?.reactive === void 0 ? {} : { reactive: v.reactive },
1857
- schemaRegistry: Fe,
1858
- tenantScopedTables: x.tenantScopedTables,
1859
- softDeleteScopedTables: x.softDeleteScopedTables,
1860
- dataTransferSnapshot: $n(T, y),
1861
- dataTransferDialect: y,
1862
- ...Xr === void 0 ? {} : { ensureTenantProvisioned: Xr.ensure },
1863
- ...Zr === void 0 ? {} : { resolveResidentStore: Zr.resolveStore },
1864
- tenantIsolation: (process.env.VOLTRO_TENANT_ISOLATION ?? v?.tenancy?.isolation) === "namespace" ? "namespace" : "shared-schema",
1865
- resolveSubject: (e, t) => Vn({
1866
- headers: e,
1867
- clientId: t
1868
- }),
1869
- ...v?.auth === void 0 ? {} : { authority: v.auth },
1870
- ...v?.agents === void 0 ? {} : { agents: v.agents },
1871
- httpRoutes: j.flatMap((e) => e.httpRoutes ?? []),
1872
- getStore: () => Ve,
1873
- ...Gn ? { baseLayer: Gn } : {},
1874
- ...fr === void 0 ? {} : { workflowEngineLayer: fr },
1875
- scheduleDefaultTrigger: rr,
1876
- scheduleCoordination: sr,
1877
- scheduleArmSelf: !or,
1878
- dormancy: process.env.VOLTRO_DORMANCY === "sleep" || process.env.VOLTRO_DORMANCY === "always-on" ? process.env.VOLTRO_DORMANCY : v?.dormancy ?? "always-on",
1879
- scheduleReplicaId: process.env.HOSTNAME ?? `pid-${process.pid}`,
1880
- ...pr === void 0 ? {} : { scheduleFireInterceptor: pr },
1881
- onSchedulerReady: (e) => {
1882
- cr = e;
1883
- },
1884
- inspectRoute: { handle: async (e, t, n, r) => await h(e, Jr, t, {
1885
- method: n,
1886
- ...r === void 0 ? {} : { body: r }
1887
- }) || ((n === "GET" ? await mn(e, Jr, t, { method: n }) : null) ?? pn(e, Jr, t, {
1888
- method: n,
1889
- ...r === void 0 ? {} : { body: r }
1890
- }) ?? {
1891
- status: 404,
1892
- contentType: "application/json",
1893
- body: JSON.stringify({ error: "not an inspect route" })
1894
- }) },
1895
- ...v?.name === void 0 ? {} : { appName: v.name },
1896
- observability: Pn,
1897
- port: ie,
1898
- ...v?.transport?.wsPath ? { path: v.transport.wsPath } : {}
1899
- });
1900
- return z = Y.dispatcher, te(Ee([
1901
- x.queries,
1902
- x.mutations,
1903
- x.actions,
1904
- x.streams
1905
- ]), (e) => {
1906
- $.warn(e);
1907
- }), $.info(`API listening on :${ie}`, {
1908
- dialect: y,
1909
- queries: x.queries.length,
1910
- mutations: x.mutations.length,
1911
- actions: x.actions.length,
1912
- streams: x.streams.length,
1913
- workflows: x.workflows.length,
1914
- workflowWorkers: x.workflowWorkers.length,
1915
- schedules: U.length,
1916
- scheduleCoordination: sr
1917
- }), d.finish($), qr(async () => {
1918
- for (let e of wn) e.stop();
1919
- xt.stop();
1920
- try {
1921
- await Y.close(), st(), Rt?.dispose(), await Nn.deactivate(), await In?.close(), await Dt({
1922
- mirror: ht,
1923
- log: $
1924
- }), await ke.dispose(), await E.close?.();
1925
- } catch (e) {
1926
- console.error("serve: shutdown step failed, exiting anyway:", e);
1927
- }
1928
- }), await new Promise(() => {}), 0;
1929
- };
1930
- //#endregion
1931
- export { ya as n, _a as r, ba as t };