@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,136 @@
1
+ import { faultToJsonRpcError } from "../fault-to-json-rpc.js";
2
+ import { isPlainObject } from "../json-schema-utilities.js";
3
+ import { executeOperation, executeSubscription, } from "../operation-catalog.js";
4
+ import { CatalogClientError } from "./catalog-client.js";
5
+ /** Dispatch unary calls in the current process, using the same fault envelope as JSON-RPC. */
6
+ export function inProcessCatalogTransport(options) {
7
+ const { host, principal, registry } = options;
8
+ const restOperationNames = new Set(options.restOperationNames);
9
+ return async (operationName, input, callOptions) => {
10
+ const signal = callOptions?.signal;
11
+ signal?.throwIfAborted();
12
+ const result = await executeOperation(operationName, input, {
13
+ principal,
14
+ host,
15
+ registry,
16
+ transport: restOperationNames.has(operationName) ? 'http-rest' : 'jsonRpcHttp',
17
+ ...(signal === undefined ? {} : { signal }),
18
+ });
19
+ signal?.throwIfAborted();
20
+ if (!result.ok)
21
+ throw new CatalogClientError(operationName, faultToJsonRpcError(result.fault));
22
+ return result.value;
23
+ };
24
+ }
25
+ /** Follow a catalog subscription in-process with the same cursor convention as SSE. */
26
+ export function inProcessSubscriptionTransport(options) {
27
+ const { host, principal, registry } = options;
28
+ return async function* (operationName, input, callOptions) {
29
+ const signal = callOptions?.signal;
30
+ if (isAborted(signal))
31
+ return;
32
+ const result = await executeSubscription(operationName, resumeInput(input, callOptions?.lastEventId), {
33
+ host,
34
+ principal,
35
+ registry,
36
+ transport: 'http-rest',
37
+ ...(signal === undefined ? {} : { signal }),
38
+ });
39
+ if (!result.ok) {
40
+ if (!isAborted(signal)) {
41
+ throw new CatalogClientError(operationName, faultToJsonRpcError(result.fault));
42
+ }
43
+ return;
44
+ }
45
+ yield* readSubscription(operationName, result.value, signal);
46
+ };
47
+ }
48
+ function resumeInput(input, cursor) {
49
+ return cursor && isPlainObject(input) ? { ...input, fromCursor: cursor } : input;
50
+ }
51
+ function isAborted(signal) {
52
+ return signal?.aborted ?? false;
53
+ }
54
+ async function* readSubscription(operationName, { iterable, replayComplete, close }, signal) {
55
+ const iterator = iterable[Symbol.asyncIterator]();
56
+ let closing;
57
+ const closeOnce = () => (closing ??= Promise.resolve()
58
+ .then(close)
59
+ .catch(() => { }));
60
+ const abort = () => {
61
+ void closeOnce();
62
+ };
63
+ signal?.addEventListener('abort', abort, { once: true });
64
+ try {
65
+ const read = subscriptionReader(iterator, replayComplete);
66
+ while (!isAborted(signal)) {
67
+ const item = await read();
68
+ if (isAborted(signal))
69
+ return;
70
+ if (item.kind === 'ready')
71
+ yield { type: 'replay-complete' };
72
+ else if (item.result.done)
73
+ return;
74
+ else
75
+ yield eventMessage(operationName, item.result.value);
76
+ }
77
+ }
78
+ catch (error) {
79
+ if (!isAborted(signal))
80
+ throw error;
81
+ }
82
+ finally {
83
+ signal?.removeEventListener('abort', abort);
84
+ await closeOnce();
85
+ await returnIterator(iterator);
86
+ }
87
+ }
88
+ async function returnIterator(iterator) {
89
+ try {
90
+ await iterator.return?.();
91
+ }
92
+ catch {
93
+ // The feed has been closed. A cleanup failure cannot replace the original read outcome.
94
+ }
95
+ }
96
+ function subscriptionReader(iterator, replayComplete) {
97
+ let replayReady = false;
98
+ let notifyReady;
99
+ let pending;
100
+ void replayComplete?.then(() => {
101
+ replayReady = true;
102
+ notifyReady?.();
103
+ return undefined;
104
+ }, () => undefined);
105
+ return async () => {
106
+ if (replayReady) {
107
+ replayReady = false;
108
+ return { kind: 'ready' };
109
+ }
110
+ const next = (pending ??= iterator.next().then((result) => ({ kind: 'event', result })));
111
+ const ready = new Promise((resolve) => {
112
+ notifyReady = () => resolve({ kind: 'ready' });
113
+ });
114
+ try {
115
+ const item = await Promise.race([next, ready]);
116
+ if (item.kind === 'ready')
117
+ replayReady = false;
118
+ else
119
+ pending = undefined;
120
+ return item;
121
+ }
122
+ finally {
123
+ notifyReady = undefined;
124
+ }
125
+ };
126
+ }
127
+ function eventMessage(operationName, data) {
128
+ if (isPlainObject(data) && typeof data['cursor'] === 'string') {
129
+ return { type: 'event', id: data['cursor'], data };
130
+ }
131
+ throw new CatalogClientError(operationName, faultToJsonRpcError({
132
+ code: 'EngineFailure',
133
+ message: 'internal error',
134
+ data: {},
135
+ }));
136
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The browser-safe client entry: the catalog client factory, its transport seam and error, the
3
+ * JSON-RPC HTTP transport, the subscription client and its Server-Sent Events transport, and the
4
+ * chunk parser. It imports no Bun or Node API
5
+ * and the HTTP and SSE transports can also be bundled independently of the in-process dispatcher.
6
+ *
7
+ * @module client
8
+ */
9
+ export { CatalogClientError, createCatalogClient, type CatalogCallOptions, type CatalogClient, type CatalogFetch, type CatalogTransport, type ClientRestOperationBinding, type JsonRpcCallResult, type JsonRpcErrorObject, } from "./catalog-client.js";
10
+ export { inProcessCatalogTransport, inProcessSubscriptionTransport, type InProcessTransportOptions, } from "./in-process-transport.js";
11
+ export { callJsonRpc, httpJsonRpcTransport, jsonRpcHttpEndpoint, type JsonRpcHttpCall, type JsonRpcHttpConnection, } from "./json-rpc-http-transport.js";
12
+ export { parseServerSentEventChunk, type ServerSentEventFrame, type ServerSentEventParseResult, } from "./server-sent-event-parser.js";
13
+ export { sseSubscriptionTransport, subscriptionUrl, type SseSubscriptionConnection, } from "./sse-subscription-transport.js";
14
+ export { createSubscriptionClient, type SubscriptionCallOptions, type SubscriptionClient, type SubscriptionMessage, type SubscriptionTransport, } from "./subscription-client.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The browser-safe client entry: the catalog client factory, its transport seam and error, the
3
+ * JSON-RPC HTTP transport, the subscription client and its Server-Sent Events transport, and the
4
+ * chunk parser. It imports no Bun or Node API
5
+ * and the HTTP and SSE transports can also be bundled independently of the in-process dispatcher.
6
+ *
7
+ * @module client
8
+ */
9
+ export { CatalogClientError, createCatalogClient, } from "./catalog-client.js";
10
+ export { inProcessCatalogTransport, inProcessSubscriptionTransport, } from "./in-process-transport.js";
11
+ export { callJsonRpc, httpJsonRpcTransport, jsonRpcHttpEndpoint, } from "./json-rpc-http-transport.js";
12
+ export { parseServerSentEventChunk, } from "./server-sent-event-parser.js";
13
+ export { sseSubscriptionTransport, subscriptionUrl, } from "./sse-subscription-transport.js";
14
+ export { createSubscriptionClient, } from "./subscription-client.js";
@@ -0,0 +1,118 @@
1
+ import { type CatalogCallOptions, type CatalogFetch, type CatalogTransport, type JsonRpcCallResult } from "./catalog-client.js";
2
+ /**
3
+ * Where a JSON-RPC HTTP transport sends its calls, and what it sends with them.
4
+ *
5
+ * `baseUrl` is the address of the handler's root: an absolute URL
6
+ * (`https://api.example.test`) or a path a browser resolves against its own
7
+ * origin (`/api`). The transport appends `/jsonrpc`, so it never builds a
8
+ * `URL` from the base and a relative one works. `headers` go on every call, such
9
+ * as an `authorization` header; `fetch` is the transport's default and a call's
10
+ * own `fetch` overrides it.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { httpJsonRpcTransport, type JsonRpcHttpConnection } from '@lostgradient/backchannel/client';
15
+ *
16
+ * const connection: JsonRpcHttpConnection = {
17
+ * baseUrl: '/api',
18
+ * headers: { authorization: 'Bearer token' },
19
+ * };
20
+ *
21
+ * const transport = httpJsonRpcTransport(connection);
22
+ * console.log(typeof transport);
23
+ * ```
24
+ */
25
+ export type JsonRpcHttpConnection = {
26
+ /** The handler's root, absolute or a path the browser resolves. */
27
+ readonly baseUrl: string;
28
+ /** Headers sent with every call. */
29
+ readonly headers?: Readonly<Record<string, string>> | undefined;
30
+ /** The `fetch` to use unless a call brings its own. Defaults to the global one. */
31
+ readonly fetch?: CatalogFetch | undefined;
32
+ /** The JSON-RPC request `id` every call carries. By default each call gets a distinct id. */
33
+ readonly requestId?: string | undefined;
34
+ };
35
+ /**
36
+ * The JSON-RPC endpoint of a handler: its base URL with any query or fragment
37
+ * removed, any trailing slash trimmed, and `/jsonrpc` appended.
38
+ *
39
+ * It joins strings, so the base may be absolute or a path the browser resolves.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { jsonRpcHttpEndpoint } from '@lostgradient/backchannel/client';
44
+ *
45
+ * console.log(jsonRpcHttpEndpoint('https://api.example.test/base/')); // https://api.example.test/base/jsonrpc
46
+ * console.log(jsonRpcHttpEndpoint('/api')); // /api/jsonrpc
47
+ * ```
48
+ */
49
+ export declare function jsonRpcHttpEndpoint(baseUrl: string): string;
50
+ /**
51
+ * One JSON-RPC call over HTTP: the `endpoint` to post to, the method and its
52
+ * params, the `id` to send, and the headers, `fetch` and abort `signal` to send
53
+ * them with.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * import type { JsonRpcHttpCall } from '@lostgradient/backchannel/client';
58
+ *
59
+ * const call: JsonRpcHttpCall = {
60
+ * endpoint: 'https://api.example.test/jsonrpc',
61
+ * method: 'probe.echo',
62
+ * params: { message: 'hello' },
63
+ * id: 'example',
64
+ * };
65
+ * console.log(call.method);
66
+ * ```
67
+ */
68
+ export type JsonRpcHttpCall = CatalogCallOptions & {
69
+ /** The full URL to post to. */
70
+ readonly endpoint: string;
71
+ /** The operation name. */
72
+ readonly method: string;
73
+ /** The operation's input. */
74
+ readonly params: unknown;
75
+ /** The JSON-RPC request `id`. */
76
+ readonly id: string;
77
+ /** Headers sent with the call. */
78
+ readonly headers?: Readonly<Record<string, string>> | undefined;
79
+ };
80
+ /**
81
+ * Post one JSON-RPC request and read the envelope: a success carries the
82
+ * operation's result, a JSON-RPC error comes back as `ok: false` rather than a
83
+ * throw. A response that is neither throws, as does a transport failure,
84
+ * including an abort.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * import { callJsonRpc } from '@lostgradient/backchannel/client';
89
+ *
90
+ * const outcome = await callJsonRpc({
91
+ * endpoint: 'https://api.example.test/jsonrpc',
92
+ * method: 'probe.echo',
93
+ * params: { message: 'hello' },
94
+ * id: 'example',
95
+ * });
96
+ * console.log(outcome.ok);
97
+ * ```
98
+ */
99
+ export declare function callJsonRpc(call: JsonRpcHttpCall): Promise<JsonRpcCallResult>;
100
+ /**
101
+ * Transport that dispatches catalog operations as JSON-RPC requests to a
102
+ * handler at `${baseUrl}/jsonrpc`. A JSON-RPC error arrives as a
103
+ * {@link CatalogClientError}.
104
+ *
105
+ * Each call's `signal` and `fetch` reach the request, so a caller can cancel one
106
+ * call or answer it from a fake.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { httpJsonRpcTransport } from '@lostgradient/backchannel/client';
111
+ *
112
+ * const transport = httpJsonRpcTransport({ baseUrl: 'https://api.example.test' });
113
+ *
114
+ * const result = await transport('probe.echo', { message: 'hello' }, { signal: AbortSignal.timeout(5000) });
115
+ * console.log(result);
116
+ * ```
117
+ */
118
+ export declare function httpJsonRpcTransport(connection: JsonRpcHttpConnection): CatalogTransport;
@@ -0,0 +1,127 @@
1
+ import { CatalogClientError, } from "./catalog-client.js";
2
+ const DEFAULT_REQUEST_ID = 'catalog-client';
3
+ let requestSequence = 0n;
4
+ /**
5
+ * The JSON-RPC endpoint of a handler: its base URL with any query or fragment
6
+ * removed, any trailing slash trimmed, and `/jsonrpc` appended.
7
+ *
8
+ * It joins strings, so the base may be absolute or a path the browser resolves.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { jsonRpcHttpEndpoint } from '@lostgradient/backchannel/client';
13
+ *
14
+ * console.log(jsonRpcHttpEndpoint('https://api.example.test/base/')); // https://api.example.test/base/jsonrpc
15
+ * console.log(jsonRpcHttpEndpoint('/api')); // /api/jsonrpc
16
+ * ```
17
+ */
18
+ export function jsonRpcHttpEndpoint(baseUrl) {
19
+ return `${baseUrl.replace(/[?#].*$/u, '').replace(/\/+$/u, '')}/jsonrpc`;
20
+ }
21
+ /**
22
+ * Post one JSON-RPC request and read the envelope: a success carries the
23
+ * operation's result, a JSON-RPC error comes back as `ok: false` rather than a
24
+ * throw. A response that is neither throws, as does a transport failure,
25
+ * including an abort.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { callJsonRpc } from '@lostgradient/backchannel/client';
30
+ *
31
+ * const outcome = await callJsonRpc({
32
+ * endpoint: 'https://api.example.test/jsonrpc',
33
+ * method: 'probe.echo',
34
+ * params: { message: 'hello' },
35
+ * id: 'example',
36
+ * });
37
+ * console.log(outcome.ok);
38
+ * ```
39
+ */
40
+ export async function callJsonRpc(call) {
41
+ const send = call.fetch ?? globalThis.fetch;
42
+ const response = await send(call.endpoint, {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json', ...call.headers },
45
+ body: JSON.stringify({
46
+ jsonrpc: '2.0',
47
+ method: call.method,
48
+ params: call.params,
49
+ id: call.id,
50
+ }),
51
+ ...(call.signal === undefined ? {} : { signal: call.signal }),
52
+ });
53
+ const body = (await response.json());
54
+ if (!matchesResponse(body, call.id))
55
+ throw new Error(`Invalid JSON-RPC response from ${call.endpoint}`);
56
+ if (isJsonRpcError(body) && !('result' in body))
57
+ return { ok: false, error: body.error };
58
+ // A success envelope carries `jsonrpc` and `id`, but `result` is absent when the operation
59
+ // returns void: `JSON.stringify` drops an `undefined` result key on the server.
60
+ if (isJsonRpcSuccess(body)) {
61
+ return { ok: true, result: 'result' in body ? body.result : undefined };
62
+ }
63
+ throw new Error(`Invalid JSON-RPC response from ${call.endpoint}`);
64
+ }
65
+ /**
66
+ * Transport that dispatches catalog operations as JSON-RPC requests to a
67
+ * handler at `${baseUrl}/jsonrpc`. A JSON-RPC error arrives as a
68
+ * {@link CatalogClientError}.
69
+ *
70
+ * Each call's `signal` and `fetch` reach the request, so a caller can cancel one
71
+ * call or answer it from a fake.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { httpJsonRpcTransport } from '@lostgradient/backchannel/client';
76
+ *
77
+ * const transport = httpJsonRpcTransport({ baseUrl: 'https://api.example.test' });
78
+ *
79
+ * const result = await transport('probe.echo', { message: 'hello' }, { signal: AbortSignal.timeout(5000) });
80
+ * console.log(result);
81
+ * ```
82
+ */
83
+ export function httpJsonRpcTransport(connection) {
84
+ const endpoint = jsonRpcHttpEndpoint(connection.baseUrl);
85
+ return async (operationName, input, options) => {
86
+ const fetchOverride = options?.fetch ?? connection.fetch;
87
+ const outcome = await callJsonRpc({
88
+ endpoint,
89
+ method: operationName,
90
+ params: input,
91
+ id: connection.requestId ?? `${DEFAULT_REQUEST_ID}-${++requestSequence}`,
92
+ headers: connection.headers,
93
+ ...(fetchOverride === undefined ? {} : { fetch: fetchOverride }),
94
+ ...(options?.signal === undefined ? {} : { signal: options.signal }),
95
+ });
96
+ if (!outcome.ok)
97
+ throw new CatalogClientError(operationName, outcome.error);
98
+ return outcome.result;
99
+ };
100
+ }
101
+ function matchesResponse(value, id) {
102
+ return (typeof value === 'object' &&
103
+ value !== null &&
104
+ Object.hasOwn(value, 'jsonrpc') &&
105
+ value['jsonrpc'] === '2.0' &&
106
+ Object.hasOwn(value, 'id') &&
107
+ value['id'] === id);
108
+ }
109
+ function isJsonRpcError(value) {
110
+ return (typeof value === 'object' &&
111
+ value !== null &&
112
+ 'error' in value &&
113
+ typeof value.error === 'object' &&
114
+ value.error !== null &&
115
+ 'code' in value.error &&
116
+ typeof value.error.code === 'number' &&
117
+ 'message' in value.error &&
118
+ typeof value.error.message === 'string');
119
+ }
120
+ function isJsonRpcSuccess(value) {
121
+ return (typeof value === 'object' &&
122
+ value !== null &&
123
+ 'jsonrpc' in value &&
124
+ value['jsonrpc'] === '2.0' &&
125
+ 'id' in value &&
126
+ !('error' in value));
127
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * One Server-Sent Events message: its optional `id` and `event` fields and its
3
+ * `data`, with multiple `data` lines joined by a newline.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { ServerSentEventFrame } from '@lostgradient/backchannel/client';
8
+ *
9
+ * const frame: ServerSentEventFrame = { id: '7', event: 'ping', data: '{"replayComplete":true}' };
10
+ * console.log(frame.event);
11
+ * ```
12
+ */
13
+ export type ServerSentEventFrame = {
14
+ /** The `id` field: the cursor to resume after this message. */
15
+ readonly id?: string;
16
+ /** The `event` field; absent for the default `message` event. */
17
+ readonly event?: string;
18
+ /** The `data` field. */
19
+ readonly data: string;
20
+ };
21
+ /**
22
+ * What {@link parseServerSentEventChunk} found in a chunk: the complete frames,
23
+ * and the text of a frame that has not finished, which the next call takes as
24
+ * its `previousRemainder`.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { parseServerSentEventChunk } from '@lostgradient/backchannel/client';
29
+ *
30
+ * const { frames, remainder } = parseServerSentEventChunk('data: one\n\ndata: tw');
31
+ * console.log(frames.length, remainder); // 1 data: tw
32
+ * ```
33
+ */
34
+ export type ServerSentEventParseResult = {
35
+ /** The complete frames, in order. */
36
+ readonly frames: ReadonlyArray<ServerSentEventFrame>;
37
+ /** The unfinished tail, including any trailing CR that could begin a CRLF. */
38
+ readonly remainder: string;
39
+ };
40
+ /**
41
+ * Split a chunk of an event stream into frames. Pass each chunk's `remainder`
42
+ * back as the next call's `previousRemainder`, so a frame that arrives in two
43
+ * chunks is read once, whole. Comments and unknown fields are ignored, and a
44
+ * frame with no field at all is dropped.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { parseServerSentEventChunk } from '@lostgradient/backchannel/client';
49
+ *
50
+ * const first = parseServerSentEventChunk('id: 1\ndata: {"a":');
51
+ * const second = parseServerSentEventChunk('1}\n\n', first.remainder);
52
+ * console.log(second.frames[0]?.data); // {"a":1}
53
+ * ```
54
+ */
55
+ export declare function parseServerSentEventChunk(text: string, previousRemainder?: string): ServerSentEventParseResult;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Split a chunk of an event stream into frames. Pass each chunk's `remainder`
3
+ * back as the next call's `previousRemainder`, so a frame that arrives in two
4
+ * chunks is read once, whole. Comments and unknown fields are ignored, and a
5
+ * frame with no field at all is dropped.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { parseServerSentEventChunk } from '@lostgradient/backchannel/client';
10
+ *
11
+ * const first = parseServerSentEventChunk('id: 1\ndata: {"a":');
12
+ * const second = parseServerSentEventChunk('1}\n\n', first.remainder);
13
+ * console.log(second.frames[0]?.data); // {"a":1}
14
+ * ```
15
+ */
16
+ export function parseServerSentEventChunk(text, previousRemainder = '') {
17
+ const combined = previousRemainder + text;
18
+ const frames = [];
19
+ let frameStart = 0;
20
+ let lineStart = 0;
21
+ for (const ending of combined.matchAll(/\r\n?|\n/gu)) {
22
+ const nextLine = ending.index + ending[0].length;
23
+ if (ending.index === lineStart) {
24
+ const frame = parseServerSentEventFrame(combined.slice(frameStart, lineStart));
25
+ if (frame !== null)
26
+ frames.push(frame);
27
+ frameStart = nextLine;
28
+ }
29
+ lineStart = nextLine;
30
+ }
31
+ // Replay a terminal blank CR as an empty line. Its LF may arrive in the next chunk.
32
+ const remainder = frameStart === combined.length && combined.endsWith('\r') ? '\r' : combined.slice(frameStart);
33
+ return { frames, remainder };
34
+ }
35
+ function parseServerSentEventFrame(block) {
36
+ const parts = {
37
+ id: undefined,
38
+ event: undefined,
39
+ dataLines: [],
40
+ };
41
+ for (const rawLine of block.split(/\r\n?|\n/u)) {
42
+ applyServerSentEventLine(parts, rawLine);
43
+ }
44
+ return frameFromParts(parts);
45
+ }
46
+ function applyServerSentEventLine(parts, rawLine) {
47
+ if (rawLine === '' || rawLine.startsWith(':'))
48
+ return;
49
+ const { field, value } = splitServerSentEventLine(rawLine);
50
+ if (field === 'id') {
51
+ parts.id = value;
52
+ }
53
+ else if (field === 'event') {
54
+ parts.event = value;
55
+ }
56
+ else if (field === 'data') {
57
+ parts.dataLines.push(value);
58
+ }
59
+ }
60
+ function splitServerSentEventLine(rawLine) {
61
+ const separator = rawLine.indexOf(':');
62
+ const field = separator === -1 ? rawLine : rawLine.slice(0, separator);
63
+ const rawValue = separator === -1 ? '' : rawLine.slice(separator + 1);
64
+ return {
65
+ field,
66
+ value: rawValue.startsWith(' ') ? rawValue.slice(1) : rawValue,
67
+ };
68
+ }
69
+ function frameFromParts(parts) {
70
+ if (parts.id === undefined && parts.event === undefined && parts.dataLines.length === 0) {
71
+ return null;
72
+ }
73
+ return {
74
+ ...(parts.id === undefined ? {} : { id: parts.id }),
75
+ ...(parts.event === undefined ? {} : { event: parts.event }),
76
+ data: parts.dataLines.join('\n'),
77
+ };
78
+ }
@@ -0,0 +1,72 @@
1
+ import { type CatalogFetch } from "./catalog-client.js";
2
+ import type { SubscriptionTransport } from "./subscription-client.js";
3
+ /**
4
+ * Where an SSE subscription transport opens its streams, and what it sends with them.
5
+ *
6
+ * `baseUrl` is the address of the handler's root, absolute or a path the browser resolves.
7
+ * `routePrefix` is the path the handler serves subscriptions under, `/v1/subscriptions` unless
8
+ * the catalog is mounted elsewhere; the operation name follows it. `headers` go on every call and
9
+ * `fetch` is the default a call's own `fetch` overrides.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { sseSubscriptionTransport, type SseSubscriptionConnection } from '@lostgradient/backchannel/client';
14
+ *
15
+ * const connection: SseSubscriptionConnection = {
16
+ * baseUrl: '/api',
17
+ * routePrefix: '/v1/subscriptions',
18
+ * headers: { authorization: 'Bearer token' },
19
+ * };
20
+ *
21
+ * console.log(typeof sseSubscriptionTransport(connection));
22
+ * ```
23
+ */
24
+ export type SseSubscriptionConnection = {
25
+ /** The handler's root, absolute or a path the browser resolves. */
26
+ readonly baseUrl: string;
27
+ /** The path subscriptions are served under. Defaults to `/v1/subscriptions`. */
28
+ readonly routePrefix?: string | undefined;
29
+ /** Headers sent with every call. */
30
+ readonly headers?: Readonly<Record<string, string>> | undefined;
31
+ /** The `fetch` to use unless a call brings its own. Defaults to the global one. */
32
+ readonly fetch?: CatalogFetch | undefined;
33
+ };
34
+ /**
35
+ * The URL a subscription is opened at: the base, the route prefix, the encoded operation name,
36
+ * and the input as a query string. A repeated key carries an array, an absent or `undefined`
37
+ * field is left out, and a value that is not a string, number or boolean is sent as JSON.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * import { subscriptionUrl } from '@lostgradient/backchannel/client';
42
+ *
43
+ * console.log(
44
+ * subscriptionUrl({ baseUrl: '/api' }, 'probe.jobs.watch', { topic: 'a', kinds: ['x', 'y'] }),
45
+ * ); // /api/v1/subscriptions/probe.jobs.watch?topic=a&kinds=x&kinds=y
46
+ * ```
47
+ */
48
+ export declare function subscriptionUrl(connection: Pick<SseSubscriptionConnection, 'baseUrl' | 'routePrefix'>, operationName: string, input: unknown): string;
49
+ /**
50
+ * Transport that opens a subscription as a Server-Sent Events stream at
51
+ * `GET ${baseUrl}${routePrefix}/${operationName}`, which is what the operation handler serves.
52
+ *
53
+ * The iteration yields each event with its `id`, then one `replay-complete` marker when the
54
+ * server says the replay is done. `lastEventId` is sent as `Last-Event-ID`, so the stream resumes
55
+ * after that event. Aborting the signal ends the iteration without an error; leaving the loop
56
+ * early closes the connection. A stream that reports an error, a response that is not a success
57
+ * and a response that is not an event stream each throw a {@link CatalogClientError}. One call
58
+ * opens one stream: reconnecting is the caller's.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { sseSubscriptionTransport } from '@lostgradient/backchannel/client';
63
+ *
64
+ * const transport = sseSubscriptionTransport({ baseUrl: 'https://api.example.test' });
65
+ * const controller = new AbortController();
66
+ *
67
+ * for await (const message of transport('probe.jobs.watch', {}, { signal: controller.signal })) {
68
+ * if (message.type === 'event') console.log(message.id, message.data);
69
+ * }
70
+ * ```
71
+ */
72
+ export declare function sseSubscriptionTransport(connection: SseSubscriptionConnection): SubscriptionTransport;