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