@voltro/runtime 0.85.0 → 0.86.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 (160) hide show
  1. package/CHANGELOG.md +666 -0
  2. package/THIRD-PARTY-NOTICES.md +5 -33
  3. package/dist/aggregate.js +42 -0
  4. package/dist/aggregateExtrema.js +80 -0
  5. package/dist/aggregateIvm.js +115 -0
  6. package/dist/analyticsMirror.js +228 -0
  7. package/dist/analyticsSink.js +38 -0
  8. package/dist/apiKeyUsage.js +33 -0
  9. package/dist/apiKeys.js +223 -0
  10. package/dist/apiKeysWiring.js +114 -0
  11. package/dist/approvalBuiltins.js +10 -0
  12. package/dist/approvals.js +269 -0
  13. package/dist/authMiddlewareLayer.js +47 -0
  14. package/dist/bindEvent.js +72 -0
  15. package/dist/bootListener.js +76 -0
  16. package/dist/bootRefusal.js +7 -0
  17. package/dist/bootStoreCodec.js +70 -0
  18. package/dist/businessRules.js +67 -0
  19. package/dist/changeClaimsTable.js +12 -0
  20. package/dist/circuitBreaker.js +72 -0
  21. package/dist/columnOnUpdate.js +23 -0
  22. package/dist/composeAnalytics.js +108 -0
  23. package/dist/computedQuery.js +4 -0
  24. package/dist/connectionBuiltins.js +81 -0
  25. package/dist/connectionCredentials.js +66 -0
  26. package/dist/connectionState.js +34 -0
  27. package/dist/connectionVault.js +410 -0
  28. package/dist/connectionsFacade.js +54 -0
  29. package/dist/coordinatedSchedule.js +139 -0
  30. package/dist/crdtHistory.js +138 -0
  31. package/dist/crdtMerge.js +179 -0
  32. package/dist/crdtVersionsTable.js +25 -0
  33. package/dist/credentialBound.js +12 -0
  34. package/dist/crud.js +72 -0
  35. package/dist/dataStore.js +679 -0
  36. package/dist/dataloader.js +61 -0
  37. package/dist/declaredTablesGuard.js +48 -0
  38. package/dist/defineExecutor.js +4 -0
  39. package/dist/dependencyGraph.js +32 -0
  40. package/dist/devices.js +228 -0
  41. package/dist/devicesWiring.js +168 -0
  42. package/dist/dialectReplicationAdapter.js +29 -0
  43. package/dist/dispatcher.js +447 -0
  44. package/dist/effectStore.js +71 -0
  45. package/dist/eventBus.js +260 -0
  46. package/dist/eventPublish.js +49 -0
  47. package/dist/events.js +193 -0
  48. package/dist/expectation.js +52 -0
  49. package/dist/expectationEvaluator.js +308 -0
  50. package/dist/experiment.js +96 -0
  51. package/dist/experimentEvaluator.js +245 -0
  52. package/dist/externalizedTasks.js +25 -0
  53. package/dist/fieldCipher.js +61 -0
  54. package/dist/fingerprint.js +21 -0
  55. package/dist/finops.js +42 -0
  56. package/dist/finopsAccountant.js +216 -0
  57. package/dist/handlerBody.js +8 -0
  58. package/dist/healthProbes.js +55 -0
  59. package/dist/httpClientSsrf.js +49 -0
  60. package/dist/httpClientTracing.js +11 -0
  61. package/dist/httpCompression.js +76 -0
  62. package/dist/httpKeepAlive.js +12 -0
  63. package/dist/httpRouteMounts.js +47 -0
  64. package/dist/idempotencyStore.js +70 -0
  65. package/dist/idleDetector.js +21 -0
  66. package/dist/index.d.ts +88 -69
  67. package/dist/index.js +144 -15292
  68. package/dist/insertRequiredColumns.js +19 -0
  69. package/dist/inspectWorkflow.js +1 -0
  70. package/dist/instanceMembership.js +98 -0
  71. package/dist/ivm.js +125 -0
  72. package/dist/kvDataStore.js +86 -0
  73. package/dist/kvFacade.js +32 -0
  74. package/dist/matcher.js +304 -0
  75. package/dist/memoryColumnDefaults.js +11 -0
  76. package/dist/memoryQueryJoins.js +114 -0
  77. package/dist/metrics.js +161 -0
  78. package/dist/observability.js +123 -0
  79. package/dist/observedGraph.js +52 -0
  80. package/dist/originGuard.js +116 -0
  81. package/dist/outbox.js +352 -0
  82. package/dist/pluginRefRules.js +65 -0
  83. package/dist/policyGuardResolver.js +55 -0
  84. package/dist/preview.js +62 -0
  85. package/dist/projectedRows.js +12 -0
  86. package/dist/provenance.js +63 -0
  87. package/dist/rangeIndex.js +89 -0
  88. package/dist/rawReadScope.js +17 -0
  89. package/dist/reaction.js +85 -0
  90. package/dist/reactiveConfig.js +11 -0
  91. package/dist/readClassification.js +57 -0
  92. package/dist/readRecorder.js +66 -0
  93. package/dist/rebac.js +104 -0
  94. package/dist/rebacInterceptor.js +81 -0
  95. package/dist/registry.js +29 -0
  96. package/dist/relevantFields.js +65 -0
  97. package/dist/replicaHealth.js +42 -0
  98. package/dist/replicaLocality.js +44 -0
  99. package/dist/replicaObservations.js +121 -0
  100. package/dist/replicaSelection.js +32 -0
  101. package/dist/replicatedDataStore.js +239 -0
  102. package/dist/requestLoader.js +7 -0
  103. package/dist/resumeCensus.js +28 -0
  104. package/dist/revalidation.js +22 -0
  105. package/dist/rowFilter.js +65 -0
  106. package/dist/rowStateBytes.js +45 -0
  107. package/dist/rpcBodyCap.js +63 -0
  108. package/dist/rpcConnections.js +83 -0
  109. package/dist/rpcDefectDiagnostics.js +15 -0
  110. package/dist/rpcServer.js +992 -0
  111. package/dist/runAsSystem.js +23 -0
  112. package/dist/rywPositionStore.js +84 -0
  113. package/dist/schedule.js +23 -0
  114. package/dist/scheduleBackfillRequests.js +151 -0
  115. package/dist/scheduleClaimsTable.js +11 -0
  116. package/dist/scheduleRunsTable.js +37 -0
  117. package/dist/scheduler.js +835 -0
  118. package/dist/schemaRegistry.js +65 -0
  119. package/dist/secretsResolver.js +35 -0
  120. package/dist/securityHeaders.js +33 -0
  121. package/dist/servePipeline.js +305 -0
  122. package/dist/serverOnlyAudit.js +66 -0
  123. package/dist/serverTracer.js +15 -0
  124. package/dist/serviceCredentials.js +40 -0
  125. package/dist/singleNodeOrchestrator.js +91 -0
  126. package/dist/sourceResolution.js +42 -0
  127. package/dist/storeMiddleware.js +880 -0
  128. package/dist/storeQuery.js +204 -0
  129. package/dist/storeRead.js +10 -0
  130. package/dist/subscriber.js +7 -0
  131. package/dist/subscriptionOutbox.js +139 -0
  132. package/dist/subscriptionRegistry.js +82 -0
  133. package/dist/subscriptionResume.js +132 -0
  134. package/dist/subscriptionSocketMetrics.js +65 -0
  135. package/dist/systemSubject.js +5 -0
  136. package/dist/tenantScope.js +23 -0
  137. package/dist/tenantSelection.js +27 -0
  138. package/dist/timeline.js +105 -0
  139. package/dist/traceContext.js +5 -0
  140. package/dist/traceSink.js +63 -0
  141. package/dist/traceSpansTable.js +29 -0
  142. package/dist/traceparent.js +34 -0
  143. package/dist/transactionSubject.js +12 -0
  144. package/dist/trustedProxy.js +155 -0
  145. package/dist/undo.js +129 -0
  146. package/dist/undoBuiltins.js +69 -0
  147. package/dist/undoCapture.js +74 -0
  148. package/dist/undoLogTable.js +16 -0
  149. package/dist/upsertBinding.js +20 -0
  150. package/dist/wakeOrchestrator.js +34 -0
  151. package/dist/wakeRegistry.js +71 -0
  152. package/dist/wakeRouter.js +63 -0
  153. package/dist/wakeSupervisor.js +62 -0
  154. package/dist/wakeupsTable.js +12 -0
  155. package/dist/webSocketGatewayRuntime.js +114 -0
  156. package/dist/webhookVerification.js +18 -0
  157. package/dist/wireColumnStrip.js +84 -0
  158. package/dist/workflowReadBuiltins.js +87 -0
  159. package/dist/workflowRuntime.js +708 -0
  160. package/package.json +7 -7
