@lostgradient/backchannel 0.0.0-stage → 0.1.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/access-policy-metadata.d.ts +92 -0
  4. package/dist/access-policy-metadata.js +87 -0
  5. package/dist/asyncapi-channels.d.ts +46 -0
  6. package/dist/asyncapi-channels.js +399 -0
  7. package/dist/asyncapi.d.ts +40 -0
  8. package/dist/asyncapi.js +165 -0
  9. package/dist/authentication/api-key.d.ts +4 -0
  10. package/dist/authentication/api-key.js +114 -0
  11. package/dist/authentication/audit.d.ts +115 -0
  12. package/dist/authentication/audit.js +75 -0
  13. package/dist/authentication/credential-verifiers.d.ts +60 -0
  14. package/dist/authentication/credential-verifiers.js +102 -0
  15. package/dist/authentication/crypto.d.ts +7 -0
  16. package/dist/authentication/crypto.js +140 -0
  17. package/dist/authentication/index.d.ts +80 -0
  18. package/dist/authentication/index.js +212 -0
  19. package/dist/authentication/rate-limiter.d.ts +133 -0
  20. package/dist/authentication/rate-limiter.js +124 -0
  21. package/dist/authentication/redaction.d.ts +72 -0
  22. package/dist/authentication/redaction.js +118 -0
  23. package/dist/authentication/rotating-api-key-store.d.ts +127 -0
  24. package/dist/authentication/rotating-api-key-store.js +126 -0
  25. package/dist/authentication/types.d.ts +337 -0
  26. package/dist/authentication/types.js +26 -0
  27. package/dist/authentication.d.ts +1 -0
  28. package/dist/authentication.js +1 -0
  29. package/dist/authorization-scope.d.ts +109 -0
  30. package/dist/authorization-scope.js +144 -0
  31. package/dist/authorization.d.ts +55 -0
  32. package/dist/authorization.js +134 -0
  33. package/dist/bind-feed-lifetime.d.ts +45 -0
  34. package/dist/bind-feed-lifetime.js +55 -0
  35. package/dist/byte-arrays.d.ts +5 -0
  36. package/dist/byte-arrays.js +9 -0
  37. package/dist/client/catalog-client.d.ts +285 -0
  38. package/dist/client/catalog-client.js +74 -0
  39. package/dist/client/in-process-transport.d.ts +19 -0
  40. package/dist/client/in-process-transport.js +136 -0
  41. package/dist/client/index.d.ts +14 -0
  42. package/dist/client/index.js +14 -0
  43. package/dist/client/json-rpc-http-transport.d.ts +118 -0
  44. package/dist/client/json-rpc-http-transport.js +127 -0
  45. package/dist/client/server-sent-event-parser.d.ts +55 -0
  46. package/dist/client/server-sent-event-parser.js +78 -0
  47. package/dist/client/sse-subscription-transport.d.ts +72 -0
  48. package/dist/client/sse-subscription-transport.js +224 -0
  49. package/dist/client/subscription-client.d.ts +122 -0
  50. package/dist/client/subscription-client.js +28 -0
  51. package/dist/connection-lease.d.ts +10 -0
  52. package/dist/connection-lease.js +8 -0
  53. package/dist/discovery-filter.d.ts +13 -0
  54. package/dist/discovery-filter.js +16 -0
  55. package/dist/discovery-info.d.ts +94 -0
  56. package/dist/discovery-info.js +38 -0
  57. package/dist/event-selector.d.ts +7 -0
  58. package/dist/event-selector.js +7 -0
  59. package/dist/fault-code.d.ts +84 -0
  60. package/dist/fault-code.js +114 -0
  61. package/dist/fault-remediation.d.ts +30 -0
  62. package/dist/fault-remediation.js +52 -0
  63. package/dist/fault-to-http.d.ts +11 -0
  64. package/dist/fault-to-http.js +13 -0
  65. package/dist/fault-to-json-rpc.d.ts +53 -0
  66. package/dist/fault-to-json-rpc.js +143 -0
  67. package/dist/fault-wire-safety.d.ts +45 -0
  68. package/dist/fault-wire-safety.js +72 -0
  69. package/dist/generator.d.ts +9 -0
  70. package/dist/generator.js +9 -0
  71. package/dist/handler/auth-context-principal.d.ts +37 -0
  72. package/dist/handler/auth-context-principal.js +67 -0
  73. package/dist/handler/authentication-responses.d.ts +23 -0
  74. package/dist/handler/authentication-responses.js +34 -0
  75. package/dist/handler/json-responses.d.ts +15 -0
  76. package/dist/handler/json-responses.js +32 -0
  77. package/dist/handler/operation-handler-authentication.d.ts +64 -0
  78. package/dist/handler/operation-handler-authentication.js +58 -0
  79. package/dist/handler/operation-handler-discovery.d.ts +29 -0
  80. package/dist/handler/operation-handler-discovery.js +55 -0
  81. package/dist/handler/operation-handler-mounts.d.ts +100 -0
  82. package/dist/handler/operation-handler-mounts.js +134 -0
  83. package/dist/handler/operation-handler-subscription.d.ts +34 -0
  84. package/dist/handler/operation-handler-subscription.js +112 -0
  85. package/dist/handler/operation-handler.d.ts +162 -0
  86. package/dist/handler/operation-handler.js +236 -0
  87. package/dist/handler/workspace-release.d.ts +6 -0
  88. package/dist/handler/workspace-release.js +75 -0
  89. package/dist/in-memory-replay-live-backend.d.ts +47 -0
  90. package/dist/in-memory-replay-live-backend.js +129 -0
  91. package/dist/index.d.ts +37 -0
  92. package/dist/index.js +30 -0
  93. package/dist/internal/cryptography/encryption.d.ts +108 -0
  94. package/dist/internal/cryptography/encryption.js +241 -0
  95. package/dist/internal/cryptography/hash.d.ts +72 -0
  96. package/dist/internal/cryptography/hash.js +233 -0
  97. package/dist/internal/cryptography/index.d.ts +4 -0
  98. package/dist/internal/cryptography/index.js +2 -0
  99. package/dist/internals.d.ts +58 -0
  100. package/dist/internals.js +54 -0
  101. package/dist/json-rpc-dispatch.d.ts +88 -0
  102. package/dist/json-rpc-dispatch.js +154 -0
  103. package/dist/json-rpc-framing.d.ts +42 -0
  104. package/dist/json-rpc-framing.js +50 -0
  105. package/dist/json-rpc-http.d.ts +36 -0
  106. package/dist/json-rpc-http.js +191 -0
  107. package/dist/json-rpc-parse.d.ts +69 -0
  108. package/dist/json-rpc-parse.js +206 -0
  109. package/dist/json-rpc-protocol.d.ts +76 -0
  110. package/dist/json-rpc-protocol.js +54 -0
  111. package/dist/json-rpc-session-runtime.d.ts +55 -0
  112. package/dist/json-rpc-session-runtime.js +111 -0
  113. package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
  114. package/dist/json-rpc-websocket-subscription-pump.js +46 -0
  115. package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
  116. package/dist/json-rpc-websocket-subscriptions.js +33 -0
  117. package/dist/json-rpc-websocket-types.d.ts +34 -0
  118. package/dist/json-rpc-websocket-types.js +1 -0
  119. package/dist/json-rpc-websocket-validation.d.ts +45 -0
  120. package/dist/json-rpc-websocket-validation.js +154 -0
  121. package/dist/json-rpc-websocket.d.ts +20 -0
  122. package/dist/json-rpc-websocket.js +363 -0
  123. package/dist/json-schema-utilities.d.ts +5 -0
  124. package/dist/json-schema-utilities.js +17 -0
  125. package/dist/mcp-discovery-names.d.ts +11 -0
  126. package/dist/mcp-discovery-names.js +11 -0
  127. package/dist/openapi-canonical-json.d.ts +10 -0
  128. package/dist/openapi-canonical-json.js +23 -0
  129. package/dist/openapi-error-responses.d.ts +15 -0
  130. package/dist/openapi-error-responses.js +104 -0
  131. package/dist/openapi-schemas.d.ts +17 -0
  132. package/dist/openapi-schemas.js +94 -0
  133. package/dist/openapi.d.ts +60 -0
  134. package/dist/openapi.js +351 -0
  135. package/dist/openrpc-document-schema.d.ts +255 -0
  136. package/dist/openrpc-document-schema.js +84 -0
  137. package/dist/openrpc-errors.d.ts +93 -0
  138. package/dist/openrpc-errors.js +134 -0
  139. package/dist/openrpc.d.ts +66 -0
  140. package/dist/openrpc.js +260 -0
  141. package/dist/operation-catalog/behavior-types.d.ts +34 -0
  142. package/dist/operation-catalog/behavior-types.js +1 -0
  143. package/dist/operation-catalog/behavior-validation.d.ts +3 -0
  144. package/dist/operation-catalog/behavior-validation.js +298 -0
  145. package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
  146. package/dist/operation-catalog/dispatch-allowlist.js +7 -0
  147. package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
  148. package/dist/operation-catalog/dispatch-preparation.js +49 -0
  149. package/dist/operation-catalog/index.d.ts +19 -0
  150. package/dist/operation-catalog/index.js +17 -0
  151. package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
  152. package/dist/operation-catalog/operation-dispatch.js +115 -0
  153. package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
  154. package/dist/operation-catalog/operation-interceptors.js +1 -0
  155. package/dist/operation-catalog/operation-metadata.d.ts +5 -0
  156. package/dist/operation-catalog/operation-metadata.js +104 -0
  157. package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
  158. package/dist/operation-catalog/pipeline-helpers.js +242 -0
  159. package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
  160. package/dist/operation-catalog/pipeline-stages.js +226 -0
  161. package/dist/operation-catalog/pipeline.d.ts +7 -0
  162. package/dist/operation-catalog/pipeline.js +33 -0
  163. package/dist/operation-catalog/registry.d.ts +17 -0
  164. package/dist/operation-catalog/registry.js +132 -0
  165. package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
  166. package/dist/operation-catalog/stream-pipeline.js +129 -0
  167. package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
  168. package/dist/operation-catalog/subscription-lifecycle.js +27 -0
  169. package/dist/operation-catalog/types.d.ts +392 -0
  170. package/dist/operation-catalog/types.js +40 -0
  171. package/dist/operation-catalog/universal-faults.d.ts +11 -0
  172. package/dist/operation-catalog/universal-faults.js +15 -0
  173. package/dist/operation-catalog-snapshot.d.ts +215 -0
  174. package/dist/operation-catalog-snapshot.js +128 -0
  175. package/dist/operation-catalog.d.ts +1 -0
  176. package/dist/operation-catalog.js +1 -0
  177. package/dist/operation-description-audit.d.ts +44 -0
  178. package/dist/operation-description-audit.js +90 -0
  179. package/dist/operation-fault-helpers.d.ts +21 -0
  180. package/dist/operation-fault-helpers.js +32 -0
  181. package/dist/operation-fault.d.ts +245 -0
  182. package/dist/operation-fault.js +235 -0
  183. package/dist/operation-registry.d.ts +46 -0
  184. package/dist/operation-registry.js +46 -0
  185. package/dist/operations/closable-iterable.d.ts +23 -0
  186. package/dist/operations/closable-iterable.js +51 -0
  187. package/dist/operations/get-principal.d.ts +106 -0
  188. package/dist/operations/get-principal.js +107 -0
  189. package/dist/operations/sse-stream.d.ts +67 -0
  190. package/dist/operations/sse-stream.js +264 -0
  191. package/dist/principal.d.ts +253 -0
  192. package/dist/principal.js +254 -0
  193. package/dist/replay-live-feed-internals.d.ts +47 -0
  194. package/dist/replay-live-feed-internals.js +215 -0
  195. package/dist/replay-live-feed-types.d.ts +66 -0
  196. package/dist/replay-live-feed-types.js +7 -0
  197. package/dist/replay-live-feed.d.ts +49 -0
  198. package/dist/replay-live-feed.js +126 -0
  199. package/dist/rest-binding.d.ts +215 -0
  200. package/dist/rest-binding.js +95 -0
  201. package/dist/rest-body.d.ts +17 -0
  202. package/dist/rest-body.js +95 -0
  203. package/dist/route-model.d.ts +305 -0
  204. package/dist/route-model.js +320 -0
  205. package/dist/runtime/cors.d.ts +161 -0
  206. package/dist/runtime/cors.js +265 -0
  207. package/dist/scripts/generate-operation-client.d.ts +186 -0
  208. package/dist/scripts/generate-operation-client.js +561 -0
  209. package/dist/scripts/operation-behaviors.d.ts +3 -0
  210. package/dist/scripts/operation-behaviors.js +16 -0
  211. package/dist/scripts/operation-client-aliases.d.ts +32 -0
  212. package/dist/scripts/operation-client-aliases.js +255 -0
  213. package/dist/scripts/operation-client-domains.d.ts +21 -0
  214. package/dist/scripts/operation-client-domains.js +74 -0
  215. package/dist/scripts/operation-client-schema.d.ts +46 -0
  216. package/dist/scripts/operation-client-schema.js +310 -0
  217. package/dist/scripts/operation-client-svelte.d.ts +3 -0
  218. package/dist/scripts/operation-client-svelte.js +61 -0
  219. package/dist/sequence-cursor.d.ts +46 -0
  220. package/dist/sequence-cursor.js +62 -0
  221. package/dist/sse-error-payload-schema.d.ts +12 -0
  222. package/dist/sse-error-payload-schema.js +33 -0
  223. package/dist/stdio-session.d.ts +71 -0
  224. package/dist/stdio-session.js +347 -0
  225. package/dist/zod-json-schema.d.ts +22 -0
  226. package/dist/zod-json-schema.js +49 -0
  227. package/package.json +38 -3
