@voltro/cli 0.24.0 → 0.25.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 +426 -0
  2. package/THIRD-PARTY-NOTICES.md +2 -2
  3. package/dist/{apiBuild-B2m4XK_8.js → apiBuild-BqhCSytw.js} +15 -15
  4. package/dist/apiBuild-N1R4V792.js +2 -0
  5. package/dist/bin.js +3 -3
  6. package/dist/{commands-CaIhTsC2.js → commands-7EmYJ9Xg.js} +1774 -1577
  7. package/dist/dbCommand-CIrdFLp9.js +2 -0
  8. package/dist/{dbCommand-CC61CsAc.js → dbCommand-FUU12FvD.js} +265 -256
  9. package/dist/{dev-DPkQVUTP.js → dev-BvHT7WZa.js} +1 -1
  10. package/dist/{dev-NCuEhNxs.js → dev-MacSQ1Ll.js} +2019 -1626
  11. package/dist/fileConventions-3bffWssN.js +30 -0
  12. package/dist/frameworkTableAssembly-BsnCKzQ6.js +2 -0
  13. package/dist/{frameworkTableAssembly-sg41s14F.js → frameworkTableAssembly-Cw5zJz6n.js} +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/inspect-C9gjHwBk.js +2 -0
  16. package/dist/{inspect-_ldwsAwH.js → inspect-DuLUrZp9.js} +14 -1
  17. package/dist/{inspectMetrics-dcC7gnxu.js → inspectMetrics-EQwH7BI4.js} +15 -15
  18. package/dist/manifestBuild-BVwS1Z_6.js +2 -0
  19. package/dist/{manifestBuild-Bs1Uw22_.js → manifestBuild-Dneq4_Jx.js} +1 -1
  20. package/dist/serveCommand-5ZFiNO1R.js +1241 -0
  21. package/dist/serveEntry.js +2 -2
  22. package/dist/{start-C_4VUDT8.js → start-C-ZWSDpg.js} +2 -2
  23. package/dist/startEntry.js +2 -2
  24. package/package.json +17 -17
  25. package/templates/AGENTS.core.md +12 -5
  26. package/templates/AGENTS.md +14 -7
  27. package/templates/agent-docs/_index.md +2 -2
  28. package/templates/agent-docs/_manifest.json +3 -3
  29. package/templates/agent-docs/cli.md +15 -0
  30. package/templates/agent-docs/data.md +306 -2
  31. package/templates/agent-docs/database/migrations.md +40 -0
  32. package/templates/agent-docs/database/schema.md +80 -0
  33. package/templates/agent-docs/deployment.md +9 -0
  34. package/templates/agent-docs/plugins.md +1 -1
  35. package/templates/agent-docs/reference.md +2 -2
  36. package/templates/agent-docs/security.md +18 -0
  37. package/templates/agent-docs/templates/apibackends.md +5 -5
  38. package/templates/agent-docs/templates/overview.md +1 -1
  39. package/templates/agent-docs/whats-new.md +263 -169
  40. package/templates/agent-docs/workflows.md +44 -20
  41. package/templates/apps/api-ai/package.json +7 -7
  42. package/templates/apps/api-auth/package.json +8 -8
  43. package/templates/apps/api-backend/package.json +7 -7
  44. package/templates/apps/api-backend-deactivation/package.json +7 -7
  45. package/templates/apps/api-backend-mail/package.json +8 -8
  46. package/templates/apps/api-backend-mariadb/package.json +9 -9
  47. package/templates/apps/api-backend-storage/package.json +8 -8
  48. package/templates/apps/api-data-advanced/package.json +8 -8
  49. package/templates/apps/api-durable/README.md +2 -1
  50. package/templates/apps/api-durable/events/orders.event.ts +18 -0
  51. package/templates/apps/api-durable/mutations/orders.place.mutation.server.ts +17 -15
  52. package/templates/apps/api-durable/package.json +8 -8
  53. package/templates/apps/api-durable/triggers/order.placed.trigger.tsx +6 -4
  54. package/templates/apps/api-feature-flags/package.json +9 -9
  55. package/templates/apps/api-governance/package.json +8 -8
  56. package/templates/apps/api-kv/package.json +8 -8
  57. package/templates/apps/api-moderation/package.json +8 -8
  58. package/templates/apps/api-observability/package.json +8 -8
  59. package/templates/apps/api-ratelimit/package.json +8 -8
  60. package/templates/apps/api-rbac/package.json +8 -8
  61. package/templates/apps/api-rest/package.json +7 -7
  62. package/templates/apps/api-saas/package.json +11 -11
  63. package/templates/apps/api-search/package.json +8 -8
  64. package/templates/apps/api-versioning/package.json +8 -8
  65. package/templates/apps/api-webhooks/README.md +2 -2
  66. package/templates/apps/api-webhooks/events/orders.event.ts +35 -0
  67. package/templates/apps/api-webhooks/package.json +9 -9
  68. package/templates/apps/api-webhooks/template.json +1 -1
  69. package/templates/apps/changelog/package.json +6 -6
  70. package/templates/apps/edge-functions/package.json +2 -2
  71. package/templates/apps/frontend-admin/package.json +8 -8
  72. package/templates/apps/frontend-app/package.json +8 -8
  73. package/templates/apps/frontend-blank/package.json +7 -7
  74. package/templates/apps/frontend-contact/package.json +7 -7
  75. package/templates/apps/frontend-dashboard/package.json +7 -7
  76. package/templates/apps/frontend-docs/package.json +7 -7
  77. package/templates/apps/frontend-i18n/package.json +6 -6
  78. package/templates/apps/frontend-landing/package.json +7 -7
  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/dist/apiBuild-UEM3QBke.js +0 -2
  84. package/dist/dbCommand-Cr__4ATv.js +0 -2
  85. package/dist/fileConventions-CBNPZVOV.js +0 -29
  86. package/dist/frameworkTableAssembly-DRJrAVr1.js +0 -2
  87. package/dist/inspect-BA67TF6v.js +0 -2
  88. package/dist/manifestBuild-i-fRHg_H.js +0 -2
  89. package/dist/serveCommand-C4gzDZzc.js +0 -1175
  90. package/templates/apps/api-webhooks/events/order.completed.webhook.tsx +0 -22