@@ -0,0 +1,992 @@
1
+ import { crdtFoldCell as e, crdtIncrementalCell as t } from "./crdtMerge.js";
2
+ import { makeDefaultRefilter as n, rowFilterMayNarrow as r } from "./rowFilter.js";
3
+ import { buildSubjectKey as i } from "./rywPositionStore.js";
4
+ import { runWithRoutingContext as a, runWithRoutingContextEffect as o } from "./replicatedDataStore.js";
5
+ import { applyKeepAlive as s, resolveKeepAlive as c } from "./httpKeepAlive.js";
6
+ import { rpcFrameDefects as l } from "./rpcDefectDiagnostics.js";
7
+ import { makeHttpRouteGroupFinder as u, makeUnmatchedGroupFinder as d, planHttpRouteMounts as f } from "./httpRouteMounts.js";
8
+ import { isComputedQuery as p } from "./computedQuery.js";
9
+ import { registerConnectionStream as m } from "./connectionCredentials.js";
10
+ import { getRpcConnection as h, withRpcClientAddress as g, withRpcConnectionIdentity as _ } from "./rpcConnections.js";
11
+ import { makeSubscriptionOutbox as v, pumpOutbox as y, reactiveSocketTunables as b } from "./subscriptionOutbox.js";
12
+ import { adoptDetached as x, canonicalInputKey as S, detachForResume as C, recordForResume as w } from "./subscriptionResume.js";
13
+ import { externalSpanFromTraceparent as ee, newTraceId as T, parseTraceparent as E } from "./traceparent.js";
14
+ import { runWithTraceContext as D } from "./traceContext.js";
15
+ import { runWithObservedProcedure as O } from "./observedGraph.js";
16
+ import { actingUserId as k } from "./storeMiddleware.js";
17
+ import { readCappedBody as A, withBufferedBody as te } from "./rpcBodyCap.js";
18
+ import { maybeCompress as ne, mergeCompressionHeaders as re } from "./httpCompression.js";
19
+ import { runWebSocketGateway as ie } from "./webSocketGatewayRuntime.js";
20
+ import { noteResumeVerdict as ae } from "./resumeCensus.js";
21
+ import { publishServerTracerLayer as oe } from "./serverTracer.js";
22
+ import { boundByCredential as j } from "./credentialBound.js";
23
+ import { classifyRequestOrigin as se, isStateChangingMethod as ce, makeOriginGuardExemption as le, resolveOriginGuardConfig as ue } from "./originGuard.js";
24
+ import { resolveRequestClientAddress as de, resolveRequestIsHttps as fe, resolveTrustedProxies as pe } from "./trustedProxy.js";
25
+ import { resolveSecurityHeaders as me, securityHeadersFor as he } from "./securityHeaders.js";
26
+ import { assertWebhookRoutesDeclareVerification as ge } from "./webhookVerification.js";
27
+ import { Cause as M, Context as _e, Deferred as N, Effect as P, Fiber as ve, Layer as F, Queue as I, Schema as L, Stream as R } from "effect";
28
+ import { extractDbCause as ye, hasEagerLoads as be, runWithWriteAttribution as z } from "@voltro/database";
29
+ import { randomUUID as xe } from "node:crypto";
30
+ import { ConnectionInfo as B, MUTATION_IN_FLIGHT_RETRY_AFTER_MS as Se, MutationConnectionRequired as Ce, MutationInFlight as we, SubjectService as V, Unauthenticated as Te, beginIdempotent as Ee, defineWebSocket as De, failIdempotent as Oe, finishIdempotent as ke, groupShapeDigests as Ae, holdIdempotentClaim as je, recheckGuardsEffect as Me, wsMutationIdempotencyScope as Ne } from "@voltro/protocol";
31
+ import { LoggerLayer as Pe, createLogger as H } from "@voltro/logger";
32
+ import { Server as Fe, createServer as Ie } from "node:http";
33
+ import { HttpRouter as U, HttpServer as Le, HttpServerError as Re, HttpServerRequest as W, HttpServerResponse as G } from "effect/http";
34
+ import { NodeHttpServer as ze, NodeHttpServerRequest as Be, NodeServices as Ve } from "@effect/platform-node";
35
+ import { RpcSerialization as He, RpcServer as K } from "effect/rpc";
36
+ import { dispatchSharedPath as Ue, restCorsHeaders as We, restCorsPreflight as Ge, routeAcceptsPath as Ke } from "@voltro/protocol/rest";
37
+ import { instanceId as qe, replicaId as Je } from "@voltro/protocol/identity";
38
+ //#region src/rpcServer.ts
39
+ var q = (e) => {
40
+ let t = e.indexOf(".");
41
+ if (t <= 0) return;
42
+ let n = e.slice(0, t), r = e.slice(t + 1);
43
+ if (r !== "" && r.includes(".")) {
44
+ if (n === "subscription") return {
45
+ tag: r,
46
+ kind: "query"
47
+ };
48
+ if (n === "query" || n === "mutation" || n === "action" || n === "stream") return {
49
+ tag: r,
50
+ kind: n
51
+ };
52
+ }
53
+ }, J = (e, t) => {
54
+ let n = q(e);
55
+ return n === void 0 ? t() : O(n, t);
56
+ }, Ye = (e, t, n, r) => e === "subject" ? `${t}:s:${n}` : e === "global" ? `${t}:global` : r.tenantId == null ? void 0 : `${t}:t:${r.tenantId}`, Xe = Pe({}), Ze = (e, t) => P.callback((n) => {
57
+ let r = z(t, () => P.runFork(e.pipe(P.provide(Xe))));
58
+ return r.addObserver((e) => {
59
+ n(e);
60
+ }), P.asVoid(ve.interrupt(r));
61
+ }), Y = (e, t, n) => {
62
+ let r = n === void 0 ? void 0 : h(n);
63
+ return {
64
+ subject: e,
65
+ traceId: t?.traceId ?? T(),
66
+ ...t?.spanId === void 0 ? {} : { spanId: t.spanId },
67
+ ...n === void 0 ? {} : { clientId: n },
68
+ ...r === void 0 ? {} : { connection: r },
69
+ ...r?.remoteAddr === void 0 ? {} : { remoteAddr: r.remoteAddr }
70
+ };
71
+ }, Qe = P.currentSpan.pipe(P.catch(() => P.succeed(void 0))), $e = (e) => ({
72
+ traceId: e.traceId,
73
+ ...e.spanId === void 0 ? {} : { spanId: e.spanId }
74
+ }), et = (e, t, n) => {
75
+ e !== void 0 && (e.attribute("rpc.tag", t), e.attribute("subject.type", n.type), n.tenantId !== void 0 && n.tenantId !== null && e.attribute("tenant.id", n.tenantId));
76
+ }, tt = (e) => n(e, (e) => {
77
+ Q.error("row filter failed to load — subscription", {}, e instanceof Error ? e : Error(String(e)));
78
+ }), X = (e) => ({
79
+ single: (t) => P.runPromise(I.offer(e, t)),
80
+ end: () => I.endUnsafe(e)
81
+ }), nt = (n, i, a, o, s, c, l, u, d, f) => R.callback((p) => P.gen(function* () {
82
+ let h = d ?? b(), g = i.crdtColumnsFor(n.table), _ = v({
83
+ maxBufferedBytes: h.maxBufferedBytes,
84
+ overrunAfterMs: h.overrunAfterMs,
85
+ oversizedEventBytes: h.oversizedEventBytes,
86
+ label: s,
87
+ ...g.size > 0 ? { crdt: {
88
+ columns: g,
89
+ merge: e,
90
+ incremental: t
91
+ } } : {}
92
+ });
93
+ yield* P.addFinalizer(() => P.sync(() => _.close()));
94
+ let ee = u !== void 0 && (be(n) || r([n.table])), T = f !== void 0 && !ee, E = T ? S(f.input) : "unused", D = T && E !== "uncanonical" ? {
95
+ label: s,
96
+ inputKey: E,
97
+ subjectId: a.subject.id ?? "anonymous",
98
+ tenantId: a.subject.tenantId ?? ""
99
+ } : void 0;
100
+ ae(s, f === void 0 ? "not-offered" : ee ? r([n.table]) ? "row-filter" : "eager-load" : E !== "uncanonical" || "uncanonical-input");
101
+ let O = { current: (e) => {
102
+ D !== void 0 && w(D, e), _.push(e);
103
+ } };
104
+ if (D !== void 0 && f?.fromRevision !== void 0 && f.reconcile === void 0) {
105
+ let e = l !== void 0 && (yield* P.tryPromise(() => l()).pipe(P.match({
106
+ onFailure: () => !0,
107
+ onSuccess: (e) => !!e
108
+ }))) ? void 0 : x(D, f.fromRevision);
109
+ if (e !== void 0) {
110
+ for (let t of e.deltas) _.push({
111
+ _tag: "delta",
112
+ revision: t.revision,
113
+ emittedAt: t.emittedAt,
114
+ patch: t.patch
115
+ });
116
+ e.sink.current = O.current;
117
+ let t = e.unsubscribe;
118
+ if (yield* P.addFinalizer(() => P.sync(() => {
119
+ e.sink.current = () => {}, C(D, {
120
+ sink: e.sink,
121
+ unsubscribe: t
122
+ });
123
+ })), yield* P.forkScoped(P.promise(() => y(_, X(p), s))), a.clientId !== void 0) {
124
+ let e = m(a.clientId, () => {
125
+ I.endUnsafe(p);
126
+ });
127
+ yield* P.addFinalizer(() => P.sync(() => e()));
128
+ }
129
+ return;
130
+ }
131
+ }
132
+ let k = yield* P.tryPromise(() => i.subscribe(n, (e) => {
133
+ O.current(e);
134
+ }, a, o, s, f?.reconcile === void 0 ? c : void 0, l, u, f?.reconcile !== void 0)).pipe(P.matchCause({
135
+ onFailure: (e) => (pt(`subscription.${s}`, a.traceId, e), {
136
+ ok: !1,
137
+ error: bt(e)
138
+ }),
139
+ onSuccess: (e) => ({
140
+ ok: !0,
141
+ unsubscribe: e
142
+ })
143
+ }));
144
+ if (!k.ok) {
145
+ I.offerUnsafe(p, {
146
+ _tag: "error",
147
+ error: k.error
148
+ }), I.endUnsafe(p);
149
+ return;
150
+ }
151
+ let A = k.unsubscribe;
152
+ if (yield* P.addFinalizer(() => P.sync(() => {
153
+ D === void 0 ? A() : (O.current = () => {}, C(D, {
154
+ sink: O,
155
+ unsubscribe: A
156
+ }));
157
+ })), yield* P.forkScoped(P.promise(() => y(_, X(p), s))), a.clientId !== void 0) {
158
+ let e = m(a.clientId, () => {
159
+ I.endUnsafe(p);
160
+ });
161
+ yield* P.addFinalizer(() => P.sync(() => e()));
162
+ }
163
+ }), { bufferSize: 1 }), rt = /* @__PURE__ */ new Set(), it = () => {
164
+ rt.clear();
165
+ }, at = (e) => {
166
+ rt.has(e) || (rt.add(e), ft.warn(`${e}: \`cache:\` is declared but NOT applied — this query's handler returns a computed value, and the snapshot cache only wraps a store read. Every subscriber re-runs the handler. Either return a query descriptor (so the read can be cached), or drop \`cache:\` so the declaration matches what happens.`, { label: e }));
167
+ }, ot = (e, t, n, r, i) => R.callback((a) => P.gen(function* () {
168
+ let o = i ?? b(), s = v({
169
+ maxBufferedBytes: o.maxBufferedBytes,
170
+ overrunAfterMs: o.overrunAfterMs,
171
+ oversizedEventBytes: o.oversizedEventBytes,
172
+ label: r
173
+ });
174
+ yield* P.addFinalizer(() => P.sync(() => s.close()));
175
+ let c = yield* P.tryPromise(() => t.subscribeComputed(e, (e) => {
176
+ s.push(e._tag === "snapshot" ? {
177
+ ...e,
178
+ computed: !0
179
+ } : e);
180
+ }, n, r)).pipe(P.matchCause({
181
+ onFailure: (e) => (pt(`subscription.${r}`, n.traceId, e), {
182
+ ok: !1,
183
+ error: bt(e)
184
+ }),
185
+ onSuccess: (e) => ({
186
+ ok: !0,
187
+ unsubscribe: e
188
+ })
189
+ }));
190
+ if (!c.ok) {
191
+ I.offerUnsafe(a, {
192
+ _tag: "error",
193
+ error: c.error
194
+ }), I.endUnsafe(a);
195
+ return;
196
+ }
197
+ let l = c.unsubscribe;
198
+ if (ae(r, "computed"), yield* P.addFinalizer(() => P.sync(() => l())), yield* P.forkScoped(P.promise(() => y(s, X(a), r))), n.clientId !== void 0) {
199
+ let e = m(n.clientId, () => {
200
+ I.endUnsafe(a);
201
+ });
202
+ yield* P.addFinalizer(() => P.sync(() => e()));
203
+ }
204
+ }), { bufferSize: 1 }), st = (e, t, n = "rpc.subscription", r, s, c, l) => R.unwrap(P.gen(function* () {
205
+ let u = yield* V, d = yield* B, f = (e) => {
206
+ let t = R.make({
207
+ _tag: "error",
208
+ error: new Te({ reason: "The session has expired. Sign in again." })
209
+ });
210
+ return j(e, d.credentialExpiresAt, t, t);
211
+ }, m = yield* Qe;
212
+ et(m, n, u);
213
+ let h = Y(u, m, d.clientId), g = i(u.id, d.clientId), _ = {
214
+ subjectKey: g,
215
+ ...d.reconcile === void 0 ? {} : { forcePrimary: !0 }
216
+ }, v = a(_, () => D({
217
+ traceId: h.traceId,
218
+ ...h.spanId === void 0 ? {} : { spanId: h.spanId }
219
+ }, () => J(n, () => e(h)))), y = P.isEffect(v) ? yield* o(_, v).pipe(P.matchCause({
220
+ onFailure: (e) => (pt(`subscription.${n}`, h.traceId, e), {
221
+ ok: !1,
222
+ error: bt(e)
223
+ }),
224
+ onSuccess: (e) => ({
225
+ ok: !0,
226
+ value: e
227
+ })
228
+ })) : {
229
+ ok: !0,
230
+ value: v
231
+ };
232
+ if (!y.ok) return R.make({
233
+ _tag: "error",
234
+ error: y.error
235
+ });
236
+ let b = y.value;
237
+ if (p(b)) return s !== void 0 && at(n), f(Z(ot(d.reconcile === void 0 ? b : {
238
+ ...b,
239
+ recompute: () => a(_, b.recompute)
240
+ }, t, h, n), d.reconcile));
241
+ let x = b, S = r?.(x), C = s === void 0 ? void 0 : Ye(s.scope, s.baseKey, g, u);
242
+ return f(Z(nt(x, t, h, S, n, s === void 0 || C === void 0 ? void 0 : {
243
+ key: C,
244
+ ttlMs: s.ttlMs,
245
+ swrMs: s.swrMs
246
+ }, c?.(u), l?.(u) ?? tt(u), void 0, {
247
+ input: x,
248
+ ...d.resumeFrom === void 0 ? {} : { fromRevision: d.resumeFrom },
249
+ ...d.reconcile === void 0 ? {} : { reconcile: d.reconcile }
250
+ }), d.reconcile));
251
+ }).pipe(P.withSpan(n, { attributes: { "framework.kind": "subscription" } }))), Z = (e, t) => t === void 0 ? e : e.pipe(R.mapAccum(() => !1, (e, n) => !e && n._tag === "snapshot" ? [!0, [{
252
+ ...n,
253
+ reconciles: t
254
+ }]] : [e, [n]])), ct = (e, t = "rpc.stream", n, r) => R.unwrap(P.gen(function* () {
255
+ let i = yield* V, a = yield* B, o = yield* Qe;
256
+ et(o, t, i);
257
+ let s = Y(i, o, a.clientId), c = n ?? [], l = () => Me(i, c, r), u = yield* l();
258
+ if (u) return R.fail(u);
259
+ let d = J(t, () => e(s)), f = P.isEffect(d) ? yield* d.pipe(P.orDie) : d, p = R.flatMap(f, (e) => R.unwrap(l().pipe(P.map((t) => t ? R.fail(t) : R.make(e))))), h = j(p, a.credentialExpiresAt, R.empty);
260
+ if (s.clientId === void 0) return h;
261
+ let g = s.clientId;
262
+ return R.unwrap(P.gen(function* () {
263
+ let e = yield* N.make(), t = m(g, () => {
264
+ N.doneUnsafe(e, P.void);
265
+ });
266
+ return yield* P.addFinalizer(() => P.sync(() => t())), h.pipe(R.interruptWhen(N.await(e)));
267
+ }));
268
+ }).pipe(P.withSpan(t, { attributes: { "framework.kind": "stream" } }))), Q = H({ scope: "voltro:rpc" }), lt = H({ scope: "voltro:http" }), ut = H({ scope: "voltro:shutdown" }), dt = (e) => {
269
+ if (e instanceof Error) {
270
+ let t = e._tag;
271
+ return {
272
+ name: e.name,
273
+ message: e.message,
274
+ ...typeof t == "string" ? { tag: t } : {},
275
+ ...e.stack === void 0 ? {} : { stack: e.stack.split("\n").slice(1, 4).map((e) => e.trim()) }
276
+ };
277
+ }
278
+ if (typeof e == "object" && e) {
279
+ let t = e._tag;
280
+ return {
281
+ ...typeof t == "string" ? { tag: t } : {},
282
+ value: String(e).slice(0, 300)
283
+ };
284
+ }
285
+ return { value: String(e).slice(0, 300) };
286
+ }, ft = H({ scope: "voltro:rpc" }), pt = (e, t, n) => {
287
+ if (M.hasInterruptsOnly(n)) return;
288
+ let r = M.squash(n), i = r?._tag, a = r instanceof Error ? r.message : r?.message ?? String(r), o = M.hasDies(n), s = ye(r), c = {
289
+ traceId: t,
290
+ ...i === void 0 ? {} : { errorTag: i },
291
+ ...s
292
+ }, l = a === "Failed to execute statement" && typeof s.dbMessage == "string" ? s.dbMessage : a;
293
+ o ? Q.error(`${e} failed: ${l}`, c) : Q.warn(`${e} failed: ${l}`, c);
294
+ }, mt = /* @__PURE__ */ new Set([
295
+ "SqlError",
296
+ "ResultLengthMismatch",
297
+ "FieldDecryptionError"
298
+ ]), ht = (e) => typeof e == "object" && !!e && typeof e._tag == "string" && mt.has(e._tag), gt = (e, t) => {
299
+ try {
300
+ return L.is(e)(t);
301
+ } catch {
302
+ return !0;
303
+ }
304
+ }, _t = /* @__PURE__ */ new Set(), vt = (e, t) => {
305
+ let n = `${e}\u0000${t}`;
306
+ _t.has(n) || (_t.size >= 1e3 && _t.clear(), _t.add(n), Q.warn(`${e} failed with '${t}', which is undeclared on its wire union — the client received InternalError instead. Add ${t} to the descriptor's \`error:\`, register it app-wide through a plugin's \`errorSchemas\`, or map it to a declared error (\`Effect.orDie\` if it is a defect). \`defineExecutor\` reports this at compile time.`, {
307
+ procedure: e,
308
+ errorTag: t
309
+ }));
310
+ }, $ = (e, t = "internal server error") => ({
311
+ _tag: "InternalError",
312
+ message: t,
313
+ traceId: e
314
+ }), yt = (e) => {
315
+ let t = e instanceof Error ? e.message : e?.message, n = typeof t == "string" && t.length > 0 ? t : String(e), r = e?._tag, i = typeof r == "string" && r.length > 0 && !n.startsWith(r) ? `${r}: ${n}` : n;
316
+ return i.length <= 500 ? i : `${i.slice(0, 500)}…`;
317
+ }, bt = (e) => {
318
+ let t = M.squash(e);
319
+ if (t && typeof t == "object" && t._tag === "UnknownError" && (t = t.error ?? t.cause ?? t), ht(t)) return {
320
+ _tag: "InternalError",
321
+ message: "internal server error"
322
+ };
323
+ let n = t && typeof t == "object" ? t : {}, r = {};
324
+ for (let [e, t] of Object.entries(n)) e !== "cause" && e !== "stack" && e !== "message" && (t === null || typeof t == "string" || typeof t == "number" || typeof t == "boolean") && (r[e] = t);
325
+ let i = t?._tag, a = t instanceof Error ? t.message : t?.message;
326
+ return {
327
+ ...r,
328
+ ...typeof i == "string" ? { _tag: i } : {},
329
+ message: typeof a == "string" ? a : String(t)
330
+ };
331
+ }, xt = (e) => {
332
+ if (e === void 0) return;
333
+ let t = L.encodeUnknownSync(e), n = L.decodeUnknownSync(e);
334
+ return {
335
+ encode: (e) => {
336
+ try {
337
+ return t(e);
338
+ } catch {
339
+ return e;
340
+ }
341
+ },
342
+ decode: (e) => {
343
+ try {
344
+ return n(e);
345
+ } catch {
346
+ return e;
347
+ }
348
+ }
349
+ };
350
+ }, St = (e) => {
351
+ let t = {}, n;
352
+ for (let [r, i] of Object.entries(e ?? {})) Array.isArray(i) ? r.toLowerCase() === "set-cookie" ? n = i : t[r] = i.join(", ") : t[r] = i;
353
+ return {
354
+ headers: t,
355
+ setCookie: n
356
+ };
357
+ }, Ct = (e, t, n = "rpc.mutation", r, o, s, c = "subject") => P.gen(function* () {
358
+ let l = yield* V, u = yield* B, d = yield* Qe;
359
+ et(d, n, l);
360
+ let f = Y(l, d, u.clientId), p = c === "connection";
361
+ if (p && (f.connection?.transport !== "websocket" || f.connection.signal.aborted)) return yield* P.fail(new Ce({ traceId: f.traceId }));
362
+ let m = o && u.idempotencyKey ? {
363
+ store: o.store,
364
+ ttlMs: o.ttlMs,
365
+ key: u.idempotencyKey,
366
+ scope: Ne(l.tenantId, k(l), n, p ? f.connection?.id : void 0)
367
+ } : null, h = i(l.id, u.clientId), g = {
368
+ traceId: f.traceId,
369
+ subjectId: k(l),
370
+ procedure: n
371
+ }, _ = (r = (e) => e) => P.suspend(() => {
372
+ let i = a({ subjectKey: h }, () => D({
373
+ traceId: f.traceId,
374
+ ...f.spanId === void 0 ? {} : { spanId: f.spanId }
375
+ }, () => z(g, () => J(n, () => e(t, f)))));
376
+ return P.isEffect(i) ? r(Ze(i, g)) : P.tryPromise({
377
+ try: () => Promise.resolve(i),
378
+ catch: (e) => e
379
+ });
380
+ }), v = !1, y;
381
+ return yield* (m ? P.acquireUseRelease(P.promise(async () => {
382
+ let e = await Ee(m.store, m.scope, m.key, m.ttlMs, Date.now());
383
+ return e.kind === "fresh" && (y = je(m.store, m.scope, m.key)), e;
384
+ }), (e) => P.gen(function* () {
385
+ return yield* P.yieldNow, p && f.connection?.signal.aborted ? yield* P.fail(new Ce({ traceId: f.traceId })) : e.kind === "replay" ? r ? r.decode(e.response.body) : e.response.body : e.kind === "conflict" ? yield* P.fail(new we({
386
+ traceId: f.traceId,
387
+ retryAfterMs: Se
388
+ })) : yield* P.uninterruptibleMask((e) => e(P.void).pipe(P.flatMap(() => _(e)), P.tap((e) => (v = !0, P.promise(() => ke(m.store, m.scope, m.key, {
389
+ status: 200,
390
+ body: r ? r.encode(e) : e
391
+ }, Date.now())).pipe(P.ignore)))));
392
+ }), (e) => P.sync(() => y?.()).pipe(P.andThen(e.kind === "fresh" && !v ? P.promise(() => Oe(m.store, m.scope, m.key)).pipe(P.ignore) : P.void))) : _()).pipe(P.tapCause((e) => P.sync(() => pt(n, f.traceId, e))), P.catchIf(ht, () => P.die($(f.traceId))), P.catchIf((e) => e instanceof Error && typeof e._tag != "string", (e) => P.die($(f.traceId, yt(e)))), P.catchIf((e) => s !== void 0 && typeof e?._tag == "string" && !gt(s, e), (e) => P.sync(() => vt(n, e._tag)).pipe(P.andThen(P.die($(f.traceId, yt(e)))))), P.catchDefect((e) => e?._tag === "InternalError" ? P.die(e) : P.die($(f.traceId, yt(e)))), P.annotateLogs($e(f)));
393
+ }).pipe(P.withSpan(n, { attributes: { "framework.kind": "mutation" } })), wt = 8388608, Tt = (e) => {
394
+ let t = e.port ?? 4e3, n = e.host, r = e.path ?? "/ws", i = r, a = e.replicaId ?? Je();
395
+ ge(e.webhookRoutes);
396
+ let o = e.listener, p = o?.server ?? Ie(), m = /* @__PURE__ */ new Set();
397
+ p.on("connection", (e) => {
398
+ m.add(e), e.once("close", () => {
399
+ m.delete(e);
400
+ });
401
+ }), s(p, c(e));
402
+ let v = (t) => W.HttpServerRequest.pipe(P.flatMap((t) => P.gen(function* () {
403
+ if (!e.inspectRoute) return G.text("inspect route not configured", { status: 404 });
404
+ let n = {};
405
+ for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
406
+ let r = e.inspectRoute, i = r.binary?.[new URL(t.url, "http://inspect.invalid").pathname], a;
407
+ !i && t.method !== "GET" && t.method !== "HEAD" && t.method !== "OPTIONS" && (a = yield* t.text.pipe(P.orElseSucceed(() => "")));
408
+ let o = yield* P.promise(async (e) => {
409
+ if (!i) return r.handle(t.url, n, t.method, a, e);
410
+ let o = R.toReadableStream(t.stream);
411
+ return i(t.url, n, t.method, o, e);
412
+ });
413
+ if (o === null) return G.text("inspect route not found", { status: 404 });
414
+ if (o.byteStream !== void 0) {
415
+ let e = {
416
+ ...o.headers,
417
+ ...o.byteStream.contentLength === void 0 ? {} : { "content-length": String(o.byteStream.contentLength) },
418
+ ...o.byteStream.contentDisposition === void 0 ? {} : { "content-disposition": o.byteStream.contentDisposition }
419
+ };
420
+ if (t.method === "HEAD") return G.empty({
421
+ status: o.status,
422
+ headers: {
423
+ ...e,
424
+ "content-type": o.contentType
425
+ }
426
+ });
427
+ let n = o.byteStream.stream;
428
+ return G.stream(R.fromReadableStream({
429
+ evaluate: () => typeof n == "function" ? n() : n,
430
+ onError: (e) => e
431
+ }), {
432
+ status: o.status,
433
+ contentType: o.contentType,
434
+ headers: e
435
+ });
436
+ }
437
+ return G.text(o.body, {
438
+ status: o.status,
439
+ contentType: o.contentType,
440
+ headers: o.headers ?? {}
441
+ });
442
+ }))), y = () => W.HttpServerRequest.pipe(P.flatMap((t) => {
443
+ let n = e.inspectStream;
444
+ if (!n) return P.succeed(G.text("inspect stream not configured", { status: 404 }));
445
+ let r = {};
446
+ for (let [e, n] of Object.entries(t.headers)) n !== void 0 && (r[e.toLowerCase()] = Array.isArray(n) ? n.join(", ") : n);
447
+ let i = n.corsHeaders(r.origin);
448
+ if (n.isDisabled()) return P.succeed(G.text(JSON.stringify({ error: "inspect disabled (VOLTRO_INSPECT=off)" }), {
449
+ status: 503,
450
+ contentType: "application/json; charset=utf-8",
451
+ headers: i
452
+ }));
453
+ let a = n.authorize(r);
454
+ return a.ok ? (n.select?.(t.url, r) ?? P.succeed(void 0)).pipe(P.flatMap((e) => {
455
+ if (e?.kind === "stream") return P.succeed(G.stream(e.stream, {
456
+ status: 200,
457
+ headers: {
458
+ ...i,
459
+ "content-type": "text/event-stream; charset=utf-8",
460
+ "cache-control": "no-cache, no-transform",
461
+ "x-accel-buffering": "no"
462
+ }
463
+ }));
464
+ if (e?.kind === "refused") return P.succeed(G.text(JSON.stringify(e.body), {
465
+ status: e.status,
466
+ contentType: "application/json; charset=utf-8",
467
+ headers: i
468
+ }));
469
+ let r = new TextEncoder(), a = n.keepAliveMs ?? 15e3, o = t.url.indexOf("?"), s = o === -1 ? new URLSearchParams() : new URLSearchParams(t.url.slice(o + 1)), c = s.get("live") === "1", l = s.get("channels"), u = l ? new Set(l.split(",").map((e) => e.trim()).filter((e) => e.length > 0)) : void 0, d = (e) => {
470
+ if (!u || e.indexOf("event: ") !== 0) return !0;
471
+ let t = e.indexOf("\n", 7);
472
+ return t < 0 || u.has(e.slice(7, t).trim());
473
+ }, f = R.callback((e) => P.gen(function* () {
474
+ if (I.offerUnsafe(e, r.encode("retry: 5000\n\n")), !c) for (let t of n.replay()) d(t) && I.offerUnsafe(e, r.encode(t));
475
+ let t = n.subscribe((t) => {
476
+ d(t) && I.offerUnsafe(e, r.encode(t));
477
+ }), i = setInterval(() => {
478
+ I.offerUnsafe(e, r.encode(n.keepAlive()));
479
+ }, a);
480
+ yield* P.addFinalizer(() => P.sync(() => {
481
+ clearInterval(i), t();
482
+ }));
483
+ }));
484
+ return P.succeed(G.stream(f, {
485
+ status: 200,
486
+ headers: {
487
+ "content-type": "text/event-stream; charset=utf-8",
488
+ ...n.replicaId ? { "x-voltro-replica-id": n.replicaId } : {},
489
+ "cache-control": "no-cache, no-transform",
490
+ connection: "keep-alive",
491
+ "x-accel-buffering": "no",
492
+ ...i
493
+ }
494
+ }));
495
+ })) : P.succeed(G.text(JSON.stringify({
496
+ error: "unauthorized",
497
+ reason: a.reason
498
+ }), {
499
+ status: 401,
500
+ contentType: "application/json; charset=utf-8",
501
+ headers: i
502
+ }));
503
+ })), b = v(!0), x = v(!1), S = U.add("*", "/_voltro/inspect/*", W.HttpServerRequest.pipe(P.flatMap((e) => e.url.split("?")[0] === "/_voltro/inspect" ? b : x))), C = F.empty;
504
+ e.inspectRoute !== void 0 && (C = e.inspectStream === void 0 ? S : F.mergeAll(U.add("GET", "/_voltro/inspect/stream", y()), S));
505
+ let w = e.publishSurfaceDigest === !0 ? Ae(e.group) : void 0, D = e.serviceSurfaceTags ?? /* @__PURE__ */ new Set(), O = (e) => {
506
+ let t = Object.entries(w), n = 0;
507
+ for (let r of t) (e ? D.has(r[0]) : !D.has(r[0])) && (t[n++] = r);
508
+ return t.length = n, Object.fromEntries(t);
509
+ }, k = w === void 0 ? void 0 : O(!1), ae = w === void 0 || D.size === 0 ? void 0 : O(!0), j = P.succeed(G.text(JSON.stringify({
510
+ protocol: 1,
511
+ mutationReplay: e.mutationReplay === !0,
512
+ ...k === void 0 ? {} : { surface: k },
513
+ ...ae === void 0 ? {} : { serviceSurface: ae }
514
+ }), {
515
+ status: 200,
516
+ contentType: "application/json; charset=utf-8",
517
+ headers: {
518
+ "cache-control": "no-store",
519
+ "access-control-allow-origin": "*"
520
+ }
521
+ })), N = "/_voltro/runtime-capabilities", L = `${i.slice(0, i.lastIndexOf("/"))}/_voltro/runtime-capabilities`, be = L === N ? U.add("GET", N, j) : F.mergeAll(U.add("GET", N, j), U.add("GET", L, j)), z = F.empty;
522
+ if (e.webhookRoutes !== void 0 && e.webhookRoutes.size > 0) {
523
+ let t = (t) => W.HttpServerRequest.pipe(P.flatMap((n) => P.gen(function* () {
524
+ let r = {};
525
+ for (let [e, t] of Object.entries(n.headers)) t !== void 0 && (r[e.toLowerCase()] = Array.isArray(t) ? t.join(", ") : t);
526
+ let i = n.url.split("?")[0], a = t.maxBodyBytes ?? Ze, o = /* @__PURE__ */ new Uint8Array();
527
+ if (n.method !== "GET" && n.method !== "HEAD") {
528
+ let e = Number(r["content-length"]);
529
+ if (Number.isFinite(e) && e > a) return G.text("payload too large", { status: 413 });
530
+ let t = yield* A(n.source, a);
531
+ if (t._tag === "aborted") return G.text("request aborted", { status: 400 });
532
+ if (t._tag === "too-large") return G.text("payload too large", { status: 413 });
533
+ o = new Uint8Array(t.bytes);
534
+ }
535
+ let s = ee(r.traceparent), c = yield* P.promise(() => t.handle({
536
+ method: n.method,
537
+ path: i,
538
+ headers: r,
539
+ rawBody: o
540
+ })).pipe(P.withSpan(`webhook${i}`, {
541
+ attributes: {
542
+ "framework.kind": "webhook",
543
+ "http.route": i
544
+ },
545
+ ...s ? { parent: s } : {}
546
+ })), l = new TextEncoder().encode(c.body), u = ne({
547
+ body: l,
548
+ contentType: c.contentType,
549
+ acceptEncoding: r["accept-encoding"],
550
+ options: e.compression
551
+ });
552
+ return u.compressed ? G.uint8Array(u.bytes, {
553
+ status: c.status,
554
+ contentType: c.contentType,
555
+ headers: u.headers
556
+ }) : G.text(c.body, {
557
+ status: c.status,
558
+ contentType: c.contentType
559
+ });
560
+ }))), n = Array.from(e.webhookRoutes.entries()).map(([e, n]) => U.add("*", e, t(n)));
561
+ z = F.mergeAll(...n);
562
+ }
563
+ let B = pe(e.security?.trustedProxies, process.env, e.security?.clientAddressHeader), Se = F.empty, Ce = () => void 0;
564
+ if (e.httpRoutes !== void 0 && e.httpRoutes.length > 0) {
565
+ let t = (t) => W.HttpServerRequest.pipe(P.flatMap((n) => P.gen(function* () {
566
+ let r = {};
567
+ for (let [e, t] of Object.entries(n.headers)) t !== void 0 && (r[e.toLowerCase()] = Array.isArray(t) ? t.join(", ") : t);
568
+ let i = n.url.indexOf("?"), a = i >= 0 ? n.url.slice(0, i) : n.url, o = i >= 0 ? n.url.slice(i + 1) : "";
569
+ if (!t.some((e) => Ke(e, a))) return G.text("not found", { status: 404 });
570
+ let s = t.reduce((e, t) => Math.max(e, t.maxBodyBytes ?? Ze), 0), c = /* @__PURE__ */ new Uint8Array();
571
+ if (n.method !== "GET" && n.method !== "HEAD") {
572
+ let e = Number(r["content-length"]);
573
+ if (Number.isFinite(e) && e > s) return G.text("payload too large", { status: 413 });
574
+ let t = yield* A(n.source, s);
575
+ if (t._tag === "aborted") return G.text("request aborted", { status: 400 });
576
+ if (t._tag === "too-large") return G.text("payload too large", { status: 413 });
577
+ c = new Uint8Array(t.bytes);
578
+ }
579
+ let l = e.getStore?.(), u;
580
+ try {
581
+ u = n.source?.socket?.remoteAddress;
582
+ } catch {
583
+ u = void 0;
584
+ }
585
+ let d = de({
586
+ socketAddress: u,
587
+ headers: r,
588
+ config: B
589
+ }), f = {
590
+ method: n.method,
591
+ path: a,
592
+ query: o,
593
+ headers: r,
594
+ rawBody: c,
595
+ ...l === void 0 ? {} : { store: l },
596
+ ...d === void 0 ? {} : { remoteAddr: d }
597
+ }, p = Date.now(), m = yield* P.promise(() => Ue(t, f));
598
+ if (e.onHttpRoute !== void 0) try {
599
+ e.onHttpRoute({
600
+ method: n.method,
601
+ path: a,
602
+ status: m.status,
603
+ durationMs: Date.now() - p,
604
+ traceId: E(r.traceparent)?.traceId ?? T()
605
+ });
606
+ } catch {}
607
+ m.status >= 500 && lt.warn(`${n.method} ${a} → ${m.status}`, {
608
+ method: n.method,
609
+ path: a,
610
+ status: m.status,
611
+ ...typeof m.body == "string" && m.body.length > 0 ? { body: m.body.slice(0, 1e3) } : {},
612
+ ...m.cause === void 0 ? {} : { cause: dt(m.cause) }
613
+ });
614
+ let h = St(m.headers), g = h.headers, _ = (e) => (h.setCookie !== void 0 && Be.toServerResponse(n).setHeader("set-cookie", [...h.setCookie]), e), v = {
615
+ status: m.status,
616
+ ...m.contentType ? { contentType: m.contentType } : {},
617
+ headers: g
618
+ };
619
+ if (m.byteStream !== void 0) {
620
+ let e = m.byteStream.stream, t = typeof e == "function" ? e() : e;
621
+ return _(G.stream(R.fromReadableStream({
622
+ evaluate: () => t,
623
+ onError: (e) => e
624
+ }), {
625
+ status: m.status,
626
+ contentType: m.contentType ?? "application/octet-stream",
627
+ headers: {
628
+ ...g,
629
+ ...m.byteStream.contentLength === void 0 ? {} : { "content-length": String(m.byteStream.contentLength) },
630
+ ...m.byteStream.contentDisposition === void 0 ? {} : { "content-disposition": m.byteStream.contentDisposition }
631
+ }
632
+ }));
633
+ }
634
+ if (m.stream !== void 0) {
635
+ let { subscribe: e, keepAliveMs: t } = m.stream, n = new TextEncoder(), r = t ?? 15e3, i = R.callback((t) => P.gen(function* () {
636
+ I.offerUnsafe(t, n.encode("retry: 5000\n\n"));
637
+ let i = e((e) => {
638
+ I.offerUnsafe(t, n.encode(e));
639
+ }), a = r > 0 ? setInterval(() => {
640
+ I.offerUnsafe(t, n.encode(": keep-alive\n\n"));
641
+ }, r) : void 0;
642
+ yield* P.addFinalizer(() => P.sync(() => {
643
+ a !== void 0 && clearInterval(a), i();
644
+ }));
645
+ }));
646
+ return _(G.stream(i, {
647
+ status: m.status,
648
+ headers: {
649
+ ...g,
650
+ "content-type": "text/event-stream; charset=utf-8",
651
+ "cache-control": "no-cache, no-transform",
652
+ connection: "keep-alive",
653
+ "x-accel-buffering": "no"
654
+ }
655
+ }));
656
+ }
657
+ if (n.method === "HEAD") return _(G.empty({
658
+ status: v.status,
659
+ headers: g
660
+ }));
661
+ let y = m.body instanceof Uint8Array ? m.body : new TextEncoder().encode(m.body ?? ""), b = ne({
662
+ body: y,
663
+ contentType: m.contentType,
664
+ acceptEncoding: r["accept-encoding"],
665
+ options: e.compression
666
+ });
667
+ return _(G.uint8Array(b.bytes, {
668
+ ...v,
669
+ headers: re(g, b.headers)
670
+ }));
671
+ })), P.tapCause((e) => M.hasInterruptsOnly(e) ? P.void : P.sync(() => lt.error(`${t.map((e) => e.method).join("|")} ${t[0].path} threw`, { path: t[0].path }, M.squash(e))))), n = f(e.httpRoutes), r = new Map(n.map((e) => [e, t(e.routes)])), i = d(n);
672
+ Ce = (e) => {
673
+ let t = i(e);
674
+ return t === void 0 ? void 0 : { effect: r.get(t) };
675
+ };
676
+ let a = n.flatMap((e) => {
677
+ let t = r.get(e);
678
+ return e.methods.map((n) => U.add(n, `${e.mountPath}/*`, t));
679
+ });
680
+ Se = F.mergeAll(...a);
681
+ }
682
+ let we = K.layerProtocolWebsocket({ path: r }), V = (e) => {
683
+ let t = H({ scope: e }), n = /* @__PURE__ */ new Map();
684
+ return (e) => F.flatMap(e, (e) => {
685
+ let r = _e.get(e, K.Protocol);
686
+ return F.succeedContext(_e.make(K.Protocol, {
687
+ ...r,
688
+ run: (e) => r.run((t, r) => P.suspend(() => {
689
+ if (r._tag === "Request") {
690
+ let e = n.get(t);
691
+ e === void 0 && (n.set(t, e = /* @__PURE__ */ new Map()), h(t)?.signal.addEventListener("abort", () => {
692
+ n.delete(t);
693
+ }, { once: !0 })), e.set(String(r.id), r.tag);
694
+ }
695
+ return e(t, r);
696
+ })),
697
+ end: (e) => (n.delete(e), r.end(e)),
698
+ send: (e, i, a) => P.suspend(() => {
699
+ let o = n.get(e), s = "requestId" in i ? String(i.requestId) : void 0, c = s === void 0 ? o?.size === 1 ? o.values().next().value : void 0 : o?.get(s);
700
+ i._tag === "Exit" && s !== void 0 && o?.delete(s);
701
+ for (let n of l(i)) {
702
+ let r = ye(n), i = typeof r.dbMessage == "string" ? r.dbMessage : void 0;
703
+ t.error(i === void 0 ? "rpc defect sent to client" : `rpc defect sent to client: ${i}`, {
704
+ clientId: e,
705
+ defect: n,
706
+ ...s === void 0 ? {} : { requestId: s },
707
+ ...c === void 0 ? {} : { rpcTag: c },
708
+ ...c === void 0 && o !== void 0 ? { rpcTags: [...new Set(o.values())] } : {},
709
+ ...String(n).includes("Expected JSON value") ? { outputHint: "Schema.Unknown outputs must contain JSON values; declare date conversion in the output schema." } : {},
710
+ ...r,
711
+ ...i === void 0 ? {} : { hint: "the failing statement is in `_voltro_traces` (attributes.db.query.text) for this trace" }
712
+ });
713
+ }
714
+ return r.send(e, i, a);
715
+ })
716
+ }));
717
+ });
718
+ }, Te = { disableFatalDefects: !0 }, Ee = K.layer(e.group, Te), Oe = K.layer(e.group, Te).pipe(F.provide(V("voltro:rpc:http")(_(K.layerProtocolHttp({ path: "/rpc" }), "http"))), F.provide(He.layerJson), F.provide(e.httpHandlersLayer ?? e.handlersLayer)), ke = Ee.pipe(F.provide(V("voltro:rpc")(_(we, "websocket"))), F.provide(He.layerJson), F.provide(e.handlersLayer)), je = new Set((e.webSocketGateways ?? []).map((e) => e.path)), Me;
719
+ if (e.webSocketGateways !== void 0 && e.webSocketGateways.length > 0) {
720
+ let t = H({ scope: "voltro:gateway" }), n = e.webSocketGateways.map(De).map((n) => U.add("GET", n.path, W.HttpServerRequest.pipe(P.flatMap((r) => P.gen(function* () {
721
+ let i = {};
722
+ for (let [e, t] of Object.entries(r.headers)) t !== void 0 && (i[e.toLowerCase()] = Array.isArray(t) ? t.join(", ") : t);
723
+ if (!ot(r.method, i)) return G.text("upgrade required", {
724
+ status: 426,
725
+ headers: { upgrade: "websocket" }
726
+ });
727
+ let a = null, o;
728
+ if (n.auth === "subject") {
729
+ let r = e.resolveGatewaySubject;
730
+ if (r === void 0) return t.error("gateway declares auth: subject but the boot passed no resolveGatewaySubject", { path: n.path }), G.text("gateway auth unavailable", { status: 500 });
731
+ let s = yield* P.promise(() => r(i).catch(() => null));
732
+ if (s === null) return G.text("unauthorized", { status: 401 });
733
+ a = s.subject, o = s.credentialExpiresAt;
734
+ }
735
+ let s = yield* r.upgrade;
736
+ return yield* ie(s, r.source.socket, n, a, i, o, (e) => t.error("gateway handler failed", { path: n.path }, e)), G.empty({ status: 200 });
737
+ })))));
738
+ Me = F.mergeAll(...n);
739
+ }
740
+ let Ne = U.make.pipe(P.provideService(U.RouterConfig, {
741
+ caseSensitive: !0,
742
+ ignoreTrailingSlash: !1,
743
+ ignoreDuplicateSlashes: !1
744
+ })), Pe = F.mergeAll(ke, Oe, be, C, z, Se, ...Me === void 0 ? [] : [Me]), Fe = e.pluginHttpInterceptor, q = Number(process.env.VOLTRO_MAX_RPC_BODY_BYTES), J = e.maxRpcBodyBytes ?? (Number.isFinite(q) && q > 0 ? q : 8388608), Ye = Number(process.env.VOLTRO_MAX_BODY_BYTES), Ze = e.maxBodyBytes ?? (Number.isFinite(Ye) && Ye > 0 ? Ye : 8388608), Y = { "cache-control": "no-store" }, Qe = e.httpRoutes?.some((e) => e.cors !== void 0 || e.credentials !== void 0) ? u(f(e.httpRoutes)) : () => void 0, $e = ue({
745
+ ...e.security?.originGuard === void 0 ? {} : { mode: e.security.originGuard },
746
+ ...e.security?.allowedOrigins === void 0 ? {} : { allowedOrigins: e.security.allowedOrigins }
747
+ }), et = le({
748
+ ...e.webhookRoutes === void 0 ? {} : { webhookPaths: e.webhookRoutes.keys() },
749
+ ...e.httpRoutes === void 0 ? {} : { httpRoutes: e.httpRoutes }
750
+ }), tt = me(e.security?.headers), X = H({ scope: "voltro:security" }), nt = H({ scope: "voltro:rpc" }), rt = (e) => {
751
+ try {
752
+ let t = new URL(e, "http://voltro.invalid").searchParams.get("voltro-socket-id");
753
+ return t !== null && /^[A-Za-z0-9-]{1,80}$/.test(t) ? t : void 0;
754
+ } catch {
755
+ return;
756
+ }
757
+ }, it = (e) => {
758
+ let t = Object.create(e);
759
+ return Object.defineProperty(t, "upgrade", {
760
+ configurable: !0,
761
+ get: () => P.gen(function* () {
762
+ let t = yield* e.upgrade, n = xe(), r = rt(e.url), i = Date.now();
763
+ return nt.info("rpc websocket opened", {
764
+ replicaId: a,
765
+ instanceId: qe(),
766
+ connectionId: n,
767
+ ...r === void 0 ? {} : { clientSocketId: r }
768
+ }), yield* P.addFinalizer(() => P.sync(() => {
769
+ nt.info("rpc websocket closed", {
770
+ replicaId: a,
771
+ instanceId: qe(),
772
+ connectionId: n,
773
+ ...r === void 0 ? {} : { clientSocketId: r },
774
+ durationMs: Date.now() - i
775
+ });
776
+ })), t;
777
+ })
778
+ }), t;
779
+ }, at = (e, t) => {
780
+ let n = e.headers, r = he(tt, {
781
+ contentType: n["content-type"],
782
+ https: t
783
+ }), i = {};
784
+ for (let [e, t] of Object.entries(r)) n[e] === void 0 && (i[e] = t);
785
+ return Object.keys(i).length === 0 ? e : G.setHeaders(e, i);
786
+ }, ot = (e, t) => e.toUpperCase() === "GET" && (t.upgrade ?? "").toLowerCase().includes("websocket"), st = (e) => P.gen(function* () {
787
+ let t = yield* W.HttpServerRequest, n = {};
788
+ for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
789
+ let r = t.url.indexOf("?"), a = r === -1 ? t.url : t.url.slice(0, r), o, s = !1;
790
+ try {
791
+ let e = t.source?.socket;
792
+ o = e?.remoteAddress, s = e?.encrypted === !0;
793
+ } catch {
794
+ o = void 0;
795
+ }
796
+ let c = fe({
797
+ socketEncrypted: s,
798
+ socketAddress: o,
799
+ xForwardedProto: n["x-forwarded-proto"],
800
+ config: B
801
+ }), l = de({
802
+ socketAddress: o,
803
+ headers: n,
804
+ config: B
805
+ }), u = t.method === "OPTIONS" ? n["access-control-request-method"] ?? t.method : t.method, d = (Qe(a)?.routes ?? []).filter((e) => Ke(e, a)), f = d.find((e) => e.method === u || e.method === "*" || u === "HEAD" && e.method === "GET"), p = f ?? d[0], m = We(p?.cors, n.origin), h = (e) => {
806
+ let t = e.headers.vary, n = p?.cors !== void 0 && t !== void 0 ? {
807
+ ...m,
808
+ vary: [...new Set(`${t}, Origin`.split(",").map((e) => e.trim()))].join(", ")
809
+ } : m;
810
+ return at(G.setHeaders(e, n), c);
811
+ };
812
+ if (t.method === "OPTIONS" && f?.cors !== void 0 && n["access-control-request-method"] !== void 0) {
813
+ let e = Ge(f.cors, f.method, n);
814
+ return h(G.empty({
815
+ status: e.status,
816
+ headers: e.headers
817
+ }));
818
+ }
819
+ if (t.method === "POST" && a === "/rpc") {
820
+ let e = n["content-length"];
821
+ if (e !== void 0 && Number(e) > J) return h(G.text("rpc payload too large", {
822
+ status: 413,
823
+ headers: Y
824
+ }));
825
+ }
826
+ let _ = a === "/rpc" && ce(t.method), v = (a === i || je.has(a)) && ot(t.method, n);
827
+ if (ce(t.method) && !et(a) && f?.credentials !== "bearer" || v) {
828
+ let e = se({
829
+ headers: n,
830
+ config: $e
831
+ });
832
+ if (!e.allowed) return X.warn("refused cross-site request", {
833
+ path: a,
834
+ method: t.method,
835
+ reason: e.reason,
836
+ origin: e.origin,
837
+ surface: v ? "websocket-upgrade" : _ ? "rpc" : "http-route"
838
+ }), h(G.text("origin not allowed", {
839
+ status: 403,
840
+ headers: Y
841
+ }));
842
+ }
843
+ let y = _ ? P.gen(function* () {
844
+ let r = yield* A(t.source, J);
845
+ return r._tag === "aborted" ? h(G.text("rpc request body incomplete", {
846
+ status: 400,
847
+ headers: Y
848
+ })) : r._tag === "too-large" ? (X.warn("refused an over-cap rpc body", {
849
+ path: a,
850
+ cap: J,
851
+ receivedAtLeast: r.received,
852
+ declaredLength: n["content-length"] ?? null
853
+ }), h(G.text("rpc payload too large", {
854
+ status: 413,
855
+ headers: Y
856
+ }))) : yield* P.provideService(e, W.HttpServerRequest, te(g(t, l), r.bytes));
857
+ }) : e, b = v && a === i ? it(g(t, l)) : t, x = b === t ? y : P.provideService(y, W.HttpServerRequest, b);
858
+ if (!Fe) {
859
+ let e = yield* x;
860
+ return G.isHttpServerResponse(e) ? h(e) : e;
861
+ }
862
+ let S = yield* P.tryPromise(() => Fe(async () => null, {
863
+ method: t.method,
864
+ path: a,
865
+ headers: n,
866
+ remoteAddr: l
867
+ })).pipe(P.catch((e) => P.sync(() => (lt.error("http interceptor threw — request REFUSED (fail-closed)", {
868
+ method: t.method,
869
+ path: a
870
+ }, e), {
871
+ status: 500,
872
+ body: "internal error",
873
+ headers: void 0
874
+ }))));
875
+ if (S !== null) return h(G.text(S.body ?? "", {
876
+ status: S.status,
877
+ ...S.headers ? { headers: S.headers } : {}
878
+ }));
879
+ let C = yield* x;
880
+ return G.isHttpServerResponse(C) ? h(C) : C;
881
+ }), Z = o === void 0 ? void 0 : new Et(p);
882
+ if (o !== void 0 && Z !== void 0) {
883
+ let e = new Promise((e) => {
884
+ let t = (n) => {
885
+ n === "request" && (Z.removeListener("newListener", t), e());
886
+ };
887
+ Z.on("newListener", t);
888
+ });
889
+ Dt.set(p, e), e.then(() => {
890
+ o.delegate({
891
+ request: (e, t) => {
892
+ Z.emit("request", e, t);
893
+ },
894
+ upgrade: (e, t, n) => {
895
+ Z.emit("upgrade", e, t, n);
896
+ }
897
+ });
898
+ });
899
+ }
900
+ let ct = F.unwrap(P.gen(function* () {
901
+ let e = yield* Ne;
902
+ return yield* F.build(F.provide(Pe, F.succeed(U.HttpRouter, e))), e.asHttpEffect();
903
+ }).pipe(P.map((e) => Le.serve(st(e.pipe(P.catchIf((e) => Re.isHttpServerError(e) && e.reason._tag === "RouteNotFound", (e) => {
904
+ let t = Ce(e.request.url.split("?")[0]);
905
+ return t === void 0 ? P.fail(e) : t.effect;
906
+ }))))))).pipe(F.provide(ze.layer(() => Z ?? p, n === void 0 ? { port: t } : {
907
+ port: t,
908
+ host: n
909
+ })), F.provide(Ve.layer), F.provide(Xe));
910
+ e.tracerLayer && (ct = ct.pipe(F.provide(oe), F.provide(e.tracerLayer)));
911
+ let Q = H({ scope: "voltro:rpc" }), ut = F.launch(ct).pipe(P.catchCause((e) => P.sync(() => {
912
+ Q.error("rpc server crashed", {}, M.squash(e)), process.exit(1);
913
+ }))), ft = P.runFork(ut);
914
+ return Ot.add(ft), Lt(), {
915
+ server: p,
916
+ shutdown: async () => {
917
+ Ot.delete(ft);
918
+ let e = P.runPromise(ve.interrupt(ft)).then(() => void 0, () => void 0);
919
+ for (let e of m) e.destroy();
920
+ p.closeIdleConnections(), await e, o !== void 0 && await o.close();
921
+ }
922
+ };
923
+ }, Et = class extends Fe {
924
+ bound;
925
+ constructor(e) {
926
+ super(), this.bound = e;
927
+ }
928
+ listen(...e) {
929
+ let t = e.find((e) => typeof e == "function");
930
+ return t !== void 0 && process.nextTick(t), this;
931
+ }
932
+ address() {
933
+ return this.bound.address();
934
+ }
935
+ }, Dt = /* @__PURE__ */ new WeakMap(), Ot = /* @__PURE__ */ new Set(), kt = /* @__PURE__ */ new Set(), At = !1, jt = (e) => (kt.add(e), () => {
936
+ kt.delete(e);
937
+ }), Mt = 1e4, Nt = 1e3, Pt = 3e5, Ft = () => {
938
+ let e = process.env.VOLTRO_SHUTDOWN_GRACE_MS;
939
+ if (e === void 0 || e === "") return Mt;
940
+ let t = Number(e);
941
+ return !Number.isFinite(t) || t <= 0 ? Mt : Math.min(Pt, Math.max(Nt, Math.trunc(t)));
942
+ }, It = (e) => {
943
+ let t = Date.now(), n = !1, r = (r) => () => {
944
+ n || (n = !0, clearTimeout(i), e.onOutcome?.({
945
+ reason: r,
946
+ ms: Date.now() - t
947
+ }), e.exit());
948
+ }, i = setTimeout(r("deadline"), e.deadlineMs);
949
+ i.unref?.(), Promise.all(e.hooks.map((e) => Promise.resolve().then(e).then(() => void 0, () => void 0))).then(() => Promise.all(e.fibers.map((e) => P.runPromise(ve.interrupt(e)).then(() => void 0, () => void 0)))).then(r("drained"), r("drained"));
950
+ }, Lt = () => {
951
+ if (At) return;
952
+ At = !0;
953
+ let e = () => {
954
+ let e = [...Ot], t = [...kt];
955
+ Ot.clear(), kt.clear(), It({
956
+ fibers: e,
957
+ hooks: t,
958
+ deadlineMs: Ft(),
959
+ exit: () => process.exit(0),
960
+ onOutcome: ({ reason: e, ms: t }) => {
961
+ e === "drained" ? ut.info(`drained in ${t}ms`) : ut.error(`drain deadline exceeded — cut at ${t}ms`, { hint: "a shutdown hook or a pool drain did not complete; whatever had not finished did not happen" });
962
+ }
963
+ });
964
+ };
965
+ process.once("SIGINT", e), process.once("SIGTERM", e);
966
+ }, Rt = (e, t = 1e4) => new Promise((n, r) => {
967
+ if (e.listening) {
968
+ let i = Dt.get(e);
969
+ if (i === void 0) {
970
+ n();
971
+ return;
972
+ }
973
+ let a = setTimeout(() => r(/* @__PURE__ */ Error(`rpc server did not bind within ${t}ms`)), t);
974
+ i.then(() => {
975
+ clearTimeout(a), n();
976
+ });
977
+ return;
978
+ }
979
+ let i = !1, a;
980
+ function o(t) {
981
+ i || (i = !0, clearTimeout(a), e.removeListener("listening", s), e.removeListener("error", c), t ? r(t) : n());
982
+ }
983
+ function s() {
984
+ o();
985
+ }
986
+ function c(e) {
987
+ o(e);
988
+ }
989
+ a = setTimeout(() => o(/* @__PURE__ */ Error(`rpc server did not bind within ${t}ms`)), t), e.on("listening", s), e.on("error", c);
990
+ });
991
+ //#endregion
992
+ export { wt as DEFAULT_MAX_RPC_BODY_BYTES, Rt as awaitServerListening, ot as bindComputedUntyped, Ct as bindMutation, ct as bindStream, st as bindSubscription, nt as bindSubscriptionUntyped, yt as defectMessage, It as drainForShutdown, ht as isInfraError, xt as makeMutationOutputCodec, jt as onProcessShutdown, it as resetComputedQueryCacheWarnings, Ft as shutdownGraceMsFromEnv, Tt as startRpcServer };