@@ -0,0 +1,112 @@
1
+ import { faultToHttpResponse } from "../fault-to-http.js";
2
+ import { executeSubscription, } from "../operation-catalog.js";
3
+ import { createEventEnvelopeSSEStream, requireServerSentEventsAccept, shapeServerSentEventsFault, SSE_RESPONSE_HEADERS, } from "../operations/sse-stream.js";
4
+ /** How long one response may stream before the handler ends it: fifteen minutes. */
5
+ export const DEFAULT_MAX_STREAM_DURATION_MS = 900_000;
6
+ /**
7
+ * Map a query string onto a subscription's input. Every value is a string; a
8
+ * key that repeats becomes an array of its values in order. Nothing is coerced
9
+ * to a number or a boolean: a schema that wants one declares `z.coerce`.
10
+ *
11
+ * The record has no prototype, so a `__proto__` key is an ordinary own key
12
+ * that the operation's unknown-key policy then rejects or strips, rather than
13
+ * a write to the prototype.
14
+ */
15
+ export function subscriptionInputFromQuery(searchParams) {
16
+ const input = Object.create(null);
17
+ for (const key of new Set(searchParams.keys())) {
18
+ const values = searchParams.getAll(key);
19
+ input[key] = values.length === 1 ? (values[0] ?? '') : values;
20
+ }
21
+ return input;
22
+ }
23
+ /** A carriage return or line feed in a field would end it and start a forged one. */
24
+ const LINE_BREAK = /[\r\n]/;
25
+ function isSseEnvelope(value) {
26
+ if (value === null || typeof value !== 'object')
27
+ return false;
28
+ return ('kind' in value &&
29
+ typeof value.kind === 'string' &&
30
+ !LINE_BREAK.test(value.kind) &&
31
+ 'cursor' in value &&
32
+ typeof value.cursor === 'string' &&
33
+ !LINE_BREAK.test(value.cursor) &&
34
+ 'emittedAtMs' in value &&
35
+ typeof value.emittedAtMs === 'number');
36
+ }
37
+ /**
38
+ * A subscription's elements reach the wire as SSE frames keyed by `cursor`, so
39
+ * every element must carry one, and `cursor` and `kind` become the `id:` and
40
+ * `event:` lines, so neither may contain a line break (an operation echoing
41
+ * caller-controlled text there could forge a frame). Anything else is the
42
+ * operation's defect, not the caller's, and ends the stream with a sanitized
43
+ * error frame.
44
+ */
45
+ async function* asEnvelopes(iterable) {
46
+ for await (const element of iterable) {
47
+ if (!isSseEnvelope(element)) {
48
+ throw { code: 'EngineFailure', message: 'internal error', data: {} };
49
+ }
50
+ yield element;
51
+ }
52
+ }
53
+ function acceptFailure(request) {
54
+ try {
55
+ requireServerSentEventsAccept(request);
56
+ return null;
57
+ }
58
+ catch (error) {
59
+ // `requireServerSentEventsAccept` throws the fault it wants shaped.
60
+ return shapeServerSentEventsFault(error);
61
+ }
62
+ }
63
+ function streamResponse(invocation, request, context) {
64
+ const stream = createEventEnvelopeSSEStream({
65
+ iterable: asEnvelopes(invocation.iterable),
66
+ close: invocation.close,
67
+ signal: request.signal,
68
+ maxDurationMs: context.maxStreamDurationMs,
69
+ ...(invocation.replayComplete === undefined ? {} : { ready: invocation.replayComplete }),
70
+ ...(context.heartbeat === undefined ? {} : { heartbeat: context.heartbeat }),
71
+ });
72
+ return new Response(stream, { status: 200, headers: SSE_RESPONSE_HEADERS });
73
+ }
74
+ /**
75
+ * Serve `GET /v1/subscriptions/:operationName`: the catalog subscription
76
+ * `operationName` as Server-Sent Events, resumable with `Last-Event-ID`.
77
+ *
78
+ * A fetch handler cannot accept a WebSocket, so this is how a subscription
79
+ * reaches a plain HTTP client. The operation runs through the same pipeline as
80
+ * every other transport (`executeSubscription`), so access policy, `authorize`,
81
+ * and input parsing are not reimplemented here.
82
+ */
83
+ export async function handleSubscriptionRequest(request, operationName, context) {
84
+ if (request.method !== 'GET') {
85
+ return new Response('Method Not Allowed', { status: 405, headers: { allow: 'GET' } });
86
+ }
87
+ const refused = acceptFailure(request);
88
+ if (refused !== null)
89
+ return refused;
90
+ const url = new URL(request.url);
91
+ const input = subscriptionInputFromQuery(url.searchParams);
92
+ // The header wins over a query `fromCursor`: it is what a reconnecting
93
+ // EventSource sends, and the query is only the first connection's cursor.
94
+ // The cursor's format belongs to the operation's feed, so the operation's
95
+ // input schema and the feed validate it, not this route.
96
+ const lastEventId = request.headers.get('Last-Event-ID');
97
+ if (lastEventId !== null && lastEventId !== '')
98
+ input['fromCursor'] = lastEventId;
99
+ const result = await executeSubscription(operationName, input, {
100
+ principal: context.principal,
101
+ host: context.host,
102
+ transport: 'http-rest',
103
+ registry: context.registry,
104
+ signal: request.signal,
105
+ });
106
+ if (!result.ok) {
107
+ return faultToHttpResponse(result.fault, context.isKnownErrorCode === undefined
108
+ ? undefined
109
+ : { isKnownErrorCode: context.isKnownErrorCode });
110
+ }
111
+ return streamResponse(result.value, request, context);
112
+ }
@@ -0,0 +1,162 @@
1
+ import type { ScopeVocabulary } from "../authorization-scope.js";
2
+ import type { DiscoveryInfo } from "../discovery-info.js";
3
+ import { type JsonRpcSocket, type JsonRpcSocketData } from "../json-rpc-session-runtime.js";
4
+ import { type FaultPolicy, type OperationHostFactory, type OperationInterceptor, type RegistrableOperation } from "../operation-catalog.js";
5
+ import type { ServerSentEventHeartbeatOptions } from "../operations/sse-stream.js";
6
+ import { type CorsOptions } from "../runtime/cors.js";
7
+ import type { OperationHandlerAuthenticate } from "./operation-handler-authentication.js";
8
+ import { type OperationHandlerMount } from "./operation-handler-mounts.js";
9
+ /**
10
+ * Options for {@link createOperationHandler}.
11
+ *
12
+ * `Host` is whatever the registered operations read from `host` in their
13
+ * `invoke` and `authorize` hooks. It is inferred from `host` alone, so an
14
+ * operation that needs a capability the host lacks is a compile error here.
15
+ */
16
+ export type OperationHandlerOptions<Host> = {
17
+ /**
18
+ * The whole catalog this handler serves. Weft's own operations are not added.
19
+ *
20
+ * A `subscription` that declares `transports.http` must accept `fromCursor`
21
+ * in its input: the route delivers `Last-Event-ID` as `fromCursor`, and
22
+ * construction throws naming an operation that does not. The cursor's format
23
+ * is the operation's own; it should reject a malformed one as
24
+ * `InvalidParams` (a schema `refine` does), which answers 400.
25
+ */
26
+ readonly operations: ReadonlyArray<RegistrableOperation<NoInfer<Host>>>;
27
+ /** Delivered as `host` to every `invoke` and `authorize` call. */
28
+ readonly host: Host | OperationHostFactory<Host>;
29
+ /** Interceptors that wrap each authorized invocation in registration order. */
30
+ readonly interceptors?: readonly OperationInterceptor[];
31
+ /**
32
+ * Resolves the caller. Omitted, every request is anonymous and only
33
+ * `public` operations pass. See `createOperationHandlerAuthenticator` for
34
+ * Weft's API-key and JWT schemes, including package `additionalScopes`.
35
+ *
36
+ * A host with exactly one caller, such as an embedded single-user app, can
37
+ * admit every request as the `unauthenticated-local` principal using
38
+ * `authenticate: async () => unauthenticatedLocalAuthContext(vocabulary)`.
39
+ */
40
+ readonly authenticate?: OperationHandlerAuthenticate;
41
+ /** Vocabulary for fallback principals when an authenticator returns only claims. */
42
+ readonly scopeVocabulary?: ScopeVocabulary;
43
+ /** Same validation and defaults as `ServeOptions.cors`; omitted means no CORS headers. */
44
+ readonly cors?: CorsOptions;
45
+ /** Adapters that claim a path prefix ahead of catalog routing. */
46
+ readonly mounts?: ReadonlyArray<OperationHandlerMount>;
47
+ /**
48
+ * Exact paths the handler answers without calling `authenticate`. Defaults
49
+ * to `/v1/health` and the three discovery documents; `[]` authenticates all
50
+ * of them. This is the only place the handler's own public paths are
51
+ * decided: `createOperationHandlerAuthenticator` has none of its own, and a
52
+ * mount's `publicPaths` cover its paths. An entry must be a path the handler
53
+ * serves exactly: a fixed route, or `/v1/subscriptions/<name>` for a
54
+ * registered subscription (a mount cannot claim one, so the two never overlap).
55
+ */
56
+ readonly publicPaths?: ReadonlyArray<string>;
57
+ /** The facts the discovery documents report, such as the server URL. */
58
+ readonly discoveryInfo?: DiscoveryInfo;
59
+ /**
60
+ * A binary encoding for `GET /v1/health`: when a request accepts `application/msgpack` and this
61
+ * is supplied, the answer is its bytes with that content type. Omitted, the answer is JSON. The
62
+ * handler carries no codec of its own; a host on Weft passes Weft's `encode`.
63
+ */
64
+ readonly encodeBinary?: (value: unknown) => Uint8Array;
65
+ /**
66
+ * What the host decides about the faults its operations throw: whether an undeclared fault
67
+ * answers `EngineFailure` (`strict`, on by default) or passes through with a warning, and how
68
+ * the host's own error classes map to faults. The handler reads no environment variable; a host
69
+ * on Weft's engine passes `weftFaultPolicy`, which follows `NODE_ENV` and `WEFT_STRICT_FAULTS`.
70
+ */
71
+ readonly faultPolicy?: FaultPolicy;
72
+ /** Maximum JSON-RPC request body size in bytes. Defaults to 1 MB. */
73
+ readonly maxRequestBodyBytes?: number;
74
+ /**
75
+ * How long one Server-Sent Events subscription response may stream before
76
+ * the handler ends it cleanly, so a client resumes with `Last-Event-ID`.
77
+ * A positive integer number of milliseconds, at most 2147483647 (a larger
78
+ * value overflows the timer, which then fires immediately); defaults to
79
+ * fifteen minutes.
80
+ * It applies to `GET /v1/subscriptions/:operationName` only.
81
+ */
82
+ readonly maxStreamDurationMs?: number;
83
+ /**
84
+ * Heartbeat interval and the timer and clock seam behind it. The
85
+ * `maxStreamDurationMs` deadline is armed through the same `schedule`, so a
86
+ * test drives both with one manual clock.
87
+ */
88
+ readonly heartbeat?: ServerSentEventHeartbeatOptions;
89
+ };
90
+ /** A fetch handler over a caller-supplied operation registry. */
91
+ export type OperationHandlerUpgradeServer = {
92
+ upgrade(request: Request, options: {
93
+ data: JsonRpcSocketData;
94
+ }): boolean;
95
+ };
96
+ /**
97
+ * The WebSocket entry points of the handler, typed against the part of a socket a session uses.
98
+ * Bun's `ServerWebSocket` satisfies {@link JsonRpcSocket}, so `Bun.serve({ websocket })` takes
99
+ * these as they are.
100
+ */
101
+ export type OperationHandlerWebSocket = {
102
+ open(ws: JsonRpcSocket<JsonRpcSocketData>): void;
103
+ message(ws: JsonRpcSocket<JsonRpcSocketData>, message: string | Uint8Array): void;
104
+ close(ws: JsonRpcSocket<JsonRpcSocketData>): void;
105
+ };
106
+ /** A callable catalog handler with an optional Bun WebSocket entry point. */
107
+ export type OperationHandler = ((request: Request) => Promise<Response>) & {
108
+ upgrade(request: Request, server: OperationHandlerUpgradeServer): Promise<boolean>;
109
+ websocket: OperationHandlerWebSocket;
110
+ };
111
+ /**
112
+ * Create a fetch handler that serves a caller-supplied operation registry with
113
+ * Weft's transport plumbing and never reads an `Engine`.
114
+ *
115
+ * What it serves, and in what order a request is handled: CORS preflight,
116
+ * authentication, mounts, then the catalog routes (`POST /jsonrpc`,
117
+ * `GET /v1/subscriptions/:operationName` as Server-Sent Events with
118
+ * `Last-Event-ID` replay, `GET /v1/health`, and the OpenAPI, OpenRPC, and
119
+ * AsyncAPI documents generated from the registry alone), and finally CORS
120
+ * decoration of the response.
121
+ *
122
+ * It does not serve the engine's `/mcp` (its workflow tools and resources),
123
+ * `/.well-known/*`, `/v1/metrics`, the workflow WebSocket streams, or any
124
+ * remote-worker route; those need an `Engine` and stay behind `serve()`. Its
125
+ * `upgrade` and `websocket` properties do serve catalog JSON-RPC WebSocket
126
+ * operations that declare `transports.jsonRpcWebSocket`. A catalog's own
127
+ * `mcpExposable` operations can be served as MCP tools by
128
+ * mounting `createOperationMcpMount` from `@lostgradient/weft`. Rate limiting stays there too, since its key falls back
129
+ * to the client address a fetch handler cannot see; put a limiter in front.
130
+ *
131
+ * A factory rather than a per-request function, so registry construction, CORS
132
+ * validation, mount validation, and option validation fail once, synchronously,
133
+ * before the first request.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * import { createOperationHandler, defineOperation } from '@lostgradient/backchannel';
138
+ * import { z } from 'zod';
139
+ *
140
+ * const echo = defineOperation({
141
+ * name: 'probe.echo',
142
+ * mcpExposable: false,
143
+ * summary: 'Echo a message',
144
+ * destructive: false,
145
+ * inputSchema: z.object({ message: z.string() }),
146
+ * outputSchema: z.object({ message: z.string() }),
147
+ * access: { kind: 'public' },
148
+ * transports: { http: false, jsonRpcHttp: true, jsonRpcWebSocket: false, jsonRpcStdio: false },
149
+ * unknownKeyPolicy: { http: 'reject', jsonRpc: 'reject' },
150
+ * invoke: async ({ input }) => ({ message: input.message }),
151
+ * });
152
+ *
153
+ * const handler = createOperationHandler({ operations: [echo], host: {} });
154
+ * const response = await handler(new Request('http://localhost/v1/health'));
155
+ * console.log(response.status); // 200
156
+ * ```
157
+ */
158
+ export declare function createOperationHandler<Host>(options: Omit<OperationHandlerOptions<Host>, 'host'> & {
159
+ readonly host: OperationHostFactory<Host>;
160
+ }): OperationHandler;
161
+ /** Build a catalog handler with a host value or a per-dispatch factory. */
162
+ export declare function createOperationHandler<Host>(options: OperationHandlerOptions<Host>): OperationHandler;
@@ -0,0 +1,236 @@
1
+ import { z } from 'zod';
2
+ import { handleJsonRpcHttpRequest } from "../json-rpc-http.js";
3
+ import { closeJsonRpcWebSocketSession, handleJsonRpcWebSocketMessage, openGenericJsonRpcWebSocketSession, } from "../json-rpc-session-runtime.js";
4
+ import { createOperationRegistry, executeOperation, executeSubscription, } from "../operation-catalog.js";
5
+ import { GENERIC_SUBSCRIPTION_ROUTE_PREFIX, JSON_RPC_PATH } from "../route-model.js";
6
+ import { buildPreflightResponse, decorateResponseWithCors, isOriginAllowed, isPreflightRequest, resolveCorsPolicy, validateCorsOptions, } from "../runtime/cors.js";
7
+ import { authContextToPrincipal } from "./auth-context-principal.js";
8
+ import { errorResponse, jsonResponse, negotiatedJsonOrBinary } from "./json-responses.js";
9
+ import { createOperationHandlerDocuments, } from "./operation-handler-discovery.js";
10
+ import { DEFAULT_OPERATION_HANDLER_PUBLIC_PATHS, isAtOrUnder, resolveHandlerPublicPaths, resolveMounts, } from "./operation-handler-mounts.js";
11
+ import { DEFAULT_MAX_STREAM_DURATION_MS, handleSubscriptionRequest, } from "./operation-handler-subscription.js";
12
+ import { createWorkspaceRevalidation, guardWorkspaceResponse } from "./workspace-release.js";
13
+ const HEALTH_PATH = '/v1/health';
14
+ /** The largest delay a timer honors; above it the runtime clamps the delay to 1 ms. */
15
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
16
+ function assertPositiveInteger(value, name, max = Number.MAX_SAFE_INTEGER) {
17
+ if (value === undefined)
18
+ return;
19
+ if (!Number.isSafeInteger(value) || value <= 0 || value > max) {
20
+ const bound = max === Number.MAX_SAFE_INTEGER ? '' : ` no greater than ${max}`;
21
+ throw new Error(`createOperationHandler: ${name} must be a positive integer${bound} (got ${value})`);
22
+ }
23
+ }
24
+ /**
25
+ * The `fromCursor` contract: `Last-Event-ID` is delivered to a subscription as
26
+ * its `fromCursor` input, so a subscription served over HTTP has to accept one.
27
+ * Checked at construction so a missing field is a startup error naming the
28
+ * operation, not a 400 on every reconnect.
29
+ */
30
+ function assertSubscriptionsAcceptFromCursor(registry) {
31
+ for (const operation of registry.list()) {
32
+ if (operation.kind !== 'subscription' || !operation.transports.http)
33
+ continue;
34
+ const accepts = operation.inputSchema instanceof z.ZodObject && 'fromCursor' in operation.inputSchema.shape;
35
+ if (!accepts) {
36
+ throw new Error(`createOperationHandler: subscription "${operation.name}" declares transports.http but its input has no fromCursor field, so Last-Event-ID cannot resume it`);
37
+ }
38
+ }
39
+ }
40
+ function normalizedPathname(request) {
41
+ const { pathname } = new URL(request.url);
42
+ return pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
43
+ }
44
+ export function createOperationHandler(options) {
45
+ assertPositiveInteger(options.maxRequestBodyBytes, 'maxRequestBodyBytes');
46
+ assertPositiveInteger(options.maxStreamDurationMs, 'maxStreamDurationMs', MAX_TIMER_DELAY_MS);
47
+ const authenticate = options.authenticate;
48
+ const registry = createOperationRegistry(options.operations, {
49
+ faultPolicy: options.faultPolicy,
50
+ interceptors: options.interceptors,
51
+ });
52
+ assertSubscriptionsAcceptFromCursor(registry);
53
+ const mounts = resolveMounts(options.mounts ?? []);
54
+ const publicPaths = resolveHandlerPublicPaths(options.publicPaths ?? DEFAULT_OPERATION_HANDLER_PUBLIC_PATHS, registry);
55
+ const corsPolicy = options.cors === undefined
56
+ ? undefined
57
+ : (validateCorsOptions(options.cors, authenticate !== undefined),
58
+ resolveCorsPolicy(options.cors, authenticate !== undefined));
59
+ const documents = createOperationHandlerDocuments({
60
+ registry,
61
+ discoveryInfo: options.discoveryInfo,
62
+ authenticates: authenticate !== undefined,
63
+ publicPaths,
64
+ });
65
+ const activeSessions = new Set();
66
+ const handle = async (request) => {
67
+ const pathname = normalizedPathname(request);
68
+ const isPublic = publicPaths.has(pathname) || mounts.isPublic(pathname);
69
+ let authContext;
70
+ if (authenticate !== undefined && !isPublic) {
71
+ const outcome = await authenticate(request);
72
+ if (outcome instanceof Response)
73
+ return outcome;
74
+ authContext = outcome;
75
+ }
76
+ const principal = authContextToPrincipal(authContext, options.scopeVocabulary);
77
+ const revalidate = createWorkspaceRevalidation(authenticate, request, principal);
78
+ const mount = mounts.match(pathname);
79
+ if (mount !== undefined) {
80
+ return guardWorkspaceResponse(await mount.fetch(request, mountContext(registry, options.host, principal, request.signal)), revalidate);
81
+ }
82
+ return guardWorkspaceResponse(await routeCatalog({ request, pathname, principal, registry, documents, options }), revalidate);
83
+ };
84
+ const handler = async (request) => {
85
+ if (corsPolicy !== undefined && isPreflightRequest(request)) {
86
+ return buildPreflightResponse(corsPolicy, request);
87
+ }
88
+ let response;
89
+ try {
90
+ response = await handle(request);
91
+ }
92
+ catch (error) {
93
+ console.error('Unhandled error in createOperationHandler', {
94
+ method: request.method,
95
+ path: new URL(request.url).pathname,
96
+ error,
97
+ });
98
+ response = errorResponse('Internal server error', 500);
99
+ }
100
+ return corsPolicy === undefined ? response : decorate(corsPolicy, request, response);
101
+ };
102
+ handler.upgrade = async (request, server) => {
103
+ const pathname = normalizedPathname(request);
104
+ if (pathname !== JSON_RPC_PATH)
105
+ return false;
106
+ const origin = request.headers.get('Origin');
107
+ if (corsPolicy !== undefined && origin !== null && !isOriginAllowed(corsPolicy, origin)) {
108
+ return false;
109
+ }
110
+ let authContext;
111
+ const isPublic = publicPaths.has(pathname) || mounts.isPublic(pathname);
112
+ if (authenticate !== undefined && !isPublic) {
113
+ const outcome = await authenticate(request);
114
+ if (outcome instanceof Response)
115
+ return false;
116
+ authContext = outcome;
117
+ }
118
+ const principal = authContextToPrincipal(authContext, options.scopeVocabulary);
119
+ const revalidateWorkspace = createWorkspaceRevalidation(authenticate, request, principal);
120
+ return server.upgrade(request, {
121
+ data: {
122
+ pathname,
123
+ connectionType: 'jsonrpc',
124
+ principal,
125
+ ...(revalidateWorkspace === undefined ? {} : { revalidateWorkspace }),
126
+ },
127
+ });
128
+ };
129
+ handler.websocket = {
130
+ open(ws) {
131
+ openGenericJsonRpcWebSocketSession({
132
+ ws,
133
+ registry,
134
+ host: options.host,
135
+ activeSessions,
136
+ discoverDocument: documents.openRpc,
137
+ });
138
+ },
139
+ message(ws, message) {
140
+ handleJsonRpcWebSocketMessage(ws, message);
141
+ },
142
+ close(ws) {
143
+ ws.data.workspaceClosed = true;
144
+ closeJsonRpcWebSocketSession({ session: ws.data.jsonRpcSession, activeSessions });
145
+ },
146
+ };
147
+ return handler;
148
+ }
149
+ /**
150
+ * Add the CORS headers to a mutable copy of the response. A `fetch()` result,
151
+ * `Response.redirect()`, or any response a hook hands back may carry immutable
152
+ * headers, and `decorateResponseWithCors` sets them in place. The copy shares
153
+ * the body stream, so nothing is buffered. A network-error response
154
+ * (`Response.error()`) has no headers to add and cannot be copied, so it is
155
+ * returned as it is.
156
+ */
157
+ function decorate(policy, request, response) {
158
+ if (response.type === 'error')
159
+ return response;
160
+ return decorateResponseWithCors(policy, request, new Response(response.body, response));
161
+ }
162
+ function mountContext(registry, host, principal, signal) {
163
+ const contextFor = (options) => ({
164
+ principal,
165
+ host,
166
+ transport: options?.transport ?? 'http-rest',
167
+ registry,
168
+ signal: options?.signal === undefined ? signal : AbortSignal.any([signal, options.signal]),
169
+ });
170
+ return {
171
+ principal,
172
+ operations: registry.list(),
173
+ dispatch: (operationName, input, options) => executeOperation(operationName, input, contextFor(options)),
174
+ subscribe: (operationName, input, options) => executeSubscription(operationName, input, contextFor(options)),
175
+ };
176
+ }
177
+ async function routeCatalog(catalog) {
178
+ const { request, pathname, options } = catalog;
179
+ if (pathname === JSON_RPC_PATH) {
180
+ return handleJsonRpcHttpRequest(request, {
181
+ registry: catalog.registry,
182
+ host: options.host,
183
+ principal: catalog.principal,
184
+ discoverDocument: catalog.documents.openRpc,
185
+ ...(options.maxRequestBodyBytes === undefined
186
+ ? {}
187
+ : { maxBodyBytes: options.maxRequestBodyBytes }),
188
+ });
189
+ }
190
+ if (isAtOrUnder(pathname, GENERIC_SUBSCRIPTION_ROUTE_PREFIX)) {
191
+ return routeSubscription(catalog);
192
+ }
193
+ if (request.method === 'GET') {
194
+ const response = routeGet(catalog, options.encodeBinary);
195
+ if (response !== null)
196
+ return response;
197
+ }
198
+ return errorResponse(`Not found: ${request.method} ${pathname}`, 404);
199
+ }
200
+ function routeGet(catalog, encodeBinary) {
201
+ const { request, pathname, documents } = catalog;
202
+ switch (pathname) {
203
+ case HEALTH_PATH:
204
+ return negotiatedJsonOrBinary(request, { status: 'ok' }, 200, encodeBinary);
205
+ case '/openapi.json':
206
+ return jsonResponse(documents.openApi());
207
+ case '/openrpc.json':
208
+ return jsonResponse(documents.openRpc());
209
+ case '/asyncapi.json':
210
+ return jsonResponse(documents.asyncApi());
211
+ default:
212
+ return null;
213
+ }
214
+ }
215
+ function routeSubscription(catalog) {
216
+ const { request, pathname, options } = catalog;
217
+ const rawName = pathname.slice(GENERIC_SUBSCRIPTION_ROUTE_PREFIX.length + 1);
218
+ if (rawName === '' || rawName.includes('/')) {
219
+ return Promise.resolve(errorResponse(`Not found: ${request.method} ${pathname}`, 404));
220
+ }
221
+ let operationName;
222
+ try {
223
+ operationName = decodeURIComponent(rawName);
224
+ }
225
+ catch {
226
+ return Promise.resolve(errorResponse('Malformed route parameter', 400));
227
+ }
228
+ return handleSubscriptionRequest(request, operationName, {
229
+ registry: catalog.registry,
230
+ host: options.host,
231
+ principal: catalog.principal,
232
+ maxStreamDurationMs: options.maxStreamDurationMs ?? DEFAULT_MAX_STREAM_DURATION_MS,
233
+ heartbeat: options.heartbeat,
234
+ isKnownErrorCode: options.faultPolicy?.isKnownErrorCode,
235
+ });
236
+ }
@@ -0,0 +1,6 @@
1
+ import type { Principal } from "../principal.js";
2
+ import type { OperationHandlerAuthenticate } from "./operation-handler-authentication.js";
3
+ /** Recheck a workspace connection without allowing a credential to change its identity. */
4
+ export declare function createWorkspaceRevalidation(authenticate: OperationHandlerAuthenticate | undefined, request: Request, principal: Principal): (() => Promise<boolean>) | undefined;
5
+ /** Check immediately before returning a response and before releasing each buffered body chunk. */
6
+ export declare function guardWorkspaceResponse(response: Response, revalidate: (() => Promise<boolean>) | undefined): Promise<Response>;
@@ -0,0 +1,75 @@
1
+ function retainsWorkspaceAuthority(original, current) {
2
+ return (current.workspaceId === original.workspaceId &&
3
+ current.actorId === original.actorId &&
4
+ current.owner === original.owner &&
5
+ current.actorKind === original.actorKind &&
6
+ current.capabilities.includes('workspace:use') &&
7
+ original.capabilities.every((capability) => current.capabilities.includes(capability)));
8
+ }
9
+ function retainsCredentialRevision(method, original, current) {
10
+ return ((method !== 'browser-session' && method !== 'connector-token') ||
11
+ current.membershipRevision === original.membershipRevision);
12
+ }
13
+ /** Recheck a workspace connection without allowing a credential to change its identity. */
14
+ export function createWorkspaceRevalidation(authenticate, request, principal) {
15
+ if (authenticate === undefined ||
16
+ principal.method === 'unauthenticated' ||
17
+ principal.workspace === undefined)
18
+ return undefined;
19
+ const original = structuredClone(principal.workspace);
20
+ const method = principal.method;
21
+ const subject = principal.subject;
22
+ const scopes = [...principal.scopes];
23
+ return async () => {
24
+ try {
25
+ const context = await authenticate(request);
26
+ if (context instanceof Response)
27
+ return false;
28
+ const current = context.principal;
29
+ const workspace = current?.workspace;
30
+ return (current !== undefined &&
31
+ workspace !== undefined &&
32
+ current.method === method &&
33
+ current.subject === subject &&
34
+ retainsCredentialRevision(method, original, workspace) &&
35
+ retainsWorkspaceAuthority(original, workspace) &&
36
+ scopes.every((scope) => current.hasScope(scope)));
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ };
42
+ }
43
+ /** Check immediately before returning a response and before releasing each buffered body chunk. */
44
+ export async function guardWorkspaceResponse(response, revalidate) {
45
+ if (revalidate === undefined)
46
+ return response;
47
+ if (!(await revalidate())) {
48
+ await response.body?.cancel();
49
+ return new Response('Workspace membership required', { status: 403 });
50
+ }
51
+ if (response.body === null)
52
+ return response;
53
+ const reader = response.body.getReader();
54
+ const body = new ReadableStream({
55
+ async pull(controller) {
56
+ const frame = await reader.read();
57
+ if (frame.done) {
58
+ controller.close();
59
+ return;
60
+ }
61
+ if (!(await revalidate())) {
62
+ await reader.cancel();
63
+ controller.close();
64
+ return;
65
+ }
66
+ controller.enqueue(frame.value);
67
+ },
68
+ cancel: (reason) => reader.cancel(reason),
69
+ });
70
+ return new Response(body, {
71
+ status: response.status,
72
+ statusText: response.statusText,
73
+ headers: response.headers,
74
+ });
75
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * A `ReplayLiveFeedBackend` that keeps its log in memory.
3
+ *
4
+ * This is the live-only half of the feed's two shapes. `createReplayLiveFeed`
5
+ * is generic over its backend, so a feed built on this one supports replay,
6
+ * cursors, late joins, and filtering exactly as a durable feed does — for as
7
+ * long as the process lives. Swapping in a persisted backend later changes
8
+ * this file and nothing above it: not the feed, not a subscription operation,
9
+ * not a client.
10
+ *
11
+ * WHAT IT COSTS TO CHOOSE THIS FIRST. Events are lost on restart, and a
12
+ * client that reconnects after the process died receives a gap and can
13
+ * continue from the new log, but cannot recover lost events. `maxEvents`
14
+ * bounds the log so a long-lived producer cannot exhaust memory; once it is
15
+ * reached the oldest envelopes are dropped and a reconnect also sees a gap.
16
+ *
17
+ * Distinct from `in-memory-event-feed-backend.test-support.ts`, which
18
+ * implements the workflow-specific `WorkflowEventFeedBackend` (bucketed by
19
+ * workflow and selector) and is a test helper. This one is generic, carries
20
+ * no domain keys, and is production code.
21
+ *
22
+ * @module server/in-memory-replay-live-backend
23
+ */
24
+ import type { ReplayLiveFeedBackend } from "./replay-live-feed-types.js";
25
+ import type { Cursor, SequencedEventEnvelope } from "./sequence-cursor.js";
26
+ /** An in-memory {@link ReplayLiveFeedBackend}: a bounded log of envelopes with an append method, for hosts and tests that have no durable event log. */
27
+ export type InMemoryReplayLiveBackend<TEnvelope extends SequencedEventEnvelope> = ReplayLiveFeedBackend<TEnvelope> & {
28
+ /** Records an envelope and delivers it to live subscribers. */
29
+ append(envelope: TEnvelope): void;
30
+ /** Envelopes currently retained, oldest first. */
31
+ readonly size: number;
32
+ /** Releases every subscriber and clears the log. */
33
+ dispose(): void;
34
+ };
35
+ /** Options for {@link createInMemoryReplayLiveBackend}. */
36
+ export type InMemoryReplayLiveBackendOptions = {
37
+ /** Retention bound. Defaults to 10,000 envelopes. */
38
+ maxEvents?: number;
39
+ /** Builds the envelope that tells a subscriber its cursor fell outside the retained window. */
40
+ createGapEnvelope?: (options: {
41
+ requestedCursor: Cursor;
42
+ firstRetainedSequence: number;
43
+ continuationCursor: Cursor;
44
+ }) => SequencedEventEnvelope;
45
+ };
46
+ /** Creates an {@link InMemoryReplayLiveBackend} that keeps at most `maxEvents` envelopes and signals a gap to a cursor from an earlier incarnation. */
47
+ export declare function createInMemoryReplayLiveBackend<TEnvelope extends SequencedEventEnvelope>(options?: InMemoryReplayLiveBackendOptions): InMemoryReplayLiveBackend<TEnvelope>;