@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,224 @@
1
+ import { CatalogClientError } from "./catalog-client.js";
2
+ import { parseServerSentEventChunk, } from "./server-sent-event-parser.js";
3
+ /** The JSON-RPC server-error code a stream's `error` frame is reported under. */
4
+ const STREAM_ERROR_CODE = -32000;
5
+ /** The JSON-RPC parse-error code, for an event whose data is not JSON. */
6
+ const PARSE_ERROR_CODE = -32700;
7
+ const DEFAULT_ROUTE_PREFIX = '/v1/subscriptions';
8
+ /**
9
+ * The URL a subscription is opened at: the base, the route prefix, the encoded operation name,
10
+ * and the input as a query string. A repeated key carries an array, an absent or `undefined`
11
+ * field is left out, and a value that is not a string, number or boolean is sent as JSON.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { subscriptionUrl } from '@lostgradient/backchannel/client';
16
+ *
17
+ * console.log(
18
+ * subscriptionUrl({ baseUrl: '/api' }, 'probe.jobs.watch', { topic: 'a', kinds: ['x', 'y'] }),
19
+ * ); // /api/v1/subscriptions/probe.jobs.watch?topic=a&kinds=x&kinds=y
20
+ * ```
21
+ */
22
+ export function subscriptionUrl(connection, operationName, input) {
23
+ const base = connection.baseUrl.replace(/[?#].*$/u, '').replace(/\/+$/u, '');
24
+ const prefix = (connection.routePrefix ?? DEFAULT_ROUTE_PREFIX).replace(/\/+$/u, '');
25
+ const query = new URLSearchParams();
26
+ if (typeof input === 'object' && input !== null) {
27
+ for (const [key, value] of Object.entries(input)) {
28
+ for (const entry of Array.isArray(value) ? value : [value]) {
29
+ if (entry !== undefined)
30
+ query.append(key, queryValue(entry));
31
+ }
32
+ }
33
+ }
34
+ const search = query.toString();
35
+ return `${base}${prefix}/${encodeURIComponent(operationName)}${search === '' ? '' : `?${search}`}`;
36
+ }
37
+ function queryValue(value) {
38
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
39
+ ? String(value)
40
+ : JSON.stringify(value);
41
+ }
42
+ /**
43
+ * Transport that opens a subscription as a Server-Sent Events stream at
44
+ * `GET ${baseUrl}${routePrefix}/${operationName}`, which is what the operation handler serves.
45
+ *
46
+ * The iteration yields each event with its `id`, then one `replay-complete` marker when the
47
+ * server says the replay is done. `lastEventId` is sent as `Last-Event-ID`, so the stream resumes
48
+ * after that event. Aborting the signal ends the iteration without an error; leaving the loop
49
+ * early closes the connection. A stream that reports an error, a response that is not a success
50
+ * and a response that is not an event stream each throw a {@link CatalogClientError}. One call
51
+ * opens one stream: reconnecting is the caller's.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * import { sseSubscriptionTransport } from '@lostgradient/backchannel/client';
56
+ *
57
+ * const transport = sseSubscriptionTransport({ baseUrl: 'https://api.example.test' });
58
+ * const controller = new AbortController();
59
+ *
60
+ * for await (const message of transport('probe.jobs.watch', {}, { signal: controller.signal })) {
61
+ * if (message.type === 'event') console.log(message.id, message.data);
62
+ * }
63
+ * ```
64
+ */
65
+ export function sseSubscriptionTransport(connection) {
66
+ return (operationName, input, options) => readSubscription(connection, operationName, input, options);
67
+ }
68
+ async function* readSubscription(connection, operationName, input, options) {
69
+ const caller = options?.signal;
70
+ if (caller?.aborted)
71
+ return;
72
+ const controller = new AbortController();
73
+ const onAbort = () => controller.abort(caller?.reason);
74
+ caller?.addEventListener('abort', onAbort, { once: true });
75
+ try {
76
+ const response = await open(connection, operationName, input, options, controller.signal);
77
+ if (response === null)
78
+ return;
79
+ yield* readFrames(operationName, response, caller);
80
+ }
81
+ finally {
82
+ caller?.removeEventListener('abort', onAbort);
83
+ controller.abort();
84
+ }
85
+ }
86
+ /** Opens the stream, or returns null when the caller aborted before the response arrived. */
87
+ async function open(connection, operationName, input, options, signal) {
88
+ const send = options?.fetch ?? connection.fetch ?? globalThis.fetch;
89
+ // The call's options belong to the caller: read the signal now, not after the request awaits.
90
+ const caller = options?.signal;
91
+ let response;
92
+ try {
93
+ response = await send(subscriptionUrl(connection, operationName, input), {
94
+ method: 'GET',
95
+ headers: requestHeaders(connection, options),
96
+ signal,
97
+ });
98
+ }
99
+ catch (error) {
100
+ if (caller?.aborted === true)
101
+ return null;
102
+ throw error;
103
+ }
104
+ if (!response.ok)
105
+ throw await failedResponse(operationName, response);
106
+ await requireEventStream(operationName, response);
107
+ return response;
108
+ }
109
+ /** The connection's headers, the media type asked for, and `Last-Event-ID` when resuming. */
110
+ function requestHeaders(connection, options) {
111
+ const headers = { ...connection.headers, accept: 'text/event-stream' };
112
+ if (options?.lastEventId !== undefined)
113
+ headers['last-event-id'] = options.lastEventId;
114
+ return headers;
115
+ }
116
+ async function requireEventStream(operationName, response) {
117
+ if (isEventStream(response) && response.body !== null)
118
+ return;
119
+ await response.body?.cancel().catch(() => undefined);
120
+ throw new CatalogClientError(operationName, {
121
+ code: response.status,
122
+ message: `Expected an event stream for ${operationName}, not ${response.headers.get('content-type') ?? 'no content type'}`,
123
+ });
124
+ }
125
+ async function* readFrames(operationName, response, caller) {
126
+ const reader = response.body.getReader();
127
+ const decoder = new TextDecoder();
128
+ const state = { replayCompleteSeen: false };
129
+ let remainder = '';
130
+ try {
131
+ for (;;) {
132
+ let chunk;
133
+ try {
134
+ chunk = await reader.read();
135
+ }
136
+ catch (error) {
137
+ if (caller?.aborted === true)
138
+ return;
139
+ throw error;
140
+ }
141
+ if (chunk.done)
142
+ return;
143
+ const parsed = parseServerSentEventChunk(decoder.decode(chunk.value, { stream: true }), remainder);
144
+ remainder = parsed.remainder;
145
+ for (const frame of parsed.frames) {
146
+ const message = interpret(operationName, frame, state);
147
+ if (message !== undefined)
148
+ yield message;
149
+ }
150
+ }
151
+ }
152
+ finally {
153
+ await reader.cancel().catch(() => undefined);
154
+ }
155
+ }
156
+ function interpret(operationName, frame, state) {
157
+ if (frame.event === 'error')
158
+ throw streamError(operationName, frame.data);
159
+ if (frame.event === 'ping') {
160
+ if (state.replayCompleteSeen || !isReplayComplete(frame.data))
161
+ return undefined;
162
+ state.replayCompleteSeen = true;
163
+ return { type: 'replay-complete' };
164
+ }
165
+ if (frame.id === undefined)
166
+ return undefined;
167
+ return { type: 'event', id: frame.id, data: parseEventData(operationName, frame.data) };
168
+ }
169
+ function parseEventData(operationName, data) {
170
+ try {
171
+ return JSON.parse(data);
172
+ }
173
+ catch {
174
+ throw new CatalogClientError(operationName, {
175
+ code: PARSE_ERROR_CODE,
176
+ message: `${operationName} sent an event whose data is not JSON`,
177
+ });
178
+ }
179
+ }
180
+ function isReplayComplete(data) {
181
+ const parsed = tryParse(data);
182
+ return isRecord(parsed) && parsed['replayComplete'] === true;
183
+ }
184
+ function streamError(operationName, data) {
185
+ const parsed = tryParse(data);
186
+ const body = isRecord(parsed) ? parsed : {};
187
+ const message = typeof body['message'] === 'string' ? body['message'] : 'The stream failed';
188
+ return new CatalogClientError(operationName, {
189
+ code: STREAM_ERROR_CODE,
190
+ message,
191
+ // The frame's `retryable` and `remediation` are the fault's advice, kept for the caller.
192
+ data: {
193
+ code: body['code'],
194
+ data: body['data'],
195
+ ...(typeof body['retryable'] === 'boolean' ? { retryable: body['retryable'] } : {}),
196
+ ...(typeof body['remediation'] === 'string' ? { remediation: body['remediation'] } : {}),
197
+ },
198
+ });
199
+ }
200
+ async function failedResponse(operationName, response) {
201
+ const parsed = tryParse(await response.text().catch(() => ''));
202
+ const body = isRecord(parsed) ? parsed : {};
203
+ const text = body['message'] ?? body['error'];
204
+ return new CatalogClientError(operationName, {
205
+ code: response.status,
206
+ message: typeof text === 'string' ? text : response.statusText || `HTTP ${response.status}`,
207
+ data: parsed,
208
+ });
209
+ }
210
+ function isEventStream(response) {
211
+ const contentType = response.headers.get('content-type');
212
+ return contentType?.split(';', 1)[0]?.trim().toLowerCase() === 'text/event-stream';
213
+ }
214
+ function tryParse(text) {
215
+ try {
216
+ return JSON.parse(text);
217
+ }
218
+ catch {
219
+ return undefined;
220
+ }
221
+ }
222
+ function isRecord(value) {
223
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
224
+ }
@@ -0,0 +1,122 @@
1
+ import type { CatalogCallOptions } from "./catalog-client.js";
2
+ /**
3
+ * One thing a subscription yields: an `event`, typed by the operation's `eventSchema`, with the
4
+ * `id` to resume after it, or the single `replay-complete` marker that says every event recorded
5
+ * before the subscription opened has been delivered and what follows is live.
6
+ *
7
+ * Narrow on `type`. Keep the `id` of the last event you handled and pass it back as
8
+ * `lastEventId` to resume.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import type { SubscriptionMessage } from '@lostgradient/backchannel/client';
13
+ *
14
+ * declare const message: SubscriptionMessage<{ kind: string }>;
15
+ *
16
+ * if (message.type === 'event') {
17
+ * console.log(message.id, message.data.kind);
18
+ * } else {
19
+ * console.log('caught up');
20
+ * }
21
+ * ```
22
+ */
23
+ export type SubscriptionMessage<Event> = {
24
+ readonly type: 'event';
25
+ readonly id: string;
26
+ readonly data: Event;
27
+ } | {
28
+ readonly type: 'replay-complete';
29
+ };
30
+ /**
31
+ * What one subscription call can carry beyond its input: the abort `signal` that ends it, the
32
+ * `fetch` to open it with, and `lastEventId`, the `id` of the last event the caller handled, so
33
+ * the stream resumes after it.
34
+ *
35
+ * Aborting the signal ends the iteration without an error. The stream is one connection: when it
36
+ * drops, reconnecting with the last `id` is the caller's to do.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * import type { SubscriptionCallOptions } from '@lostgradient/backchannel/client';
41
+ *
42
+ * const controller = new AbortController();
43
+ * const options: SubscriptionCallOptions = { signal: controller.signal, lastEventId: '41' };
44
+ * console.log(options.lastEventId);
45
+ * ```
46
+ */
47
+ export type SubscriptionCallOptions = CatalogCallOptions & {
48
+ /** The `id` of the last event handled; the stream resumes after it. */
49
+ readonly lastEventId?: string | undefined;
50
+ };
51
+ /**
52
+ * Transport seam for a subscription client: opens one stream for an operation and its input and
53
+ * returns what the server sends, typed as {@link SubscriptionMessage}. {@link sseSubscriptionTransport}
54
+ * reads it over Server-Sent Events; writing your own routes it to a fake or an in-process host.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import type { SubscriptionTransport } from '@lostgradient/backchannel/client';
59
+ *
60
+ * const empty: SubscriptionTransport = async function* () {
61
+ * yield { type: 'replay-complete' };
62
+ * };
63
+ * console.log(typeof empty);
64
+ * ```
65
+ */
66
+ export type SubscriptionTransport = (operationName: string, input: unknown, options?: SubscriptionCallOptions) => AsyncIterable<SubscriptionMessage<unknown>>;
67
+ type SubscriptionOperationTypes = Record<string, {
68
+ readonly input: unknown;
69
+ readonly event: unknown;
70
+ }>;
71
+ /**
72
+ * The shape a subscription client takes: one method per subscription name, each accepting that
73
+ * operation's input and an optional {@link SubscriptionCallOptions}, and returning an
74
+ * `AsyncIterable` of its events and the replay-complete marker.
75
+ *
76
+ * Nothing is requested until the iteration starts, and leaving the loop early closes the stream.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * import type { SubscriptionClient } from '@lostgradient/backchannel/client';
81
+ *
82
+ * type Operations = {
83
+ * 'probe.jobs.watch': {
84
+ * readonly input: { topic?: string };
85
+ * readonly event: { kind: string; cursor: string };
86
+ * };
87
+ * };
88
+ *
89
+ * declare const client: SubscriptionClient<Operations>;
90
+ * const controller = new AbortController();
91
+ *
92
+ * for await (const message of client['probe.jobs.watch']({}, { signal: controller.signal })) {
93
+ * if (message.type === 'event') console.log(message.id, message.data.kind);
94
+ * }
95
+ * ```
96
+ */
97
+ export type SubscriptionClient<Operations extends SubscriptionOperationTypes> = {
98
+ readonly [Name in keyof Operations]: (input: Operations[Name]['input'], options?: SubscriptionCallOptions) => AsyncIterable<SubscriptionMessage<Operations[Name]['event']>>;
99
+ };
100
+ /**
101
+ * Build a subscription client from a list of subscription names and a transport. Each name
102
+ * becomes a method that forwards its input and options through the transport.
103
+ *
104
+ * A generated `create...Client` function pairs the generated names with
105
+ * {@link sseSubscriptionTransport}. Call this directly when you supply the transport yourself.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * import {
110
+ * createSubscriptionClient,
111
+ * sseSubscriptionTransport,
112
+ * } from '@lostgradient/backchannel/client';
113
+ *
114
+ * const client = createSubscriptionClient<{
115
+ * 'probe.jobs.watch': { readonly input: { topic?: string }; readonly event: { kind: string } };
116
+ * }>(['probe.jobs.watch'], sseSubscriptionTransport({ baseUrl: 'https://api.example.test' }));
117
+ *
118
+ * console.log(typeof client['probe.jobs.watch']);
119
+ * ```
120
+ */
121
+ export declare function createSubscriptionClient<Operations extends SubscriptionOperationTypes>(operationNames: readonly (keyof Operations & string)[], transport: SubscriptionTransport): SubscriptionClient<Operations>;
122
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Build a subscription client from a list of subscription names and a transport. Each name
3
+ * becomes a method that forwards its input and options through the transport.
4
+ *
5
+ * A generated `create...Client` function pairs the generated names with
6
+ * {@link sseSubscriptionTransport}. Call this directly when you supply the transport yourself.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import {
11
+ * createSubscriptionClient,
12
+ * sseSubscriptionTransport,
13
+ * } from '@lostgradient/backchannel/client';
14
+ *
15
+ * const client = createSubscriptionClient<{
16
+ * 'probe.jobs.watch': { readonly input: { topic?: string }; readonly event: { kind: string } };
17
+ * }>(['probe.jobs.watch'], sseSubscriptionTransport({ baseUrl: 'https://api.example.test' }));
18
+ *
19
+ * console.log(typeof client['probe.jobs.watch']);
20
+ * ```
21
+ */
22
+ export function createSubscriptionClient(operationNames, transport) {
23
+ const methods = {};
24
+ for (const operationName of operationNames) {
25
+ methods[operationName] = (input, options) => transport(operationName, input, options);
26
+ }
27
+ return methods;
28
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A held connection: the transport that opened it calls `release` once, when the connection ends.
3
+ * Declared apart from the server's connection counting so the transports that hold one need not
4
+ * import the server's runtime context.
5
+ *
6
+ * @module server/connection-lease
7
+ */
8
+ export type ConnectionLease = Readonly<{
9
+ release(): void;
10
+ }>;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A held connection: the transport that opened it calls `release` once, when the connection ends.
3
+ * Declared apart from the server's connection counting so the transports that hold one need not
4
+ * import the server's runtime context.
5
+ *
6
+ * @module server/connection-lease
7
+ */
8
+ export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Shared operation filter for public discovery documents.
3
+ *
4
+ * @module server/discovery-filter
5
+ */
6
+ import type { ErasedOperation } from "./operation-catalog.js";
7
+ /**
8
+ * Return whether an operation should appear in generated discovery documents.
9
+ *
10
+ * Public operations are always discoverable. Non-public operations opt in with
11
+ * `discoverable: true`; `discoverable: false` cannot hide a public operation.
12
+ */
13
+ export declare function isDiscoverable(operation: Pick<ErasedOperation, 'access' | 'discoverable'>): boolean;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shared operation filter for public discovery documents.
3
+ *
4
+ * @module server/discovery-filter
5
+ */
6
+ /**
7
+ * Return whether an operation should appear in generated discovery documents.
8
+ *
9
+ * Public operations are always discoverable. Non-public operations opt in with
10
+ * `discoverable: true`; `discoverable: false` cannot hide a public operation.
11
+ */
12
+ export function isDiscoverable(operation) {
13
+ if (operation.access.kind === 'public')
14
+ return true;
15
+ return operation.discoverable === true;
16
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Shared `DiscoveryInfo` type and helper for applying it to API discovery documents.
3
+ *
4
+ * @module server/discovery-info
5
+ */
6
+ /**
7
+ * Operator-supplied metadata applied uniformly to all three discovery documents
8
+ * (`/openapi.json`, `/openrpc.json`, `/asyncapi.json`). Set it once on
9
+ * `serve({ discoveryInfo })` and the description, contact, license, and
10
+ * external-docs fields appear in every discovery surface from a single source,
11
+ * so the three documents never drift.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { type DiscoveryInfo } from '@lostgradient/backchannel';
16
+ * import { serve } from '@lostgradient/weft';
17
+ * import { Engine } from '@lostgradient/weft';
18
+ * import { MemoryStorage } from '@lostgradient/storage';
19
+ *
20
+ * const discoveryInfo: DiscoveryInfo = {
21
+ * description: 'Order processing API',
22
+ * contact: { name: 'Platform', email: 'platform@example.com' },
23
+ * license: { name: 'MIT' },
24
+ * };
25
+ *
26
+ * await using engine = new Engine({ storage: new MemoryStorage() });
27
+ * await using server = serve({ engine, discoveryInfo });
28
+ * void server;
29
+ * ```
30
+ */
31
+ export type DiscoveryInfo = {
32
+ /**
33
+ * Document title rendered in each document's `info.title`. Absent, the document carries the
34
+ * title of the server that generates it (Weft's own server uses `'Weft Workflow Engine'`).
35
+ */
36
+ title?: string;
37
+ /**
38
+ * Document version rendered in each document's `info.version`. Absent, the document carries the
39
+ * version of the server that generates it (Weft's own server uses the Weft package version).
40
+ */
41
+ version?: string;
42
+ /** Long-form description rendered in each document's `info.description`. */
43
+ description?: string;
44
+ /** Contact details rendered in each document's `info.contact`. */
45
+ contact?: {
46
+ name?: string;
47
+ url?: string;
48
+ email?: string;
49
+ };
50
+ /** License rendered in each document's `info.license`. */
51
+ license?: {
52
+ name: string;
53
+ url?: string;
54
+ };
55
+ /**
56
+ * External documentation reference. **Placement is asymmetric across the
57
+ * three discovery documents:**
58
+ *
59
+ * - OpenAPI 3.1: rendered inside `info.externalDocs` (or at the document
60
+ * root depending on the OpenAPI generator's chosen location, but
61
+ * semantically attached to the document's metadata block).
62
+ * - OpenRPC 1.3.2: rendered inside `info.externalDocs`.
63
+ * - AsyncAPI 3.0.0: rendered at the **document top-level**, NOT inside
64
+ * `info`. The AsyncAPI 3.0 spec moved `externalDocs` out of `info`.
65
+ *
66
+ * `applyDiscoveryInfo` does NOT place this field; each generator's call
67
+ * site is responsible for picking the spec-correct location.
68
+ */
69
+ externalDocs?: {
70
+ description?: string;
71
+ url: string;
72
+ };
73
+ };
74
+ /**
75
+ * The `title` and `version` a document's `info` starts from: the generator's explicit option,
76
+ * else `info.title` and `info.version`, else a neutral `'API'` and `'0.0.0'`. A server that
77
+ * has its own name and version supplies them through `DiscoveryInfo`, so the generators name
78
+ * no server in particular.
79
+ */
80
+ export declare function resolveDocumentTitleAndVersion(explicit: {
81
+ readonly title?: string | undefined;
82
+ readonly version?: string | undefined;
83
+ }, info: DiscoveryInfo | undefined): {
84
+ title: string;
85
+ version: string;
86
+ };
87
+ /**
88
+ * Merge `DiscoveryInfo` fields into a document's `info` object (or top-level
89
+ * for AsyncAPI 3.0 `externalDocs`).
90
+ *
91
+ * Returns a shallow copy of `target` with the discovery info fields applied.
92
+ * Fields absent from `info` are omitted from the output.
93
+ */
94
+ export declare function applyDiscoveryInfo(target: Record<string, unknown>, info: DiscoveryInfo | undefined): Record<string, unknown>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Shared `DiscoveryInfo` type and helper for applying it to API discovery documents.
3
+ *
4
+ * @module server/discovery-info
5
+ */
6
+ /**
7
+ * The `title` and `version` a document's `info` starts from: the generator's explicit option,
8
+ * else `info.title` and `info.version`, else a neutral `'API'` and `'0.0.0'`. A server that
9
+ * has its own name and version supplies them through `DiscoveryInfo`, so the generators name
10
+ * no server in particular.
11
+ */
12
+ export function resolveDocumentTitleAndVersion(explicit, info) {
13
+ return {
14
+ title: explicit.title ?? info?.title ?? 'API',
15
+ version: explicit.version ?? info?.version ?? '0.0.0',
16
+ };
17
+ }
18
+ /**
19
+ * Merge `DiscoveryInfo` fields into a document's `info` object (or top-level
20
+ * for AsyncAPI 3.0 `externalDocs`).
21
+ *
22
+ * Returns a shallow copy of `target` with the discovery info fields applied.
23
+ * Fields absent from `info` are omitted from the output.
24
+ */
25
+ export function applyDiscoveryInfo(target, info) {
26
+ if (info === undefined)
27
+ return target;
28
+ const result = { ...target };
29
+ if (info.description !== undefined)
30
+ result['description'] = info.description;
31
+ if (info.contact !== undefined)
32
+ result['contact'] = { ...info.contact };
33
+ if (info.license !== undefined)
34
+ result['license'] = { ...info.license };
35
+ // externalDocs is applied at the call site (document top-level for AsyncAPI,
36
+ // inside info for OpenAPI/OpenRPC)
37
+ return result;
38
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Which of a workflow's two event streams a subscriber reads: its lifecycle `events` or its
3
+ * `tokens`. Declared apart from the feed so a session can validate the choice without importing it.
4
+ *
5
+ * @module server/event-selector
6
+ */
7
+ export type EventSelector = 'events' | 'tokens';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Which of a workflow's two event streams a subscriber reads: its lifecycle `events` or its
3
+ * `tokens`. Declared apart from the feed so a session can validate the choice without importing it.
4
+ *
5
+ * @module server/event-selector
6
+ */
7
+ export {};
@@ -0,0 +1,84 @@
1
+ /**
2
+ * `FaultCode` is the stable, machine-readable discriminant that the server's
3
+ * operation pipeline attaches to every fault. Transport adapters serialize it
4
+ * onto the wire so clients can branch on the failure programmatically rather
5
+ * than string-matching a human message:
6
+ *
7
+ * - REST operation routes: the HTTP status derived from this code, plus a
8
+ * `{ error, weftCode?, data?, retryable, remediation? }` body. The body
9
+ * never carries the `FaultCode` itself: its optional `weftCode` is the
10
+ * fine-grained `WeftErrorCode` of the originating error class (see
11
+ * `shapeRestFaultAsJson` in `operation-fault.ts`). `EngineFailure` is
12
+ * masked to exactly `{ "error": "Internal server error", "retryable": false }`.
13
+ * - JSON-RPC: `error.data.weftCode` is this coarse `FaultCode`, alongside
14
+ * `error.data.httpStatus` (see `fault-to-json-rpc.ts`). The fine-grained
15
+ * `WeftErrorCode` is not carried on this transport.
16
+ * - Both transports, and an MCP tool error's `structuredContent`, carry
17
+ * `retryable` (always, from {@link FAULT_CODE_RETRYABLE}) and
18
+ * `remediation` (when the fault sets one).
19
+ *
20
+ * The same key therefore names different vocabularies per transport; see
21
+ * `documentation/reference/api-errors.md#wire-envelopes`.
22
+ *
23
+ * The type lives in its own file because the server (which produces faults)
24
+ * and the client (which consumes them off the wire) both need it, and it
25
+ * imports nothing, so it stays with the transport-neutral operation layer.
26
+ * `core/fault-code.ts` keeps `FAULT_CODE_TO_FAILURE_CATEGORY`, the mapping onto
27
+ * Weft's execution taxonomy.
28
+ */
29
+ /**
30
+ * Every stable fault code name, in declaration order. The full vocabulary is
31
+ * closed for v1; new codes can be added additively, and the maps keyed by
32
+ * {@link FaultCode} force every new code to be handled at compile time.
33
+ */
34
+ export declare const FAULT_CODES: readonly ["Unauthorized", "Forbidden", "NotFound", "Conflict", "Unprocessable", "Timeout", "PayloadTooLarge", "NotImplemented", "UnsupportedTransport", "SubscriptionOverflow", "InvalidParams", "MethodNotFound", "StaleRevision", "RateLimited", "Unavailable", "UnsupportedCapability", "EngineFailure"];
35
+ /**
36
+ * Stable fault code names. The full vocabulary is closed for v1; new codes can
37
+ * be added additively, and the `satisfies` map in `core/fault-code.ts` forces
38
+ * every new code to declare its failure category at compile time.
39
+ *
40
+ * See `documentation/reference/api-errors.md#faultcode` for the HTTP status,
41
+ * JSON-RPC error code, and failure category of every fault code.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import { type FaultCode } from '@lostgradient/backchannel';
46
+ * import { HttpClientError } from '@lostgradient/weft';
47
+ *
48
+ * function describe(error: HttpClientError): string {
49
+ * const code: FaultCode | undefined = error.faultCode;
50
+ * return code === 'NotFound' ? 'missing resource' : (code ?? 'unknown');
51
+ * }
52
+ * void describe;
53
+ * ```
54
+ */
55
+ export type FaultCode = (typeof FAULT_CODES)[number];
56
+ /**
57
+ * Whether the caller can expect the identical call to succeed if it simply tries again later.
58
+ * Every fault puts this on the wire as `retryable`: in the REST body, in the JSON-RPC
59
+ * `error.data`, and in an MCP tool error's `structuredContent`.
60
+ *
61
+ * The rule: a code is `true` only when the same call, repeated unchanged after a wait, can
62
+ * succeed with no change by the caller. A fault that needs fresh state (re-read the resource, take
63
+ * a new revision) or different input, credentials or capabilities is `false`; its `remediation`
64
+ * says what to change. `retryable` belongs to the code, not to the call site, so this table owns
65
+ * it. A code that covers both a transient and a permanent case is `false`.
66
+ *
67
+ * A new {@link FaultCode} cannot compile until it has a value here, and `fault-code.test.ts`
68
+ * fails when the table and {@link FAULT_CODES} disagree.
69
+ */
70
+ export declare const FAULT_CODE_RETRYABLE: Readonly<Record<FaultCode, boolean>>;
71
+ /** Whether `code`'s fault tells the caller that repeating the identical call later can succeed. */
72
+ export declare function isFaultRetryable(code: FaultCode): boolean;
73
+ /**
74
+ * Type guard: narrows an unknown wire value to a known {@link FaultCode}.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { isFaultCode } from '@lostgradient/backchannel';
79
+ *
80
+ * isFaultCode('NotFound'); // true
81
+ * isFaultCode('teapot'); // false
82
+ * ```
83
+ */
84
+ export declare function isFaultCode(value: unknown): value is FaultCode;