@@ -0,0 +1,1241 @@
1
+ import { ot as e, t } from "./inspectMetrics-EQwH7BI4.js";
2
+ import { s as n } from "./seedRunner-D6eu-u5U.js";
3
+ import { r, t as i } from "./appModuleLoader-C9r9mxZt.js";
4
+ import { f as a, m as o, n as s, p as c, u as l } from "./frameworkTableAssembly-Cw5zJz6n.js";
5
+ import { u } from "./fileConventions-3bffWssN.js";
6
+ import { p as d } from "./inspect-DuLUrZp9.js";
7
+ import { $ as f, A as p, B as ee, D as te, E as ne, F as m, G as h, H as re, I as g, J as ie, K as _, L as ae, M as oe, N as v, O as y, P as se, Q as ce, R as le, S as ue, T as de, U as fe, V as pe, W as me, X as b, Y as x, _ as he, _t as ge, b as S, bt as C, c as _e, ct as ve, dt as ye, et as be, ft as w, g as xe, gt as Se, h as Ce, ht as we, i as T, j as Te, k as Ee, lt as De, mt as E, o as D, pt as Oe, q as ke, r as Ae, st as je, t as Me, tt as Ne, u as Pe, ut as Fe, v as Ie, w as O, x as Le, y as Re, yt as ze, z as Be } from "./dev-MacSQ1Ll.js";
8
+ import { r as Ve, u as He } from "./apiBuild-BqhCSytw.js";
9
+ import { t as Ue } from "./bootTiming-BdyP9nYw.js";
10
+ import { n as k } from "./cliArgs-qdZSElM3.js";
11
+ import { basename as We, join as A } from "node:path";
12
+ import { pathToFileURL as j } from "node:url";
13
+ import { Cause as Ge, Effect as M, Layer as N, ManagedRuntime as Ke } from "effect";
14
+ import { createLogger as P } from "@voltro/logger";
15
+ import { existsSync as qe } from "node:fs";
16
+ import { AggregateRegistry as Je, Dispatcher as Ye, apiKeyManagementRoutes as Xe, applySoftDeleteScope as Ze, applyTenantScope as Qe, attachAnalyticsMirror as $e, awaitServerListening as et, bindMutation as F, bindStream as tt, bindSubscription as I, buildTracingLayer as nt, cancelWakeup as rt, compileCron as it, dataStoreApiKeyStore as at, dataStoreIdempotencyStore as ot, formatServerOnlyLeaks as L, frameworkApiKeyStrategy as st, installPolicyGuardResolver as R, loadResourceTuples as ct, makeActionRunner as lt, makeAdvisoryLockCoordinator as ut, makeApiKeyService as dt, makeApiKeyUsageBuffer as ft, makeApiKeyUsageFlusher as pt, makeAsyncKv as mt, makeCoordinatedScheduler as ht, makeEffectStoreLayer as gt, makeLazyWorkflowFacade as _t, makeMutationOutputCodec as vt, makeMutationRunner as yt, makeOneShotQueryRunner as bt, makeQueryDescriptorProducer as xt, makeQueryReauthorizer as St, makeQuerySubscriber as Ct, makeSchemaRegistry as wt, makeWorkflowFacade as Tt, makeWorkflowFacadeWithCallerContext as z, makeWorkflowLayers as Et, noopKv as Dt, onProcessShutdown as Ot, recordSubscriptionDelivery as kt, recordWorkflowRun as At, registerWakeup as B, resolveSecretsBackend as jt, runProvidedEffect as Mt, setSecretsBackend as Nt, setSystemStoreHandle as Pt, setTupleSource as Ft, singleCoordinator as It, startRpcServer as Lt, startScheduler as Rt, workflowToRpc as zt, wrapStoreWithBootCodec as Bt } from "@voltro/runtime";
17
+ import { RpcGroup as Vt } from "@effect/rpc";
18
+ import { SqlClient as Ht } from "@effect/sql";
19
+ import { and as V, ensureTableRegistered as Ut, eq as H, or as Wt } from "@voltro/database";
20
+ import { appStorageProvider as Gt, fromNodeReadable as Kt, getObjectStream as qt, putObjectStream as Jt, toNodeReadable as Yt } from "@voltro/plugin-storage";
21
+ import { AuthMiddleware as U, ConnectionInfoMiddleware as W, actionToRpc as G, anonymousSubject as Xt, isWireReachable as Zt, mutationToRpc as K, queryToRpc as q, streamToRpc as Qt, workflowCancelDescriptor as $t, workflowDomainEventsQueryDescriptor as J, workflowEventDeliveriesQueryDescriptor as en, workflowResumeDescriptor as tn, workflowRunEventsQueryDescriptor as nn, workflowRunQueryDescriptor as Y, workflowRunStepsQueryDescriptor as X, workflowRunsQueryDescriptor as Z, workflowSignalDescriptor as rn, workflowUpdateDescriptor as an } from "@voltro/protocol";
22
+ import { assertProductionSessionSecret as on } from "@voltro/protocol/session";
23
+ import { createHash as sn, timingSafeEqual as cn } from "node:crypto";
24
+ import { declaredSnapshot as ln, describeOutcome as un, runPlannedMigrations as dn } from "@voltro/database/sql";
25
+ import { getAuthSessionStrategy as fn } from "@voltro/plugin-auth";
26
+ import { collectPublicApiRoutes as pn, restRoutesToHttpRoutes as mn } from "@voltro/protocol/rest";
27
+ import { buildDeliverWebhookExecute as hn, buildWebhooksService as gn, defaultIncomingPath as _n, deliverWebhookWorkflow as vn, mountIncomingWebhook as yn } from "@voltro/plugin-webhooks";
28
+ import { channelFor as bn, getBroadcastPlugin as xn } from "@voltro/plugin-broadcast";
29
+ import { packBundle as Sn, runExport as Cn, runImport as wn, storageBlobSink as Tn, storageRefsBlobSource as En, unpackBundle as Dn, unpackBundleToDir as On } from "@voltro/data-transfer";
30
+ //#region src/bootRefusal.ts
31
+ var kn = "VoltroBootRefusal", An = (e) => {
32
+ let t = Error(e);
33
+ return t.name = kn, t;
34
+ }, jn = "/_voltro/admin/import", Mn = "/_voltro/admin/export", Q = (e, t) => ({
35
+ status: e,
36
+ contentType: "application/json; charset=utf-8",
37
+ body: JSON.stringify(t)
38
+ }), Nn = (e) => {
39
+ let t = e.authorization ?? e.Authorization, n = t ? /^Bearer\s+(.+)$/i.exec(t) : null;
40
+ return n ? n[1] : null;
41
+ }, Pn = (e, t) => cn(sn("sha256").update(e).digest(), sn("sha256").update(t).digest()), Fn = (e, t) => {
42
+ if (e.method.toUpperCase() !== "POST") return Q(405, { error: "method not allowed" });
43
+ if (!t || t.length < 16) return Q(503, { error: "data transfer misconfigured (no/weak secret)" });
44
+ let n = Nn(e.headers);
45
+ return !n || !Pn(n, t) ? Q(401, { error: "unauthorized" }) : null;
46
+ }, In = P({ scope: "voltro:admin-import" }), Ln = "VBUNDLE2", Rn = async function* (e) {
47
+ yield e;
48
+ }, zn = (e) => async (t) => {
49
+ let n = Fn(t, e.secret);
50
+ if (n) return n;
51
+ 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.rawBody.byteLength >= 8 && Buffer.from(t.rawBody.subarray(0, 8)).toString("latin1") === Ln, c, l;
52
+ if (s) c = Rn(t.rawBody), l = "upload";
53
+ else {
54
+ let n;
55
+ try {
56
+ n = JSON.parse(Buffer.from(t.rawBody).toString("utf8") || "{}");
57
+ } catch {
58
+ return Q(400, { error: "body must be a packed bundle archive or { bundleKey } JSON" });
59
+ }
60
+ if (typeof n.bundleKey != "string" || !n.bundleKey) return Q(400, { error: "body.bundleKey (string) is required for the storage transport" });
61
+ if (!e.openArchive) return Q(501, { error: "storage transport not configured on this instance" });
62
+ c = e.openArchive(n.bundleKey), l = "storage";
63
+ }
64
+ let u = await import("node:os"), d = await import("node:fs/promises"), f = await import("node:path"), p = await d.mkdtemp(f.join(u.tmpdir(), "voltro-admin-import-"));
65
+ try {
66
+ e.assetSink ? await Dn(c, {
67
+ dir: p,
68
+ blobs: e.assetSink
69
+ }) : await On(c, p);
70
+ let t = await M.runPromiseExit(wn({
71
+ store: e.store,
72
+ bundleDir: p,
73
+ ...r ? { mode: r } : {},
74
+ ...i ? { onConflict: i } : {},
75
+ ...a ? { atomic: a } : {},
76
+ ...e.snapshot ? { targetSnapshot: e.snapshot } : {},
77
+ force: o,
78
+ onWarn: (e) => In.warn("admin.import", { message: e }),
79
+ ...e.assetSink ? { assetsAlreadyRestored: !0 } : {}
80
+ }));
81
+ if (t._tag === "Failure") {
82
+ let e = t.cause._tag === "Fail" ? t.cause.error : void 0;
83
+ if (e && e._tag === "SchemaDriftError") {
84
+ let t = e;
85
+ return In.warn("admin.import refused (schema drift)", {
86
+ transport: l,
87
+ bundle: t.bundleFingerprint.slice(0, 16),
88
+ target: t.targetFingerprint.slice(0, 16)
89
+ }), Q(409, {
90
+ error: "schema drift",
91
+ bundleFingerprint: t.bundleFingerprint,
92
+ targetFingerprint: t.targetFingerprint,
93
+ diff: t.diff,
94
+ hint: "re-export against the current schema, or resend with x-import-force: 1"
95
+ });
96
+ }
97
+ throw Error(String(e?.message ?? e ?? "import failed"));
98
+ }
99
+ let n = t.value, s = n.tables.reduce((e, t) => e + t.rowCount, 0);
100
+ return In.info("admin.import", {
101
+ transport: l,
102
+ tables: n.tables.length,
103
+ rows: s,
104
+ mode: r ?? "upsert",
105
+ atomic: a
106
+ }), Q(200, {
107
+ tables: n.tables.length,
108
+ rows: s,
109
+ transport: l
110
+ });
111
+ } catch (e) {
112
+ return In.warn("admin.import failed", {
113
+ transport: l,
114
+ error: e?.message ?? String(e)
115
+ }), Q(500, {
116
+ error: "import failed",
117
+ message: e?.message ?? String(e)
118
+ });
119
+ } finally {
120
+ await d.rm(p, {
121
+ recursive: !0,
122
+ force: !0
123
+ });
124
+ }
125
+ }, Bn = P({ scope: "voltro:admin-export" }), Vn = async (e) => {
126
+ let t = [];
127
+ for await (let n of e) t.push(Buffer.from(n));
128
+ return new Uint8Array(Buffer.concat(t));
129
+ }, Hn = (e) => typeof e.tenant == "string" && e.tenant ? {
130
+ kind: "tenant",
131
+ tenantId: e.tenant
132
+ } : Array.isArray(e.tables) && e.tables.length ? {
133
+ kind: "tables",
134
+ tables: e.tables.filter((e) => typeof e == "string")
135
+ } : { kind: "all" }, Un = (e) => async (t) => {
136
+ let n = Fn(t, e.secret);
137
+ if (n) return n;
138
+ let r;
139
+ try {
140
+ r = JSON.parse(Buffer.from(t.rawBody).toString("utf8") || "{}");
141
+ } catch {
142
+ return Q(400, { error: "body must be JSON: { profile?, tenant?, tables?, consistency?, compression?, bundleKey? }" });
143
+ }
144
+ let i = {};
145
+ if (typeof r.profile == "string" && r.profile) {
146
+ if (!e.loadProfile) return Q(501, { error: "server-side profiles not configured on this instance" });
147
+ try {
148
+ i = await e.loadProfile(r.profile);
149
+ } catch (e) {
150
+ return Q(400, {
151
+ error: `profile '${r.profile}' could not be loaded`,
152
+ message: e?.message ?? String(e)
153
+ });
154
+ }
155
+ }
156
+ let a = r.consistency === "snapshot" ? "snapshot" : i.consistency ?? "live", o = (typeof r.compression == "string" ? r.compression : void 0) ?? i.compression, s = i.scope ?? Hn(r), c = typeof r.bundleKey == "string" && r.bundleKey.length > 0, l = r.assets === !0 && e.assetSource ? { blobs: e.assetSource } : {}, u = await import("node:os"), d = await import("node:fs/promises"), f = await import("node:path"), p = await d.mkdtemp(f.join(u.tmpdir(), "voltro-admin-export-"));
157
+ try {
158
+ let t = await M.runPromise(Cn({
159
+ store: e.store,
160
+ snapshot: e.snapshot,
161
+ dialect: e.dialect,
162
+ outDir: p,
163
+ ...i.subset ? { subset: i.subset } : {
164
+ scope: s,
165
+ ...e.tenantTables && e.tenantTables.length > 0 ? { tenantTables: e.tenantTables } : {}
166
+ },
167
+ consistency: a,
168
+ ...o ? { compression: o } : {},
169
+ ...i.masking ? { masking: i.masking } : {}
170
+ })), n = t.tables.reduce((e, t) => e + t.rowCount, 0), u = t.masking?.transformed.length ?? 0;
171
+ if (c) {
172
+ if (!e.putArchive) return Q(501, { error: "storage transport not configured on this instance" });
173
+ let i = r.bundleKey;
174
+ return await e.putArchive(i, () => Sn({
175
+ dir: p,
176
+ ...l
177
+ })), Bn.info("admin.export", {
178
+ transport: "storage",
179
+ tables: t.tables.length,
180
+ rows: n,
181
+ masked: u,
182
+ bundleKey: i
183
+ }), Q(200, {
184
+ bundleKey: i,
185
+ tables: t.tables.length,
186
+ rows: n,
187
+ masked: u,
188
+ transport: "storage"
189
+ });
190
+ }
191
+ let d = await Vn(Sn({
192
+ dir: p,
193
+ ...l
194
+ }));
195
+ return Bn.info("admin.export", {
196
+ transport: "download",
197
+ tables: t.tables.length,
198
+ rows: n,
199
+ masked: u,
200
+ bytes: d.byteLength
201
+ }), {
202
+ status: 200,
203
+ contentType: "application/octet-stream",
204
+ body: d,
205
+ headers: {
206
+ "x-export-tables": String(t.tables.length),
207
+ "x-export-rows": String(n),
208
+ "x-export-masked": String(u)
209
+ }
210
+ };
211
+ } catch (e) {
212
+ return Bn.warn("admin.export failed", { error: e?.message ?? String(e) }), Q(500, {
213
+ error: "export failed",
214
+ message: e?.message ?? String(e)
215
+ });
216
+ } finally {
217
+ await d.rm(p, {
218
+ recursive: !0,
219
+ force: !0
220
+ });
221
+ }
222
+ }, Wn = async (e) => {
223
+ let { resolve: t } = await import("node:path"), { existsSync: n } = await import("node:fs"), r = [
224
+ e,
225
+ `${e}.profile.ts`,
226
+ `data-profiles/${e}.ts`,
227
+ `data-profiles/${e}.profile.ts`
228
+ ].map((e) => t(process.cwd(), e)), i = r.find((e) => n(e));
229
+ if (!i) throw Error(`data profile '${e}' not found (looked for: ${r.join(", ")})`);
230
+ let a = await import(i), o = a.default ?? a.profile;
231
+ if (!o) throw Error(`data profile '${i}' has no default export`);
232
+ return o;
233
+ }, Gn = (e, t, n = {}) => (async function* () {
234
+ let r = await Yt((await M.runPromise(qt(e, t).pipe(M.timeout(n.openTimeout ?? "30 seconds")))).stream), i = n.stallMs ?? 12e4, a, o = () => {
235
+ a && clearTimeout(a), a = setTimeout(() => r.destroy(/* @__PURE__ */ Error(`storage read stalled for ${i}ms reading '${t}'`)), i);
236
+ };
237
+ try {
238
+ o();
239
+ for await (let e of r) o(), yield e instanceof Uint8Array ? e : new Uint8Array(e);
240
+ } finally {
241
+ a && clearTimeout(a), r.destroy();
242
+ }
243
+ })(), Kn = {
244
+ get: async () => void 0,
245
+ set: async () => {},
246
+ setWithTags: async () => {},
247
+ remove: async () => !1,
248
+ has: async () => !1,
249
+ clear: async () => {},
250
+ invalidateTag: async () => 0,
251
+ wrap: async (e, t, n) => n()
252
+ }, qn = async (e) => {
253
+ Pt({
254
+ dataStore: e.store,
255
+ schemaRegistry: e.schemaRegistry
256
+ });
257
+ let t = new Ye({
258
+ store: e.store,
259
+ ...e.snapshotCache ? { cache: e.snapshotCache } : {},
260
+ recordDelivery: (e) => kt({
261
+ label: e.label,
262
+ kind: e.kind,
263
+ durationMs: e.durationMs,
264
+ rowCount: e.rowCount
265
+ })
266
+ }), n = e.cache ?? Kn, r = e.kv ?? Dt, i, a, o, s = /* @__PURE__ */ new Map(), c = () => `wfctx_${globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`, l = async (t, n, r) => {
267
+ let i = {
268
+ ...r,
269
+ source: r.source ?? `workflow:${t}`
270
+ };
271
+ s.set(n, i);
272
+ try {
273
+ let r = await e.store.query({
274
+ table: "_voltro_workflow_start_contexts",
275
+ order: [],
276
+ predicate: H("executionId", n),
277
+ projection: ["id"],
278
+ skip: void 0,
279
+ take: 1
280
+ }), a = {
281
+ workflowName: t,
282
+ executionId: n,
283
+ subject: i.subject ?? null,
284
+ traceId: i.traceId ?? null,
285
+ source: i.source ?? null,
286
+ parentExecutionId: i.parentExecutionId ?? null,
287
+ parentClosePolicy: i.parentClosePolicy ?? null,
288
+ createdAt: /* @__PURE__ */ new Date()
289
+ };
290
+ r[0] === void 0 ? await e.store.insert("_voltro_workflow_start_contexts", {
291
+ id: c(),
292
+ ...a
293
+ }) : await e.store.update("_voltro_workflow_start_contexts", r[0].id, a);
294
+ } catch (e) {
295
+ process.stderr.write(`[workflow] failed to persist start context for ${t}/${n}: ${e?.message ?? String(e)}\n`);
296
+ }
297
+ }, u = async (t, n) => {
298
+ let r = s.get(n);
299
+ if (r !== void 0) return r;
300
+ try {
301
+ let t = (await e.store.query({
302
+ table: "_voltro_workflow_start_contexts",
303
+ order: [],
304
+ predicate: H("executionId", n),
305
+ projection: void 0,
306
+ skip: void 0,
307
+ take: 1
308
+ }))[0];
309
+ if (t === void 0) return;
310
+ let r = {
311
+ ...t.subject === null ? {} : { subject: t.subject },
312
+ ...t.traceId === null ? {} : { traceId: t.traceId },
313
+ ...t.source === null ? {} : { source: t.source },
314
+ ...t.parentExecutionId === null ? {} : { parentExecutionId: t.parentExecutionId },
315
+ ...t.parentClosePolicy === null ? {} : { parentClosePolicy: t.parentClosePolicy }
316
+ };
317
+ return s.set(n, r), r;
318
+ } catch (e) {
319
+ process.stderr.write(`[workflow] failed to load start context for ${n}: ${e?.message ?? String(e)}\n`);
320
+ return;
321
+ }
322
+ }, d = (e.discovered.workflows?.length ?? 0) > 0 ? _t(() => i) : void 0, f = (e.discovered.workflows?.length ?? 0) > 0 || (e.discovered.eventTriggers?.length ?? 0) > 0, p = f || (e.discovered.workflowWorkers?.length ?? 0) > 0 || e.scheduleCoordination === "cluster", te = e.tenantIsolation === "namespace", ne = (e.log ?? P({ scope: "voltro:serve" })).child("webhooks"), re, g = e.discovered.webhooks;
323
+ if (g && g.outgoing.length > 0 && e.workflowEngineLayer !== void 0) {
324
+ let t = e.workflowEngineLayer, i = w({
325
+ store: e.store,
326
+ schemaRegistry: e.schemaRegistry,
327
+ cache: n,
328
+ kv: r
329
+ }), a = g.outgoing.map((e) => e.descriptor);
330
+ re = gn(i, async (e) => {
331
+ let n = vn.execute(e).pipe(M.provide(vn.toLayer(hn(i, { events: a })).pipe(N.provideMerge(t))));
332
+ M.runPromise(n).catch((t) => {
333
+ ne.error("deliverWebhook workflow crashed", {
334
+ deliveryId: e.deliveryId,
335
+ targetId: e.targetId
336
+ }, t);
337
+ });
338
+ }, { events: a });
339
+ }
340
+ let ae = /* @__PURE__ */ new Map();
341
+ if (g) for (let e of g.incoming) {
342
+ let t = e.descriptor.path ?? _n(e.descriptor.id), n = `VOLTRO_WEBHOOK_SECRET_${e.descriptor.id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`, r = yn(e.descriptor, {
343
+ resolveSecret: async () => process.env[n] ?? null,
344
+ resolveWorkflows: () => d === void 0 ? void 0 : z(d, {
345
+ traceId: `incoming:${e.descriptor.id}`,
346
+ source: `incoming:${e.descriptor.id}`
347
+ }),
348
+ log: (e) => {
349
+ let t = {
350
+ webhookId: e.webhookId,
351
+ status: e.status,
352
+ signatureOk: String(e.signatureOk),
353
+ idempotency: e.idempotency,
354
+ durationMs: e.durationMs
355
+ };
356
+ e.status >= 500 ? ne.error("incoming delivery failed", t) : e.status >= 400 ? ne.warn("incoming delivery rejected", t) : ne.info("incoming delivery handled", t);
357
+ }
358
+ });
359
+ ae.set(t, { handle: r });
360
+ }
361
+ R(), Ft((t) => ct(e.store, t.subjectId, t.resourceType, t.resourceId));
362
+ let oe = (e.discovered.outboxHandlers?.length ?? 0) > 0 ? ie({
363
+ handlers: e.discovered.outboxHandlers ?? [],
364
+ store: e.store,
365
+ log: (e.log ?? P({ scope: "voltro:serve" })).child("outbox")
366
+ }) : void 0, v = _({
367
+ definitions: (e.discovered.connections ?? []).map((e) => e.definition),
368
+ store: e.store,
369
+ publicUrl: h(e.port ?? 4e3),
370
+ log: (e.log ?? P({ scope: "voltro:serve" })).child("connections")
371
+ });
372
+ S({
373
+ events: e.discovered.events ?? [],
374
+ rpcTags: [
375
+ ...e.discovered.queries.map((e) => e.descriptor.name),
376
+ ...e.discovered.mutations.map((e) => e.descriptor.name),
377
+ ...e.discovered.actions.map((e) => e.descriptor.name),
378
+ ...(e.discovered.streams ?? []).map((e) => e.descriptor.name)
379
+ ]
380
+ });
381
+ let ce = (e.log ?? P({ scope: "voltro:serve" })).child("events"), le = e.broadcastNamespace ?? he(e.plugins, void 0), fe = Ie(e.plugins, le, ce), pe = e.membership?.instanceId ?? process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, me = e.membership ?? Re(e.plugins, {
382
+ instanceId: pe,
383
+ namespace: le,
384
+ meta: { mode: "serve" },
385
+ logger: ce
386
+ }), b = Le({
387
+ events: e.discovered.events ?? [],
388
+ origin: pe,
389
+ ...fe.publishRemote === void 0 ? {} : { publishRemote: fe.publishRemote }
390
+ }), ge = (e.discovered.events ?? []).length > 0 ? await fe.attach(b.bus) : null, C = ye({
391
+ store: e.store,
392
+ schemaRegistry: e.schemaRegistry,
393
+ cache: n,
394
+ kv: r,
395
+ ...re === void 0 ? {} : { webhooksService: re },
396
+ ...d === void 0 ? {} : { workflowsProxy: d },
397
+ eventTriggers: e.discovered.eventTriggers ?? [],
398
+ namespaceIsolationOn: te,
399
+ ...oe === void 0 ? {} : { outbox: { nudge: oe.nudge } },
400
+ ...v.active ? { connections: { registry: v.registry } } : {},
401
+ eventBus: b.bus
402
+ }), _e = N.succeed(Je, m), ve = (t, n) => {
403
+ let r = t.pipe(M.provide(gt(n)));
404
+ return (e.baseLayer ? r.pipe(M.provide(e.baseLayer)) : r).pipe(M.provide(_e));
405
+ }, be = (e, t) => Mt(ve(e, t)), xe = yt({
406
+ store: e.store,
407
+ buildContext: (e, t, n) => C(e, t, n),
408
+ runEffect: be,
409
+ undoCapture: Ee()
410
+ }), Se = y(), Ce = lt({
411
+ buildContext: (e) => C(e),
412
+ runEffect: be
413
+ }), we = {
414
+ buildContext: (e) => C(e),
415
+ finalize: (t, n) => Ze(Qe(t, e.tenantScopedTables, n.subject.tenantId), e.softDeleteScopedTables),
416
+ provideEffect: ve
417
+ }, T = xt(we), Te = bt({
418
+ ...we,
419
+ queryRows: (t) => e.store.query(t)
420
+ }), De = Ct({
421
+ ...we,
422
+ subscribeDescriptor: (e, n, r) => t.subscribe(e, n, r),
423
+ subscribeComputed: (e, n, r) => t.subscribeComputed(e, n, r)
424
+ }), E = (e) => e.filter((e) => Zt(e.descriptor)), D = {};
425
+ for (let n of [
426
+ ...E(e.discovered.queries),
427
+ ...Se.queries,
428
+ ...v.queries
429
+ ]) D[n.descriptor.name] = (e) => I(T(n, e), t, `subscription.${n.descriptor.name}`, void 0, void 0, St(n, e));
430
+ for (let t of [
431
+ ...E(e.discovered.mutations),
432
+ ...Se.mutations,
433
+ ...v.mutations
434
+ ]) {
435
+ let n = vt(t.descriptor.output);
436
+ D[t.descriptor.name] = (r) => F(async (e, n) => xe(t, e, n), r, `mutation.${t.descriptor.name}`, n, e.idempotency);
437
+ }
438
+ for (let t of [...E(e.discovered.actions), ...v.actions]) {
439
+ let n = vt(t.descriptor.output);
440
+ D[t.descriptor.name] = (r) => F(async (e, n) => Ce(t, e, n), r, `action.${t.descriptor.name}`, n, e.idempotency);
441
+ }
442
+ let Oe = () => `public-${Math.random().toString(36).slice(2, 10)}`, ke = [
443
+ ...e.discovered.queries.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
444
+ descriptor: e.descriptor,
445
+ invoke: (t, n) => Te(e, t, {
446
+ subject: n.subject,
447
+ traceId: Oe()
448
+ }),
449
+ subscribe: (t, n, r) => De(e, t, {
450
+ subject: n.subject,
451
+ traceId: Oe()
452
+ }, r)
453
+ })),
454
+ ...e.discovered.mutations.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
455
+ descriptor: e.descriptor,
456
+ invoke: (t, n) => xe(e, t, {
457
+ subject: n.subject,
458
+ traceId: Oe()
459
+ })
460
+ })),
461
+ ...e.discovered.actions.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
462
+ descriptor: e.descriptor,
463
+ invoke: (t, n) => Ce(e, t, {
464
+ subject: n.subject,
465
+ traceId: Oe()
466
+ })
467
+ }))
468
+ ], Ae = ke.length > 0 ? mn(pn(ke), {
469
+ store: e.store,
470
+ resolveSubject: (t) => e.resolveSubject(t, -1)
471
+ }) : [], Me = e.dataTransferSecret ?? process.env.VOLTRO_DATA_TRANSFER_SECRET, Ne = Me && Me.length >= 16 ? [{
472
+ method: "POST",
473
+ path: jn,
474
+ handle: zn({
475
+ secret: Me,
476
+ store: e.store,
477
+ ...e.dataTransferSnapshot ? { snapshot: e.dataTransferSnapshot } : {},
478
+ assetSink: Tn(Gt()),
479
+ openArchive: (e) => Gn(Gt(), e)
480
+ })
481
+ }, {
482
+ method: "POST",
483
+ path: Mn,
484
+ handle: Un({
485
+ secret: Me,
486
+ store: e.store,
487
+ snapshot: e.dataTransferSnapshot ?? { tables: [] },
488
+ dialect: e.dataTransferDialect ?? "memory",
489
+ tenantTables: [...e.tenantScopedTables],
490
+ loadProfile: Wn,
491
+ assetSource: En(Gt(), e.store),
492
+ putArchive: async (e, t) => {
493
+ let { Readable: n } = await import("node:stream"), r = Gt(), i = Kt("storage", () => n.from(t()));
494
+ await M.runPromise(Jt(r, e, i, { contentType: "application/octet-stream" }));
495
+ }
496
+ })
497
+ }] : [], Pe = [
498
+ ...e.httpRoutes ?? [],
499
+ ...Ae,
500
+ ...Ne,
501
+ ...v.httpRoutes
502
+ ];
503
+ Object.assign(D, b.handlers);
504
+ for (let t of E(e.discovered.streams ?? [])) D[t.descriptor.name] = (n) => tt((r) => {
505
+ let i = C(r), a = t.executor(n, i);
506
+ if (M.isEffect(a)) {
507
+ let t = a.pipe(M.provide(gt(i.store)));
508
+ return (e.baseLayer ? t.pipe(M.provide(e.baseLayer)) : t).pipe(M.provide(_e));
509
+ }
510
+ return typeof a == "object" && a && typeof a.then == "function" ? M.promise(() => a) : a;
511
+ }, `stream.${t.descriptor.name}`);
512
+ for (let t of e.discovered.workflows ?? []) D[t.definition.name] = (e) => F(async (e, n) => {
513
+ let r = n;
514
+ return z(d, {
515
+ subject: r.subject,
516
+ traceId: r.traceId,
517
+ source: "workflow-rpc"
518
+ }).start(t.definition.name, e);
519
+ }, e, `workflow.${t.definition.name}`);
520
+ f && (D[Y.name] = (e) => I(T({
521
+ descriptor: Y,
522
+ executor: (e) => {
523
+ let t = e.id;
524
+ return {
525
+ table: "_voltro_workflow_runs",
526
+ order: [{
527
+ column: "startedAt",
528
+ direction: "desc"
529
+ }],
530
+ predicate: Wt(H("id", t), H("executionId", t)),
531
+ take: 1,
532
+ skip: void 0,
533
+ projection: void 0
534
+ };
535
+ }
536
+ }, e), t, `subscription.${Y.name}`), D[Z.name] = (e) => I(T({
537
+ descriptor: Z,
538
+ executor: (e) => {
539
+ let t = e, n = [...t.tag === void 0 ? [] : [H("tag", t.tag)], ...t.status === void 0 ? [] : [H("status", t.status)]], r = Number.isFinite(t.limit) && t.limit !== void 0 ? Math.min(Math.max(Math.floor(t.limit), 1), 500) : 100;
540
+ return {
541
+ table: "_voltro_workflow_runs",
542
+ order: [{
543
+ column: "startedAt",
544
+ direction: "desc"
545
+ }],
546
+ predicate: n.length === 0 ? void 0 : n.length === 1 ? n[0] : V(...n),
547
+ take: r,
548
+ skip: void 0,
549
+ projection: void 0
550
+ };
551
+ }
552
+ }, e), t, `subscription.${Z.name}`), D[X.name] = (e) => I(T({
553
+ descriptor: X,
554
+ executor: (e) => {
555
+ let t = e.runId;
556
+ return {
557
+ table: "_voltro_workflow_run_steps",
558
+ order: [{
559
+ column: "startedAt",
560
+ direction: "asc"
561
+ }],
562
+ predicate: H("runId", t),
563
+ take: 1e3,
564
+ skip: void 0,
565
+ projection: void 0
566
+ };
567
+ }
568
+ }, e), t, `subscription.${X.name}`), D[nn.name] = (e) => I(T({
569
+ descriptor: nn,
570
+ executor: (e) => {
571
+ let t = e.runId;
572
+ return {
573
+ table: "_voltro_workflow_run_events",
574
+ order: [{
575
+ column: "occurredAt",
576
+ direction: "asc"
577
+ }],
578
+ predicate: H("runId", t),
579
+ take: 1e3,
580
+ skip: void 0,
581
+ projection: void 0
582
+ };
583
+ }
584
+ }, e), t, `subscription.${nn.name}`), D[J.name] = (e) => I(T({
585
+ descriptor: J,
586
+ executor: (e) => {
587
+ let t = e;
588
+ return {
589
+ table: "_voltro_workflow_events",
590
+ order: [{
591
+ column: "occurredAt",
592
+ direction: "desc"
593
+ }],
594
+ predicate: t.name === void 0 ? void 0 : H("name", t.name),
595
+ take: Math.max(1, Math.min(500, t.limit ?? 100)),
596
+ skip: void 0,
597
+ projection: void 0
598
+ };
599
+ }
600
+ }, e), t, `subscription.${J.name}`), D[en.name] = (e) => I(T({
601
+ descriptor: en,
602
+ executor: (e) => {
603
+ let t = e.eventId;
604
+ return {
605
+ table: "_voltro_workflow_event_deliveries",
606
+ order: [{
607
+ column: "createdAt",
608
+ direction: "asc"
609
+ }],
610
+ predicate: H("eventId", t),
611
+ take: 500,
612
+ skip: void 0,
613
+ projection: void 0
614
+ };
615
+ }
616
+ }, e), t, `subscription.${en.name}`), D[$t.name] = (t) => F(async (t, n) => {
617
+ let r = t;
618
+ return await Fe(e.store, n.subject, { executionId: r.executionId }), await d.cancel(r.workflowName, r.executionId), await qe(r.workflowName, r.executionId, "workflow.cancel"), { ok: !0 };
619
+ }, t, `action.${$t.name}`), D[tn.name] = (t) => F(async (t, n) => {
620
+ let r = t;
621
+ return await Fe(e.store, n.subject, { executionId: r.executionId }), await d.resume(r.workflowName, r.executionId), { ok: !0 };
622
+ }, t, `action.${tn.name}`), D[rn.name] = (t) => F(async (t, n) => {
623
+ let r = t;
624
+ return await Fe(e.store, n.subject, { id: r.id }), d.signal({ id: r.id }, r.signalName, r.payload);
625
+ }, t, `action.${rn.name}`), D[an.name] = (t) => F(async (t, n) => {
626
+ let r = t;
627
+ return await Fe(e.store, n.subject, { id: r.id }), d.update({ id: r.id }, r.updateName, r.payload, r.timeoutMs === void 0 ? void 0 : { timeoutMs: r.timeoutMs });
628
+ }, t, `action.${an.name}`));
629
+ let ze = [
630
+ ...E(e.discovered.queries).map((e) => q(e.descriptor)),
631
+ ...E(e.discovered.mutations).map((e) => K(e.descriptor)),
632
+ ...E(e.discovered.actions).map((e) => G(e.descriptor)),
633
+ ...Se.queries.map((e) => q(e.descriptor)),
634
+ ...Se.mutations.map((e) => K(e.descriptor)),
635
+ ...v.queries.map((e) => q(e.descriptor)),
636
+ ...v.mutations.map((e) => K(e.descriptor)),
637
+ ...v.actions.map((e) => G(e.descriptor)),
638
+ ...E(e.discovered.streams ?? []).map((e) => Qt(e.descriptor)),
639
+ ...b.rpcs,
640
+ ...(e.discovered.workflows ?? []).map((e) => zt(e.definition)),
641
+ ...f ? [
642
+ q(Y),
643
+ q(Z),
644
+ q(X),
645
+ q(nn),
646
+ q(J),
647
+ q(en),
648
+ G($t),
649
+ G(tn),
650
+ G(rn),
651
+ G(an)
652
+ ] : []
653
+ ], Ve = Vt.make(...ze).middleware(U).middleware(W), He = N.succeed(U, U.of(({ headers: t, clientId: n }) => M.promise(() => e.resolveSubject(t, n)))), Ue = N.succeed(W, W.of(({ headers: e, clientId: t }) => M.succeed({
654
+ clientId: t,
655
+ ...e["idempotency-key"] ? { idempotencyKey: e["idempotency-key"] } : {}
656
+ }))), k = e.dormancyTenantId ?? "default", We = e.dormancy === "sleep" ? {
657
+ register: (t, n, r) => B(e.store, {
658
+ tenantId: r ?? k,
659
+ kind: "workflow",
660
+ refId: t,
661
+ wakeAt: n
662
+ }),
663
+ cancel: (t, n) => rt(e.store, {
664
+ tenantId: n ?? k,
665
+ kind: "workflow",
666
+ refId: t
667
+ }).then(() => {})
668
+ } : void 0, A = p ? await import("@voltro/workflow") : void 0, j = A?.makeWorkflowRunRecorder({
669
+ store: e.store,
670
+ ...We === void 0 ? {} : { wakeups: We }
671
+ }), Ge = async (t, n) => {
672
+ await A.closeWorkflowChildrenForParent({
673
+ store: e.store,
674
+ parentExecutionId: t,
675
+ parentStatus: n,
676
+ recorder: j,
677
+ log: { warn: (e, t) => {
678
+ process.stderr.write(`[workflow] ${e} ${t ? JSON.stringify(t) : ""}\n`);
679
+ } },
680
+ interruptChild: async (t, n) => {
681
+ let r = (e.discovered.workflows ?? []).find((e) => e.definition.name === t);
682
+ if (!r) throw Error(`Unknown child workflow: ${t}`);
683
+ if (!a) throw Error("Workflow runtime is not ready");
684
+ await a.runPromise(r.definition.interrupt(n));
685
+ }
686
+ });
687
+ }, qe = async (t, n, r) => {
688
+ let i = (await e.store.query({
689
+ table: "_voltro_workflow_runs",
690
+ order: [],
691
+ predicate: H("executionId", n),
692
+ projection: void 0,
693
+ skip: void 0,
694
+ take: 1
695
+ }))[0];
696
+ if (i === void 0) return;
697
+ let a = await e.store.update("_voltro_workflow_runs", i.id, {
698
+ status: "cancelled",
699
+ cancelled: !0,
700
+ completedAt: /* @__PURE__ */ new Date()
701
+ }), o = i.subject?.tenantId ?? void 0;
702
+ a && await j.recordEvent({
703
+ runId: i.id,
704
+ eventType: "run-cancelled",
705
+ payload: {
706
+ reason: r,
707
+ workflowName: t,
708
+ executionId: n,
709
+ ...o == null ? {} : { tenantId: o }
710
+ }
711
+ }), a && await Ge(n, "cancelled");
712
+ }, Xe = [...Et(e.discovered.workflows ?? [], {
713
+ buildContext: (t, n) => e.buildContextForWorkflow?.(t, n) ?? C({
714
+ subject: t.subject,
715
+ traceId: t.traceId
716
+ }, e.store, void 0, `workflow:${n.workflowName}`, { parentExecutionId: n.executionId }),
717
+ resolveStartContext: u
718
+ }, (t, n, r) => {
719
+ let i = A.getWorkflowVersionMetadata(t.definition);
720
+ return A.wrapWorkflowExecuteWithRunRecording({
721
+ name: t.definition.name,
722
+ store: e.store,
723
+ subject: r.subject,
724
+ source: r.source ?? null,
725
+ traceId: r.traceId,
726
+ workflowVersion: i.version,
727
+ workflowCompatibleVersions: i.compatibleWith,
728
+ workflowPatches: i.patches,
729
+ parentExecutionId: r?.parentExecutionId ?? null,
730
+ parentClosePolicy: r?.parentClosePolicy ?? null,
731
+ onParentClose: ({ executionId: e, status: t }) => Ge(e, t),
732
+ recorder: j,
733
+ recordRun: At
734
+ }, n);
735
+ }), ...e.discovered.workflowWorkers ?? []], $e = Xe.length > 0 ? N.mergeAll(...Xe) : N.empty;
736
+ if (((e.discovered.workflows?.length ?? 0) > 0 || (e.discovered.workflowWorkers?.length ?? 0) > 0 || e.scheduleCoordination === "cluster") && e.workflowEngineLayer !== void 0) {
737
+ let t = $e.pipe(N.provideMerge(e.workflowEngineLayer));
738
+ a = Ke.make(e.baseLayer === void 0 ? t : t.pipe(N.provideMerge(e.baseLayer))), await a.runPromise(M.void), i = (e.discovered.workflows?.length ?? 0) > 0 ? Tt({
739
+ workflows: e.discovered.workflows ?? [],
740
+ runEffect: (e) => a.runPromise(e),
741
+ rememberStartContext: l,
742
+ signal: async (t, n, r) => {
743
+ let i = await A.sendWorkflowSignal({
744
+ store: e.store,
745
+ recorder: j,
746
+ target: t,
747
+ signalName: n,
748
+ payload: r
749
+ });
750
+ return await a.runPromise(A.completeSuspendingSignal({
751
+ store: e.store,
752
+ target: t,
753
+ signalName: n,
754
+ payload: r
755
+ })).catch(() => {}), i;
756
+ },
757
+ update: (t, n, r, i) => A.sendWorkflowUpdate({
758
+ store: e.store,
759
+ recorder: j,
760
+ target: t,
761
+ updateName: n,
762
+ payload: r,
763
+ ...i === void 0 ? {} : { options: i }
764
+ }),
765
+ listRuns: (t) => O(e.store, t),
766
+ retry: (t, n) => de({
767
+ store: e.store,
768
+ workflows: e.discovered.workflows ?? [],
769
+ runPromise: (e) => a.runPromise(e)
770
+ }, t, n)
771
+ }) : void 0;
772
+ }
773
+ let it = N.mergeAll(Ve.toLayer(D), He, Ue), at = je(D, e.discovered.queries.map((e) => e.descriptor.name), f), ot = N.mergeAll(Ve.toLayer(at), He, Ue), L = e.observability, st = await nt({
774
+ ...L && L.spanProcessors.length > 0 ? { extraSpanProcessors: L.spanProcessors } : {},
775
+ ...L && L.metricReaders.length > 0 ? { extraMetricReaders: L.metricReaders } : {},
776
+ ...L && Object.keys(L.resourceAttributes).length > 0 ? { resourceAttributes: L.resourceAttributes } : {},
777
+ ...L && L.sampler !== void 0 ? { sampler: L.sampler } : {}
778
+ }), dt = !1, ft = e.store.ping ? () => e.store.ping().then(() => !0).catch(() => !1) : void 0, { server: pt, shutdown: mt } = Lt({
779
+ group: Ve,
780
+ handlersLayer: it,
781
+ httpHandlersLayer: ot,
782
+ port: e.port ?? 4e3,
783
+ ...e.host === void 0 ? {} : { host: e.host },
784
+ path: e.path ?? "/ws",
785
+ tracerLayer: st.layer,
786
+ healthCheck: {
787
+ isReady: () => dt,
788
+ ...ft ? { ping: ft } : {}
789
+ },
790
+ ...Pe.length > 0 ? { httpRoutes: Pe } : {},
791
+ ...e.getStore === void 0 ? {} : { getStore: e.getStore },
792
+ ...ae.size > 0 ? { webhookRoutes: ae } : {},
793
+ ...e.inspectRoute === void 0 ? {} : { inspectRoute: e.inspectRoute }
794
+ });
795
+ if (await et(pt), (e.discovered.schedules?.length ?? 0) > 0) {
796
+ let t = (e.scheduleCoordination ?? "single") === "advisoryLock" ? ut(e.store, e.scheduleReplicaId ?? `pid-${process.pid}`) : It;
797
+ o = await Rt(e.discovered.schedules ?? [], {
798
+ store: e.store,
799
+ coordinator: t,
800
+ defaultTrigger: e.scheduleDefaultTrigger ?? "self",
801
+ replicaId: e.scheduleReplicaId ?? `pid-${process.pid}`,
802
+ armSelf: e.scheduleArmSelf ?? !0,
803
+ dormancy: e.dormancy ?? "always-on",
804
+ ...e.dormancyTenantId === void 0 ? {} : { dormancyTenantId: e.dormancyTenantId },
805
+ buildContext: ({ traceId: t, scheduleName: n, subject: r }) => C({
806
+ subject: r,
807
+ traceId: t
808
+ }, e.store, void 0, `schedule:${n}`),
809
+ log: {
810
+ info: (e, t) => {
811
+ process.stdout.write(`[schedule] ${e} ${t ? JSON.stringify(t) : ""}\n`);
812
+ },
813
+ warn: (e, t) => {
814
+ process.stderr.write(`[schedule] ${e} ${t ? JSON.stringify(t) : ""}\n`);
815
+ },
816
+ error: (e, t) => {
817
+ process.stderr.write(`[schedule] ERROR ${e} ${t ? JSON.stringify(t) : ""}\n`);
818
+ },
819
+ debug: () => {}
820
+ },
821
+ ...e.scheduleFireInterceptor === void 0 ? {} : { interceptFire: e.scheduleFireInterceptor },
822
+ ...e.onScheduleRunEvent === void 0 ? {} : { onRunEvent: e.onScheduleRunEvent }
823
+ }), e.onSchedulerReady?.(o);
824
+ }
825
+ let ht = e.log ?? P({ scope: "voltro:serve" }), wt, Ot;
826
+ if ((e.discovered.subscribers?.length ?? 0) > 0 && (wt = x(e.discovered.subscribers ?? [], e.store, ht.child("subscribe"), e.schemaRegistry, b.bus)), (e.discovered.reactions?.length ?? 0) > 0) {
827
+ let t = ht.child("reaction");
828
+ Ot = Be(e.discovered.reactions ?? [], e.store, {
829
+ runAct: async (n, r) => {
830
+ if (n.kind === "workflow") {
831
+ if (d === void 0) {
832
+ t.warn("reaction workflow act skipped — no workflow engine in this app", { workflow: n.workflow });
833
+ return;
834
+ }
835
+ let e = r.new ?? r.old ?? {};
836
+ await z(d, {
837
+ traceId: `reaction:${n.workflow}`,
838
+ source: `reaction:${n.workflow}`
839
+ }).start(n.workflow, e);
840
+ return;
841
+ }
842
+ await ee(n.agent, r, {
843
+ findAgentSend: (t) => e.discovered.actions.find((e) => e.descriptor.name === `${t}.send`),
844
+ runAction: (e, t, n) => Promise.resolve(Ce(e, t, n)),
845
+ makeSubject: (e) => Xt(e),
846
+ now: () => Date.now(),
847
+ log: t
848
+ });
849
+ },
850
+ checkBudget: async (n, r) => {
851
+ try {
852
+ let { requireAiBudget: t } = await import("@voltro/ai");
853
+ return (await M.runPromise(M.either(t(e.store, {
854
+ tenantId: n,
855
+ limitUsd: r
856
+ }))))._tag === "Right";
857
+ } catch (e) {
858
+ return t.warn("reaction budget check failed — refusing the act", { tenantId: n }, e), !1;
859
+ }
860
+ }
861
+ }, t);
862
+ }
863
+ let jt;
864
+ return (e.discovered.aggregates?.length ?? 0) > 0 && (jt = await se({
865
+ discovered: e.discovered.aggregates ?? [],
866
+ store: e.store,
867
+ log: ht.child("aggregate"),
868
+ ...e.analytics === void 0 ? {} : { analytics: e.analytics },
869
+ ...e.aggregateStorage === void 0 ? {} : { storage: e.aggregateStorage },
870
+ ...e.aggregateCoordinator === void 0 ? {} : { coordinator: e.aggregateCoordinator }
871
+ }), _e = N.succeed(Je, jt.registry)), dt = !0, e.bootTiming?.mark("ready"), {
872
+ dispatcher: t,
873
+ server: pt,
874
+ scheduler: o,
875
+ eventsSnapshot: ue(b.bus, b.declared),
876
+ membersSnapshot: () => ({
877
+ members: me.membership.list(),
878
+ capturedAt: Date.now()
879
+ }),
880
+ close: async () => {
881
+ dt = !1, await ge?.detach(), await me.detach(), jt?.detach(), Ot?.(), wt?.(), await o?.shutdown(), t.close(), await a?.dispose(), await new Promise((e) => pt.close(() => e())), await mt();
882
+ }
883
+ };
884
+ }, $ = P({ scope: "voltro:serve" }), Jn = (e, t, n) => (e === "production" || e === "staging") && t !== "memory" && n !== "0", Yn = k, Xn = async (e) => {
885
+ let t = He(process.cwd());
886
+ if (qe(t)) {
887
+ let n;
888
+ try {
889
+ let e = await import(j(t).href);
890
+ typeof e.runServe == "function" ? n = e.runServe : $.warn("serve bundle has no runServe export — using the standard serve path");
891
+ } catch (e) {
892
+ $.warn("serve bundle failed to load — using the standard serve path", {}, e);
893
+ }
894
+ if (n) return $.info("serve: booting from the precompiled serve bundle"), n(e);
895
+ }
896
+ return Zn(e);
897
+ }, Zn = async (ee) => {
898
+ let m = Ue();
899
+ process.env.NODE_ENV || (process.env.NODE_ENV = "production");
900
+ try {
901
+ on();
902
+ } catch (e) {
903
+ throw An(e instanceof Error ? e.message : String(e));
904
+ }
905
+ let h = process.cwd(), ie = Number(process.env.PORT ?? Yn(ee, "--port") ?? 4e3), _ = await _e(h);
906
+ Nt(jt(_?.secrets)), await e({
907
+ rawEnv: _?.env,
908
+ appType: "api",
909
+ root: h,
910
+ log: $,
911
+ generateTypes: !1
912
+ }), m.mark("config");
913
+ let y = (process.env.DB_DIALECT ?? _?.store ?? "memory").toLowerCase(), se = (y === "mariadb" || y === "postgres" || y === "mssql") && (process.env.CDC ?? "1") !== "0", ue = y === "mariadb" ? "mariadb" : y === "mssql" ? "mssql" : void 0, de = Ve(h);
914
+ if (!i() && qe(de)) try {
915
+ let e = await import(j(de).href);
916
+ if (e.modules) {
917
+ let t = {};
918
+ for (let [n, r] of Object.entries(e.modules)) t[A(h, n)] = r;
919
+ r(t), $.info("precompiled api bundle loaded", { modules: Object.keys(t).length });
920
+ }
921
+ } catch (e) {
922
+ $.warn("precompiled api bundle failed to load — falling back to source", {}, e);
923
+ }
924
+ let x = await Ce(h), S = await Pe(x, { cdc: se && ue !== void 0 });
925
+ {
926
+ let e = me(S.serverOnlyLeaks, fe(process.env, "strict"), L, "`voltro serve`");
927
+ if (e.action === "fail") throw An(e.message ?? "");
928
+ e.action === "warn" && $.warn(e.message ?? "");
929
+ }
930
+ let ye = x.filter((e) => Te.test(e)), w = ye.length > 0 ? await oe(ye, $.child("webhooks")) : {
931
+ outgoing: [],
932
+ incoming: [],
933
+ providers: []
934
+ }, Ee = v(S.events), je = w.outgoing.length + w.incoming.length + w.providers.length + Ee.length === 0 ? void 0 : {
935
+ ...w,
936
+ outgoing: [...w.outgoing, ...Ee]
937
+ }, Fe = s({
938
+ mix: S.featureMix,
939
+ plugins: _?.plugins ?? [],
940
+ cdc: se && ue !== void 0,
941
+ ...ue ? { cdcDialect: ue } : {}
942
+ }), Ie = _?.analytics !== void 0 && _.analytics.kind !== "noop" && y !== "memory" ? (await n(y)).makeSqlLayer(D()) : void 0, O = await f({
943
+ spec: _?.analytics,
944
+ sqlLayer: Ie,
945
+ log: $
946
+ }), Le = (() => {
947
+ let e = new Set(S.tables.map((e) => e.tableName)), t = [...S.tables];
948
+ for (let n of [...Fe, ...O.tables]) e.has(n.tableName) || (e.add(n.tableName), t.push(n));
949
+ return t;
950
+ })();
951
+ for (let e of Le) Ut(e);
952
+ let Be = (process.env.NODE_ENV ?? "").toLowerCase();
953
+ if (Jn(Be, y, process.env.VOLTRO_AUTO_MIGRATE)) {
954
+ let e = (await n(y)).makeSqlLayer(D()), t = await M.runPromise(Ht.SqlClient.pipe(M.flatMap((e) => dn(e, Le, {
955
+ appliedBy: `serve:${Be}`,
956
+ environment: "prod",
957
+ dialectId: y
958
+ })), M.provide(e)));
959
+ t.kind === "prod-mismatch" && ($.error(un(t, y)), $.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(t, y));
960
+ }
961
+ let He = wt(Le);
962
+ m.mark("discover");
963
+ let k = await T(_, void 0), P = Bt(k, y);
964
+ for (let e of ge({
965
+ dialect: String(_?.store ?? process.env.DB_DIALECT ?? "postgres"),
966
+ changeStrategy: (process.env.CDC ?? "1") === "0" ? "inline" : "cdc",
967
+ dbUrl: process.env.DB_URL,
968
+ tables: S.tables.map((e) => ({
969
+ tableName: e.tableName,
970
+ isReactive: e.isReactive === !0
971
+ })),
972
+ querySources: S.queries.flatMap((e) => {
973
+ let t = e.descriptor.source;
974
+ return t === void 0 ? [] : typeof t == "string" ? [t] : [...t];
975
+ })
976
+ })) e.level === "warn" ? $.warn(e.message) : $.info(e.message);
977
+ {
978
+ let e = Se(we({
979
+ tables: S.tables.map((e) => ({ tableName: e.tableName })),
980
+ queries: S.queries.map((e) => ({
981
+ name: e.descriptor.name,
982
+ source: e.descriptor.source
983
+ }))
984
+ }));
985
+ e !== void 0 && $.warn(e);
986
+ }
987
+ _?.cache && !process.env.CACHE_BACKEND && (process.env.CACHE_BACKEND = _.cache), _?.cacheRedisUrl && !process.env.CACHE_REDIS_URL && (process.env.CACHE_REDIS_URL = _.cacheRedisUrl), _?.cacheRedisDriver && !process.env.CACHE_REDIS_DRIVER && (process.env.CACHE_REDIS_DRIVER = _.cacheRedisDriver), _?.cacheKeyPrefix && !process.env.CACHE_KEY_PREFIX && (process.env.CACHE_KEY_PREFIX = _.cacheKeyPrefix);
988
+ let { service: Je, invalidationBus: Ye, snapshotCache: Ze, cache: Qe, backend: et, dispose: F } = await E({ env: process.env });
989
+ $.info(`cache backend resolved: ${et}` + (et === "redis" ? ` (driver ${process.env.CACHE_REDIS_DRIVER ?? "resp"})` : " — in-process, not cross-instance")), k.onChange((e) => {
990
+ M.runFork(Ye.publish(e.table));
991
+ }), _?.kv && !process.env.KV_BACKEND && (process.env.KV_BACKEND = _.kv), _?.kvRedisUrl && !process.env.KV_REDIS_URL && (process.env.KV_REDIS_URL = _.kvRedisUrl), _?.kvKeyPrefix && !process.env.KV_KEY_PREFIX && (process.env.KV_KEY_PREFIX = _.kvKeyPrefix);
992
+ let { kv: tt, service: I } = await mt({ store: k });
993
+ m.mark("store");
994
+ let nt = $e({
995
+ store: k,
996
+ sink: O.sink,
997
+ log: $
998
+ }), rt = Oe({
999
+ store: k,
1000
+ dialect: y
1001
+ }), R = _?.plugins ?? [], ct = process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, lt, gt;
1002
+ y !== "memory" && (lt = Ke.make((await n(y)).makeSqlLayer(D())), gt = await lt.runPromise(Ht.SqlClient));
1003
+ let _t = ht({
1004
+ coordinator: [
1005
+ "postgres",
1006
+ "mariadb",
1007
+ "mysql",
1008
+ "mssql"
1009
+ ].includes(y) ? ut(k, ct, $) : It,
1010
+ replicaId: ct,
1011
+ log: $
1012
+ }), vt = [], yt = process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, bt = xn(_?.plugins ?? [])?.broadcast?.provider, xt = he(_?.plugins, _?.name ?? We(h)), St = Re(_?.plugins, {
1013
+ instanceId: yt,
1014
+ namespace: xt,
1015
+ meta: { mode: "serve" },
1016
+ logger: $
1017
+ }), Ct = {
1018
+ ...gt ? { sql: gt } : {},
1019
+ instanceId: yt,
1020
+ membership: St.membership,
1021
+ ...bt === void 0 ? {} : { broadcast: bt },
1022
+ broadcastChannels: { presence: bn(xt, "presence") },
1023
+ scheduleCoordinated: (e, t, n) => {
1024
+ let r = _t(e, t, n);
1025
+ return vt.push(r), r;
1026
+ }
1027
+ };
1028
+ for (let e of R) e.bindDataStore?.(k, Ct);
1029
+ let Tt = R.filter((e) => typeof e.onChangeEvent == "function");
1030
+ if (Tt.length > 0) {
1031
+ let e = k.changeScope ?? "local";
1032
+ k.onChange((t) => {
1033
+ let n = re(t, e);
1034
+ for (let e of Tt) M.runFork(e.onChangeEvent(n).pipe(M.catchAllCause((t) => M.sync(() => $.warn(`plugin ${e.name} onChangeEvent failed`, { error: Ge.pretty(t) })))));
1035
+ });
1036
+ }
1037
+ let z = te({
1038
+ plugins: R,
1039
+ appName: _?.name ?? "voltro-api",
1040
+ appType: "api",
1041
+ voltroVersion: process.env.npm_package_version ?? "0.0.0",
1042
+ log: $
1043
+ });
1044
+ R.length && await z.activate(), m.mark("plugins");
1045
+ let Et = await z.gatherObservability(), Dt = {
1046
+ info: (e, t) => process.stdout.write(`[broadcast] ${e} ${t ? JSON.stringify(t) : ""}\n`),
1047
+ warn: (e, t) => process.stderr.write(`[broadcast] ${e} ${t ? JSON.stringify(t) : ""}\n`),
1048
+ debug: () => {}
1049
+ }, kt, At = await xe(k, _, y, xt, Dt, (e, t) => {
1050
+ kt?.refreshAll(`broadcast gap: missed ${t} change(s) from ${e}`);
1051
+ }), B = _?.apiKeys, Mt = (typeof B == "object" ? B.prefix : void 0) ?? "voltro_", Pt = B ? at(k) : void 0, Ft = Pt ? ft({ flush: pt(Pt) }) : void 0;
1052
+ Ft && Ot(() => Ft.shutdown());
1053
+ let Lt = Pt ? dt(Pt, {
1054
+ prefix: Mt,
1055
+ ...Ft ? { usage: Ft } : {}
1056
+ }) : void 0, Rt = Lt ? [st(Lt, { prefix: Mt })] : [], zt = Ae([..._?.auth?.strategies ?? [], ...Rt], fn(_?.plugins ?? []), _?.auth?.anonymousTenantRequired ?? !1, _?.auth?.resolveScopes, () => P), Vt = [..._?.restRoutes ?? [], ...Lt ? Xe(Lt, (typeof B == "object" ? B.managementPath : void 0) ?? "/v1/api-keys") : []], V = _?.idempotency, H = V ? {
1057
+ store: ot(k),
1058
+ header: (typeof V == "object" ? V.header : void 0) ?? "Idempotency-Key",
1059
+ ttlMs: (typeof V == "object" ? V.ttlMs : void 0) ?? 864e5
1060
+ } : void 0, Wt = Vt.length > 0 ? mn(Vt, {
1061
+ store: k,
1062
+ resolveSubject: (e) => zt({
1063
+ headers: e,
1064
+ clientId: -1
1065
+ }),
1066
+ ...H ? { idempotency: H } : {}
1067
+ }) : [], Gt = R.map((e) => e.services).filter((e) => e !== void 0), Kt = N.mergeAll(De({
1068
+ analyticsLayer: O.layer,
1069
+ cacheService: Je,
1070
+ kvService: I,
1071
+ pluginServices: Gt,
1072
+ userLayers: _?.layers ?? []
1073
+ }), ve(_?.http ?? {})), qt = _?.scheduling ?? {}, Jt = qt.trigger ?? "self", Yt = /* @__PURE__ */ new Set([
1074
+ "postgres",
1075
+ "mysql",
1076
+ "mariadb",
1077
+ "mssql"
1078
+ ]), U = qt.coordination ?? (Yt.has(y) ? "advisoryLock" : "single"), W = U === "cluster" && Yt.has(y), G = W ? "cluster" : U === "advisoryLock" && Yt.has(y) ? "advisoryLock" : "single";
1079
+ U === "cluster" && !W && $.warn("scheduling.coordination=cluster needs a sql-backed store except sqlite — falling back to single"), U === "advisoryLock" && !Yt.has(y) && $.warn("scheduling.coordination=advisoryLock needs a SQL store (the claim-row gate) — falling back to single");
1080
+ let Xt, Zt = S.workflows.length > 0 || S.workflowWorkers.length > 0 || S.eventTriggers.length > 0 || (je?.outgoing.length ?? 0) > 0 || W, K;
1081
+ if (Zt) {
1082
+ if (y === "mssql") {
1083
+ let e = await ce(process.cwd());
1084
+ e && $.warn(e);
1085
+ }
1086
+ let [{ WorkflowEngine: e }, { makeClusterCronLayer: t, workflowEngineLayer: r, resolveRunnerStorage: i }] = await Promise.all([import("@effect/workflow"), import("@voltro/workflow/cluster")]), a = W ? S.schedules.filter((e) => (e.trigger ?? Jt) === "self").map((e) => t({
1087
+ name: e.name,
1088
+ cron: it(e),
1089
+ execute: async () => {
1090
+ await Xt?.fireFromCluster(e.name);
1091
+ }
1092
+ })) : [];
1093
+ K = y === "memory" ? e.layerMemory : await (async () => {
1094
+ let e = await n(y), t = i({ sqliteFamily: e.id === "sqlite" || e.id === "turso" });
1095
+ 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)" : "") : "")), r({
1096
+ sqlClientLayer: e.makeSqlLayer(D()),
1097
+ runnerStorage: t,
1098
+ dialectId: e.id,
1099
+ ...process.env.VOLTRO_WORKFLOW_RUNNER_PORT ? { runnerListenPort: Number(process.env.VOLTRO_WORKFLOW_RUNNER_PORT) } : {},
1100
+ ...a.length > 0 ? { extraShardingLayers: a } : {}
1101
+ });
1102
+ })();
1103
+ }
1104
+ let q = ne(R, t()), Qt = x.filter((e) => /\.subscribe\.tsx?$/.test(e)), $t = Qt.length > 0 ? await b(Qt, $) : [], J = x.filter((e) => /\.reaction\.tsx?$/.test(e)), en = J.length > 0 ? await pe(J, $) : [], tn = x.filter((e) => u.test(e)), nn = tn.length > 0 ? await ke(tn, $) : [], Y = x.filter((e) => /\.aggregate\.tsx?$/.test(e)), X = Y.length > 0 ? await g(Y, $) : [], Z = ae();
1105
+ if (X.length > 0 && y !== "memory") try {
1106
+ Z = le((await n(y)).makeSqlLayer(D()));
1107
+ } catch (e) {
1108
+ $.warn("aggregate: SQL storage init failed — falling back to in-process", { err: String(e) });
1109
+ }
1110
+ let rn = y === "memory" ? It : ut(k, `aggregate@${process.pid}`, $), an = [], sn = [], cn = x.filter((e) => l.test(e));
1111
+ if (cn.length > 0) {
1112
+ let e = $.child("agent"), t = x.filter((e) => a.test(e));
1113
+ t.length > 0 && await o(t, e);
1114
+ let n = await c(cn, e);
1115
+ for (let e of n.agents) for (let t of p(e)) (t.kind === "action" ? an : sn).push({
1116
+ file: t.file,
1117
+ descriptor: t.descriptor,
1118
+ executor: t.executor
1119
+ });
1120
+ n.agents.length > 0 && e.info("synthesized agent routes", { agents: n.agents.map((e) => e.descriptor.name) });
1121
+ }
1122
+ m.mark("workflow");
1123
+ let pn = await qn({
1124
+ bootTiming: m,
1125
+ broadcastNamespace: xt,
1126
+ membership: {
1127
+ ...St,
1128
+ instanceId: yt
1129
+ },
1130
+ ..._?.plugins === void 0 ? {} : { plugins: _.plugins },
1131
+ ...H ? { idempotency: {
1132
+ store: H.store,
1133
+ ttlMs: H.ttlMs
1134
+ } } : {},
1135
+ discovered: {
1136
+ queries: [...S.queries, ...sn],
1137
+ mutations: S.mutations,
1138
+ actions: [...S.actions, ...an],
1139
+ streams: S.streams,
1140
+ events: S.events,
1141
+ workflows: S.workflows,
1142
+ workflowWorkers: S.workflowWorkers,
1143
+ eventTriggers: S.eventTriggers,
1144
+ schedules: S.schedules,
1145
+ subscribers: $t,
1146
+ outboxHandlers: nn,
1147
+ connections: S.connections,
1148
+ reactions: en,
1149
+ aggregates: X,
1150
+ ...je === void 0 ? {} : { webhooks: je }
1151
+ },
1152
+ log: $,
1153
+ analytics: O.sink,
1154
+ aggregateStorage: Z,
1155
+ aggregateCoordinator: rn,
1156
+ store: k,
1157
+ kv: tt,
1158
+ cache: Qe,
1159
+ snapshotCache: Ze,
1160
+ schemaRegistry: He,
1161
+ tenantScopedTables: S.tenantScopedTables,
1162
+ softDeleteScopedTables: S.softDeleteScopedTables,
1163
+ dataTransferSnapshot: ln(Le),
1164
+ dataTransferDialect: y,
1165
+ tenantIsolation: (process.env.VOLTRO_TENANT_ISOLATION ?? _?.tenancy?.isolation) === "namespace" ? "namespace" : "shared-schema",
1166
+ resolveSubject: (e, t) => zt({
1167
+ headers: e,
1168
+ clientId: t
1169
+ }),
1170
+ httpRoutes: [...R.flatMap((e) => e.httpRoutes ?? []), ...Wt],
1171
+ getStore: () => P,
1172
+ ...Kt ? { baseLayer: Kt } : {},
1173
+ ...K === void 0 ? {} : { workflowEngineLayer: K },
1174
+ scheduleDefaultTrigger: Jt,
1175
+ scheduleCoordination: G,
1176
+ scheduleArmSelf: !W,
1177
+ dormancy: process.env.VOLTRO_DORMANCY === "sleep" || process.env.VOLTRO_DORMANCY === "always-on" ? process.env.VOLTRO_DORMANCY : _?.dormancy ?? "always-on",
1178
+ scheduleReplicaId: process.env.HOSTNAME ?? `pid-${process.pid}`,
1179
+ ...q === void 0 ? {} : { scheduleFireInterceptor: q },
1180
+ onSchedulerReady: (e) => {
1181
+ Xt = e;
1182
+ },
1183
+ inspectRoute: { handle: (e, t, n, r) => d(e, {
1184
+ kind: "api",
1185
+ meta: {
1186
+ name: _?.name ?? "voltro-api",
1187
+ voltroVersion: Me,
1188
+ port: ie,
1189
+ mode: "start",
1190
+ store: y,
1191
+ cdc: se ? "on" : "off"
1192
+ },
1193
+ rpc: ze(S, h),
1194
+ workflows: C(S, h),
1195
+ events: () => pn.eventsSnapshot(),
1196
+ members: () => pn.membersSnapshot(),
1197
+ inspectFireSchedule: async ({ name: e, trigger: t }) => {
1198
+ if (!Xt) throw Error("scheduler not started — this app registers no self-triggered schedules (all schedules are trigger:'external', or there are none).");
1199
+ return { runId: await Xt.fireNow(e, t) ?? null };
1200
+ }
1201
+ }, t, {
1202
+ method: n,
1203
+ ...r === void 0 ? {} : { body: r }
1204
+ }) ?? {
1205
+ status: 404,
1206
+ contentType: "application/json",
1207
+ body: JSON.stringify({ error: "not an inspect route" })
1208
+ } },
1209
+ observability: Et,
1210
+ port: ie,
1211
+ ..._?.transport?.wsPath ? { path: _.transport.wsPath } : {}
1212
+ });
1213
+ return kt = pn.dispatcher, Ne(be([
1214
+ S.queries,
1215
+ S.mutations,
1216
+ S.actions,
1217
+ S.streams
1218
+ ]), (e) => {
1219
+ $.warn(e);
1220
+ }), $.info(`API listening on :${ie}`, {
1221
+ dialect: y,
1222
+ queries: S.queries.length,
1223
+ mutations: S.mutations.length,
1224
+ actions: S.actions.length,
1225
+ streams: S.streams.length,
1226
+ workflows: S.workflows.length,
1227
+ workflowWorkers: S.workflowWorkers.length,
1228
+ schedules: S.schedules.length,
1229
+ scheduleCoordination: G
1230
+ }), m.finish($), Ot(async () => {
1231
+ for (let e of vt) e.stop();
1232
+ nt.detach(), rt.stop(), F(), lt?.dispose();
1233
+ try {
1234
+ await z.deactivate(), await At?.close(), await O.dispose(), await pn.close(), await k.close?.();
1235
+ } catch (e) {
1236
+ console.error("serve: shutdown step failed, exiting anyway:", e);
1237
+ }
1238
+ }), await new Promise(() => {}), 0;
1239
+ };
1240
+ //#endregion
1241
+ export { Xn as n, Wn as r, Zn as t };