@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,50 @@
1
+ /**
2
+ * Shared newline-delimited framing helper for JSON-RPC over stdio.
3
+ *
4
+ * The runtime stdio subcommand consumes this helper to turn newline-delimited
5
+ * byte chunks into complete JSON-RPC frames. Phase 6 locked in the framing
6
+ * contract against the original inline buffer logic; Phase 7 extracted that
7
+ * logic into this pure function.
8
+ *
9
+ * Contract:
10
+ * - Input: `buffer` (leftover from the previous call) + `chunk` (new
11
+ * bytes decoded to string).
12
+ * - Output: an array of `lines` (complete, newline-terminated, trimmed,
13
+ * non-empty) plus a `buffer` to feed into the next call.
14
+ * - Split: on `\n`. `\r` is treated as surrounding whitespace and
15
+ * trimmed — standard `trim()` behavior. CRLF framing works
16
+ * transparently.
17
+ * - Blanks: lines that are empty after `trim()` are silently dropped.
18
+ * They are framing artifacts, not empty payloads — if every
19
+ * caller had to filter them, eventually one would forget and
20
+ * log a malformed-JSON warning on a legitimately blank frame.
21
+ *
22
+ * Pure: no I/O, no allocations beyond the returned arrays/string, no
23
+ * state. Safe to call from any context.
24
+ *
25
+ * **No built-in buffer bound.** A peer that never emits a newline can
26
+ * force the returned `buffer` to grow unboundedly across calls. The
27
+ * helper is deliberately primitive here — callers that cannot trust
28
+ * the peer (the Phase 13 runtime stdio session; any future network-
29
+ * facing consumer) MUST enforce their own max-frame cap and drop /
30
+ * fault the connection when the buffer exceeds it.
31
+ */
32
+ /**
33
+ * Append `chunk` to `buffer`, split off every complete newline-terminated
34
+ * frame, and return the extracted lines plus the leftover buffer.
35
+ *
36
+ * Lines are trimmed; empty lines (after trim) are dropped silently.
37
+ */
38
+ export function splitNewlineDelimitedBuffer(buffer, chunk) {
39
+ let working = buffer + chunk;
40
+ const lines = [];
41
+ let newlineIndex = working.indexOf('\n');
42
+ while (newlineIndex !== -1) {
43
+ const line = working.slice(0, newlineIndex).trim();
44
+ working = working.slice(newlineIndex + 1);
45
+ if (line.length > 0)
46
+ lines.push(line);
47
+ newlineIndex = working.indexOf('\n');
48
+ }
49
+ return { lines, buffer: working };
50
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * POST `/jsonrpc` HTTP transport adapter.
3
+ *
4
+ * Takes an incoming `Request`, validates the method + content-type +
5
+ * body size, reads the body (bounded), and delegates dispatch to
6
+ * `dispatchJsonRpc`. Maps the dispatcher's `DispatchJsonRpcResult`
7
+ * onto an HTTP `Response` per JSON-RPC 2.0 spec conventions:
8
+ *
9
+ * - single non-notification → HTTP 200 + JSON body
10
+ * - single notification → HTTP 204 No Content
11
+ * - batch with ≥1 response → HTTP 200 + JSON array body
12
+ * - all-notification batch → HTTP 204 No Content
13
+ *
14
+ * Note: body-level errors (parse-error, invalid-request) come back in
15
+ * the JSON-RPC error envelope with `id: null` at HTTP 200 per spec.
16
+ * HTTP 4xx/5xx are reserved for transport-level concerns (wrong
17
+ * method, wrong content-type, body too large, server crash).
18
+ *
19
+ * The pre-read content-length guard rejects oversize bodies before
20
+ * allocating a buffer. The post-read size check is the backstop when
21
+ * the client omits content-length or lies.
22
+ */
23
+ import type { OperationRegistry } from "./operation-catalog.js";
24
+ import type { Principal } from "./principal.js";
25
+ export type JsonRpcHttpContext = {
26
+ readonly registry: OperationRegistry;
27
+ /** See `OperationContext.host`. */
28
+ readonly host: unknown;
29
+ readonly principal: Principal;
30
+ /** Hard cap on request body size. Defaults to 1 MB. */
31
+ readonly maxBodyBytes?: number;
32
+ /** See `DispatchJsonRpcContext.discoverDocument`. */
33
+ readonly discoverDocument?: () => Record<string, unknown>;
34
+ };
35
+ /** Handle a POST `/jsonrpc` request end-to-end. */
36
+ export declare function handleJsonRpcHttpRequest(request: Request, context: JsonRpcHttpContext): Promise<Response>;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * POST `/jsonrpc` HTTP transport adapter.
3
+ *
4
+ * Takes an incoming `Request`, validates the method + content-type +
5
+ * body size, reads the body (bounded), and delegates dispatch to
6
+ * `dispatchJsonRpc`. Maps the dispatcher's `DispatchJsonRpcResult`
7
+ * onto an HTTP `Response` per JSON-RPC 2.0 spec conventions:
8
+ *
9
+ * - single non-notification → HTTP 200 + JSON body
10
+ * - single notification → HTTP 204 No Content
11
+ * - batch with ≥1 response → HTTP 200 + JSON array body
12
+ * - all-notification batch → HTTP 204 No Content
13
+ *
14
+ * Note: body-level errors (parse-error, invalid-request) come back in
15
+ * the JSON-RPC error envelope with `id: null` at HTTP 200 per spec.
16
+ * HTTP 4xx/5xx are reserved for transport-level concerns (wrong
17
+ * method, wrong content-type, body too large, server crash).
18
+ *
19
+ * The pre-read content-length guard rejects oversize bodies before
20
+ * allocating a buffer. The post-read size check is the backstop when
21
+ * the client omits content-length or lies.
22
+ */
23
+ import { dispatchJsonRpc, } from "./json-rpc-dispatch.js";
24
+ /** 1 MB default — large enough for batched JSON-RPC, small enough to bound memory. */
25
+ const DEFAULT_MAX_BODY_BYTES = 1 * 1024 * 1024;
26
+ /**
27
+ * `Cache-Control: no-store` is applied to EVERY response from this
28
+ * adapter — including 4xx transport-level rejections — because any
29
+ * cached `/jsonrpc` response is a correctness hazard. The JSON-RPC
30
+ * contract is strictly request-response, and a cached 413 or 415
31
+ * served to a different client could mask a legitimate request.
32
+ */
33
+ const CACHE_CONTROL_HEADERS = { 'cache-control': 'no-store' };
34
+ function textResponse(body, status, extra) {
35
+ const headers = new Headers(extra);
36
+ headers.set('cache-control', 'no-store');
37
+ return new Response(body, { status, headers });
38
+ }
39
+ /** Handle a POST `/jsonrpc` request end-to-end. */
40
+ export async function handleJsonRpcHttpRequest(request, context) {
41
+ const methodRejection = guardMethod(request);
42
+ if (methodRejection !== null)
43
+ return methodRejection;
44
+ const contentTypeRejection = guardContentType(request);
45
+ if (contentTypeRejection !== null)
46
+ return contentTypeRejection;
47
+ const maxBytes = context.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
48
+ const contentLengthRejection = guardContentLength(request.headers.get('content-length'), maxBytes);
49
+ if (contentLengthRejection !== null)
50
+ return contentLengthRejection;
51
+ // Stream-bounded body read. Pulls chunks and enforces `maxBytes`
52
+ // as the hard ceiling so a lying or missing content-length header
53
+ // cannot force an unbounded allocation.
54
+ let bodyBytes;
55
+ try {
56
+ bodyBytes = await readBodyBounded(request, maxBytes);
57
+ }
58
+ catch (error) {
59
+ if (error instanceof RequestBodyTooLargeError)
60
+ return textResponse('Payload Too Large', 413);
61
+ // Stream error reading the body — treat as transport-level failure.
62
+ return textResponse('Bad Request', 400);
63
+ }
64
+ const bodyText = new TextDecoder('utf-8').decode(bodyBytes);
65
+ const dispatchContext = {
66
+ registry: context.registry,
67
+ host: context.host,
68
+ principal: context.principal,
69
+ transport: 'jsonRpcHttp',
70
+ signal: request.signal,
71
+ ...(context.discoverDocument === undefined
72
+ ? {}
73
+ : { discoverDocument: context.discoverDocument }),
74
+ };
75
+ const result = await dispatchJsonRpc(bodyText, dispatchContext);
76
+ return dispatchResultToResponse(result);
77
+ }
78
+ function guardMethod(request) {
79
+ if (request.method === 'POST')
80
+ return null;
81
+ return textResponse('Method Not Allowed', 405, { allow: 'POST' });
82
+ }
83
+ function guardContentType(request) {
84
+ const contentType = request.headers.get('content-type') ?? '';
85
+ if (isJsonContentType(contentType))
86
+ return null;
87
+ return textResponse('Unsupported Media Type', 415);
88
+ }
89
+ /**
90
+ * Pre-read content-length guard. Validates a canonical non-negative
91
+ * base-10 integer. Invalid/negative/fractional values → 400 (malformed
92
+ * request). A valid-but-oversize declaration → 413 before any body
93
+ * buffer is allocated.
94
+ */
95
+ function guardContentLength(header, maxBytes) {
96
+ if (header === null)
97
+ return null;
98
+ if (!CONTENT_LENGTH_PATTERN.test(header))
99
+ return textResponse('Bad Request', 400);
100
+ const declared = Number(header);
101
+ if (!Number.isSafeInteger(declared) || declared < 0)
102
+ return textResponse('Bad Request', 400);
103
+ if (declared > maxBytes)
104
+ return textResponse('Payload Too Large', 413);
105
+ return null;
106
+ }
107
+ function dispatchResultToResponse(result) {
108
+ switch (result.kind) {
109
+ case 'notification':
110
+ case 'notification-batch':
111
+ return new Response(null, { status: 204, headers: CACHE_CONTROL_HEADERS });
112
+ case 'single':
113
+ return Response.json(result.response, { status: 200, headers: CACHE_CONTROL_HEADERS });
114
+ case 'batch':
115
+ return Response.json(result.responses, { status: 200, headers: CACHE_CONTROL_HEADERS });
116
+ default: {
117
+ const exhaustiveCheck = result;
118
+ throw new Error(`Unknown JSON-RPC dispatch result kind: ${JSON.stringify(exhaustiveCheck)}`);
119
+ }
120
+ }
121
+ }
122
+ /**
123
+ * Canonical base-10 non-negative integer. Rejects empty strings,
124
+ * leading zeros on multi-digit values, signs, decimal points, and
125
+ * scientific notation.
126
+ */
127
+ const CONTENT_LENGTH_PATTERN = /^(0|[1-9]\d*)$/;
128
+ /**
129
+ * Accepts `application/json` and `application/json; charset=...`
130
+ * (case-insensitive on the type). Subtypes / vendor-tagged types
131
+ * (`application/vnd.weft+json`) are NOT accepted — callers must use
132
+ * the canonical JSON content type so the OpenRPC / OpenAPI documentation
133
+ * remain consistent.
134
+ */
135
+ function isJsonContentType(contentType) {
136
+ const lowered = contentType.trim().toLowerCase();
137
+ const [type = ''] = lowered.split(';');
138
+ return type.trim() === 'application/json';
139
+ }
140
+ class RequestBodyTooLargeError extends Error {
141
+ /** Stable machine-readable discriminant; equals the class name, as a `WeftError`'s does. */
142
+ code = 'RequestBodyTooLargeError';
143
+ constructor() {
144
+ super('body exceeds max bytes');
145
+ this.name = this.code;
146
+ }
147
+ }
148
+ /**
149
+ * Read the request body in chunks and enforce `maxBytes + 1` as a
150
+ * hard ceiling BEFORE the full body is buffered. This prevents a
151
+ * lying / missing `content-length` header from forcing an unbounded
152
+ * allocation via `request.text()`.
153
+ *
154
+ * Returns the concatenated bytes; caller decodes with `TextDecoder`.
155
+ * Throws `RequestBodyTooLargeError` on overflow — caller maps to 413.
156
+ */
157
+ async function readBodyBounded(request, maxBytes) {
158
+ const body = request.body;
159
+ if (body === null)
160
+ return new Uint8Array(0);
161
+ const reader = body.getReader();
162
+ const chunks = [];
163
+ let total = 0;
164
+ try {
165
+ while (true) {
166
+ const { done, value } = await reader.read();
167
+ if (done)
168
+ break;
169
+ if (!value)
170
+ continue;
171
+ total += value.byteLength;
172
+ if (total > maxBytes) {
173
+ // Abort the stream as soon as we exceed the limit.
174
+ await reader.cancel();
175
+ throw new RequestBodyTooLargeError();
176
+ }
177
+ chunks.push(value);
178
+ }
179
+ }
180
+ finally {
181
+ reader.releaseLock();
182
+ }
183
+ // Concatenate.
184
+ const out = new Uint8Array(total);
185
+ let offset = 0;
186
+ for (const chunk of chunks) {
187
+ out.set(chunk, offset);
188
+ offset += chunk.byteLength;
189
+ }
190
+ return out;
191
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * JSON-RPC 2.0 request parser — accepts a raw body (string or already-
3
+ * parsed JSON) and returns a discriminated-union `ParseResult` that
4
+ * describes what the transport should dispatch.
5
+ *
6
+ * The stable JSON-RPC operation-catalog contract enforces:
7
+ * - `params` MUST be absent or a JSON object. Array-form positional
8
+ * params are rejected with `InvalidRequest` (-32600). This matches
9
+ * OpenRPC's `paramStructure: "by-name"` contract and eliminates a
10
+ * whole class of drift between REST (which has no positional form)
11
+ * and JSON-RPC.
12
+ * - `jsonrpc` MUST be the literal string `"2.0"`. No auto-upgrade
13
+ * from 1.0 or 1.1.
14
+ * - `method` MUST be a non-empty string. The name regex
15
+ * (`validateOperationName` in `operation-catalog.ts`) is NOT
16
+ * enforced here — the dispatcher treats an unknown name as
17
+ * `MethodNotFound`, which is the spec's intended semantics.
18
+ * - Notifications are requests with no `id` key. Explicit `id: null`
19
+ * is a real request (not a notification) per spec — the parser
20
+ * surfaces this via `isNotification: false`.
21
+ *
22
+ * The result is transport-neutral: HTTP POST, WebSocket frames, and
23
+ * stdio sessions all consume the same `ParseResult`.
24
+ */
25
+ import { JSON_RPC_ERROR_CODES, type JsonRpcId, type JsonRpcRequest } from "./json-rpc-protocol.js";
26
+ /**
27
+ * A request body that has been parsed successfully. Either a single
28
+ * request, a batch of per-item parse results, or a body-level error.
29
+ */
30
+ export type ParseResult = {
31
+ readonly kind: 'parse-error';
32
+ readonly code: typeof JSON_RPC_ERROR_CODES.PARSE_ERROR;
33
+ readonly message: string;
34
+ } | {
35
+ readonly kind: 'invalid-request';
36
+ readonly code: typeof JSON_RPC_ERROR_CODES.INVALID_REQUEST;
37
+ readonly message: string;
38
+ readonly id: JsonRpcId;
39
+ } | {
40
+ readonly kind: 'single';
41
+ readonly request: JsonRpcRequest;
42
+ readonly isNotification: boolean;
43
+ } | {
44
+ readonly kind: 'batch';
45
+ readonly items: ReadonlyArray<ParsedBatchItem>;
46
+ };
47
+ export type ParsedBatchItem = {
48
+ readonly kind: 'valid';
49
+ readonly request: JsonRpcRequest;
50
+ readonly isNotification: boolean;
51
+ } | {
52
+ readonly kind: 'invalid';
53
+ readonly code: typeof JSON_RPC_ERROR_CODES.INVALID_REQUEST;
54
+ readonly message: string;
55
+ readonly id: JsonRpcId;
56
+ };
57
+ /**
58
+ * Parse a raw body into a transport-neutral `ParseResult`. Accepts
59
+ * either a string (will be JSON.parse'd) or an already-parsed value.
60
+ */
61
+ /**
62
+ * Hard upper bound on batch size. A well-behaved client will stay well
63
+ * below this; the limit exists to make a hostile client's first attempt
64
+ * at memory/CPU exhaustion cheap to fail. Transport adapters (Phase 11
65
+ * HTTP, Phase 12 WebSocket, Phase 13 stdio) SHOULD enforce their own
66
+ * body/frame byte limits in addition to this item cap.
67
+ */
68
+ export declare const MAX_JSON_RPC_BATCH_ITEMS = 100;
69
+ export declare function parseJsonRpcRequest(body: unknown): ParseResult;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * JSON-RPC 2.0 request parser — accepts a raw body (string or already-
3
+ * parsed JSON) and returns a discriminated-union `ParseResult` that
4
+ * describes what the transport should dispatch.
5
+ *
6
+ * The stable JSON-RPC operation-catalog contract enforces:
7
+ * - `params` MUST be absent or a JSON object. Array-form positional
8
+ * params are rejected with `InvalidRequest` (-32600). This matches
9
+ * OpenRPC's `paramStructure: "by-name"` contract and eliminates a
10
+ * whole class of drift between REST (which has no positional form)
11
+ * and JSON-RPC.
12
+ * - `jsonrpc` MUST be the literal string `"2.0"`. No auto-upgrade
13
+ * from 1.0 or 1.1.
14
+ * - `method` MUST be a non-empty string. The name regex
15
+ * (`validateOperationName` in `operation-catalog.ts`) is NOT
16
+ * enforced here — the dispatcher treats an unknown name as
17
+ * `MethodNotFound`, which is the spec's intended semantics.
18
+ * - Notifications are requests with no `id` key. Explicit `id: null`
19
+ * is a real request (not a notification) per spec — the parser
20
+ * surfaces this via `isNotification: false`.
21
+ *
22
+ * The result is transport-neutral: HTTP POST, WebSocket frames, and
23
+ * stdio sessions all consume the same `ParseResult`.
24
+ */
25
+ import { JSON_RPC_ERROR_CODES, JSON_RPC_VERSION, isValidJsonRpcId, } from "./json-rpc-protocol.js";
26
+ import { isPlainObject } from "./json-schema-utilities.js";
27
+ /**
28
+ * Parse a raw body into a transport-neutral `ParseResult`. Accepts
29
+ * either a string (will be JSON.parse'd) or an already-parsed value.
30
+ */
31
+ /**
32
+ * Hard upper bound on batch size. A well-behaved client will stay well
33
+ * below this; the limit exists to make a hostile client's first attempt
34
+ * at memory/CPU exhaustion cheap to fail. Transport adapters (Phase 11
35
+ * HTTP, Phase 12 WebSocket, Phase 13 stdio) SHOULD enforce their own
36
+ * body/frame byte limits in addition to this item cap.
37
+ */
38
+ export const MAX_JSON_RPC_BATCH_ITEMS = 100;
39
+ export function parseJsonRpcRequest(body) {
40
+ let parsed;
41
+ if (typeof body === 'string') {
42
+ try {
43
+ parsed = JSON.parse(body);
44
+ }
45
+ catch {
46
+ return {
47
+ kind: 'parse-error',
48
+ code: JSON_RPC_ERROR_CODES.PARSE_ERROR,
49
+ message: 'Parse error',
50
+ };
51
+ }
52
+ }
53
+ else {
54
+ parsed = body;
55
+ }
56
+ if (Array.isArray(parsed)) {
57
+ if (parsed.length === 0) {
58
+ return {
59
+ kind: 'invalid-request',
60
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
61
+ message: 'Invalid Request',
62
+ id: null,
63
+ };
64
+ }
65
+ if (parsed.length > MAX_JSON_RPC_BATCH_ITEMS) {
66
+ return {
67
+ kind: 'invalid-request',
68
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
69
+ message: `Invalid Request: batch size ${parsed.length} exceeds limit ${MAX_JSON_RPC_BATCH_ITEMS}`,
70
+ id: null,
71
+ };
72
+ }
73
+ return {
74
+ kind: 'batch',
75
+ items: parsed.map(parseBatchItem),
76
+ };
77
+ }
78
+ if (!isPlainObject(parsed)) {
79
+ return {
80
+ kind: 'invalid-request',
81
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
82
+ message: 'Request must be a JSON object or batch array',
83
+ id: null,
84
+ };
85
+ }
86
+ return parseSingleObject(parsed);
87
+ }
88
+ function parseBatchItem(item) {
89
+ if (!isPlainObject(item)) {
90
+ return {
91
+ kind: 'invalid',
92
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
93
+ message: 'Batch item must be a JSON object',
94
+ id: null,
95
+ };
96
+ }
97
+ const result = parseSingleObject(item);
98
+ if (result.kind === 'single') {
99
+ return { kind: 'valid', request: result.request, isNotification: result.isNotification };
100
+ }
101
+ return {
102
+ kind: 'invalid',
103
+ code: result.code,
104
+ message: result.message,
105
+ id: result.id,
106
+ };
107
+ }
108
+ function parseSingleObject(object) {
109
+ // Grab the raw id early so we can echo it in any error response.
110
+ // The spec requires `id: null` when the incoming id was invalid, so
111
+ // we only echo the id if it's actually valid.
112
+ const rawId = object['id'];
113
+ const hasIdKey = 'id' in object;
114
+ const idForError = isValidJsonRpcId(rawId) ? rawId : null;
115
+ const versionRejection = checkJsonRpcVersion(object, idForError);
116
+ if (versionRejection !== null)
117
+ return versionRejection;
118
+ const method = object['method'];
119
+ const methodRejection = checkMethodField(method, idForError);
120
+ if (methodRejection !== null)
121
+ return methodRejection;
122
+ const paramsRejection = checkParamsField(object, idForError);
123
+ if (paramsRejection !== null)
124
+ return paramsRejection;
125
+ const idRejection = checkIdField(rawId, hasIdKey);
126
+ if (idRejection !== null)
127
+ return idRejection;
128
+ // Notifications omit the `id` key entirely. `id: null` is a real
129
+ // request per the JSON-RPC 2.0 spec.
130
+ const isNotification = !hasIdKey;
131
+ // `params` is narrowed to a plain object by `checkParamsField`; we
132
+ // re-read here only for the success path (the validator already
133
+ // guarantees the shape).
134
+ const params = 'params' in object ? object['params'] : undefined;
135
+ const request = {
136
+ jsonrpc: JSON_RPC_VERSION,
137
+ method: method,
138
+ ...(params === undefined ? {} : { params }),
139
+ ...(hasIdKey ? { id: rawId } : {}),
140
+ };
141
+ return { kind: 'single', request, isNotification };
142
+ }
143
+ function checkJsonRpcVersion(object, idForError) {
144
+ if (object['jsonrpc'] === JSON_RPC_VERSION)
145
+ return null;
146
+ return {
147
+ kind: 'invalid-request',
148
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
149
+ message: `jsonrpc field must be exactly "${JSON_RPC_VERSION}"`,
150
+ id: idForError,
151
+ };
152
+ }
153
+ function checkMethodField(method, idForError) {
154
+ if (typeof method === 'string' && method.length > 0)
155
+ return null;
156
+ return {
157
+ kind: 'invalid-request',
158
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
159
+ message: 'method field must be a non-empty string',
160
+ id: idForError,
161
+ };
162
+ }
163
+ /**
164
+ * Validate the `params` field. Returns `null` when absent or a plain object
165
+ * (the two accepted shapes); returns an `invalid-request` rejection
166
+ * otherwise.
167
+ *
168
+ * `params` is passed through verbatim on success. Prototype-pollution keys
169
+ * (`__proto__` / `constructor` / `prototype`) are NOT stripped here — the
170
+ * authoritative defense is `executeOperation`'s `UNSAFE_PROTOTYPE_KEYS`
171
+ * filter plus the registry-time rejection of schema-declared unsafe keys.
172
+ * Sanitizing at the parse layer would duplicate that policy and force the
173
+ * transport-neutral parser to know about operation-catalog internals.
174
+ */
175
+ function checkParamsField(object, idForError) {
176
+ if (!('params' in object))
177
+ return null;
178
+ const rawParams = object['params'];
179
+ if (Array.isArray(rawParams)) {
180
+ return {
181
+ kind: 'invalid-request',
182
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
183
+ message: 'positional params are not supported; use named params (params must be a JSON object)',
184
+ id: idForError,
185
+ };
186
+ }
187
+ if (!isPlainObject(rawParams)) {
188
+ return {
189
+ kind: 'invalid-request',
190
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
191
+ message: 'params must be a JSON object (named params) or absent',
192
+ id: idForError,
193
+ };
194
+ }
195
+ return null;
196
+ }
197
+ function checkIdField(rawId, hasIdKey) {
198
+ if (!hasIdKey || isValidJsonRpcId(rawId))
199
+ return null;
200
+ return {
201
+ kind: 'invalid-request',
202
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
203
+ message: 'id must be a string, finite number, or null',
204
+ id: null,
205
+ };
206
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * JSON-RPC 2.0 protocol constants and shared types.
3
+ *
4
+ * Single source of truth for the wire-level representation every
5
+ * JSON-RPC transport in this codebase consumes:
6
+ * - Parse helpers (`json-rpc-parse.ts`, Phase 8)
7
+ * - Dispatcher (`json-rpc-dispatch.ts`, Phase 8)
8
+ * - HTTP adapter (`json-rpc-http.ts`, Phase 11)
9
+ * - WebSocket adapter (`json-rpc-websocket.ts`, Phase 12)
10
+ * - Runtime stdio session (`stdio-session.ts`, Phase 13)
11
+ *
12
+ * Reserved-spec error codes (-32700..-32603) keep their JSON-RPC 2.0
13
+ * meanings. Weft domain codes live in the -32010..-32099 band; this stable
14
+ * error-code allocation preserves compatibility across JSON-RPC transports.
15
+ */
16
+ /** Literal `"2.0"` — the only `jsonrpc` version this runtime accepts. */
17
+ export declare const JSON_RPC_VERSION: "2.0";
18
+ export type JsonRpcVersion = typeof JSON_RPC_VERSION;
19
+ /**
20
+ * Error codes carried on the wire in `JsonRpcError.code`.
21
+ *
22
+ * Reserved band (-32700..-32603) — JSON-RPC 2.0 spec.
23
+ * Weft domain band (-32010..-32099) — see `OperationFault` +
24
+ * `fault-to-json-rpc.ts` for the mapping to `FaultCode`.
25
+ */
26
+ export declare const JSON_RPC_ERROR_CODES: Readonly<{
27
+ readonly PARSE_ERROR: -32700;
28
+ readonly INVALID_REQUEST: -32600;
29
+ readonly METHOD_NOT_FOUND: -32601;
30
+ readonly INVALID_PARAMS: -32602;
31
+ readonly INTERNAL_ERROR: -32603;
32
+ readonly UNAUTHORIZED: -32010;
33
+ readonly FORBIDDEN: -32011;
34
+ readonly NOT_FOUND: -32020;
35
+ readonly CONFLICT: -32021;
36
+ readonly UNPROCESSABLE: -32022;
37
+ readonly TIMEOUT: -32023;
38
+ readonly RATE_LIMITED: -32024;
39
+ readonly NOT_IMPLEMENTED: -32025;
40
+ readonly UNSUPPORTED_TRANSPORT: -32030;
41
+ readonly SUBSCRIPTION_OVERFLOW: -32031;
42
+ readonly ENGINE_FAILURE: -32099;
43
+ }>;
44
+ export type JsonRpcErrorCode = (typeof JSON_RPC_ERROR_CODES)[keyof typeof JSON_RPC_ERROR_CODES];
45
+ /**
46
+ * A JSON-RPC request id. The spec allows string, number, or null.
47
+ * `null` is only valid when returned in error responses for requests
48
+ * whose id could not be parsed.
49
+ */
50
+ export type JsonRpcId = string | number | null;
51
+ /** Total runtime guard for `JsonRpcId`. Rejects NaN, Infinity, booleans, objects. */
52
+ export declare function isValidJsonRpcId(value: unknown): value is JsonRpcId;
53
+ /** Raw JSON-RPC request shape (pre-parse, as it arrives on the wire). */
54
+ export type JsonRpcRequest = {
55
+ readonly jsonrpc: JsonRpcVersion;
56
+ readonly method: string;
57
+ readonly params?: Record<string, unknown> | undefined;
58
+ readonly id?: JsonRpcId | undefined;
59
+ };
60
+ /** JSON-RPC success response. */
61
+ export type JsonRpcSuccessResponse = {
62
+ readonly jsonrpc: JsonRpcVersion;
63
+ readonly result: unknown;
64
+ readonly id: JsonRpcId;
65
+ };
66
+ /** JSON-RPC error response. */
67
+ export type JsonRpcErrorResponse = {
68
+ readonly jsonrpc: JsonRpcVersion;
69
+ readonly error: {
70
+ readonly code: number;
71
+ readonly message: string;
72
+ readonly data?: unknown;
73
+ };
74
+ readonly id: JsonRpcId;
75
+ };
76
+ export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * JSON-RPC 2.0 protocol constants and shared types.
3
+ *
4
+ * Single source of truth for the wire-level representation every
5
+ * JSON-RPC transport in this codebase consumes:
6
+ * - Parse helpers (`json-rpc-parse.ts`, Phase 8)
7
+ * - Dispatcher (`json-rpc-dispatch.ts`, Phase 8)
8
+ * - HTTP adapter (`json-rpc-http.ts`, Phase 11)
9
+ * - WebSocket adapter (`json-rpc-websocket.ts`, Phase 12)
10
+ * - Runtime stdio session (`stdio-session.ts`, Phase 13)
11
+ *
12
+ * Reserved-spec error codes (-32700..-32603) keep their JSON-RPC 2.0
13
+ * meanings. Weft domain codes live in the -32010..-32099 band; this stable
14
+ * error-code allocation preserves compatibility across JSON-RPC transports.
15
+ */
16
+ /** Literal `"2.0"` — the only `jsonrpc` version this runtime accepts. */
17
+ export const JSON_RPC_VERSION = '2.0';
18
+ /**
19
+ * Error codes carried on the wire in `JsonRpcError.code`.
20
+ *
21
+ * Reserved band (-32700..-32603) — JSON-RPC 2.0 spec.
22
+ * Weft domain band (-32010..-32099) — see `OperationFault` +
23
+ * `fault-to-json-rpc.ts` for the mapping to `FaultCode`.
24
+ */
25
+ export const JSON_RPC_ERROR_CODES = Object.freeze({
26
+ // Spec-reserved.
27
+ PARSE_ERROR: -32700,
28
+ INVALID_REQUEST: -32600,
29
+ METHOD_NOT_FOUND: -32601,
30
+ INVALID_PARAMS: -32602,
31
+ INTERNAL_ERROR: -32603,
32
+ // Weft domain.
33
+ UNAUTHORIZED: -32010,
34
+ FORBIDDEN: -32011,
35
+ NOT_FOUND: -32020,
36
+ CONFLICT: -32021,
37
+ UNPROCESSABLE: -32022,
38
+ TIMEOUT: -32023,
39
+ RATE_LIMITED: -32024,
40
+ NOT_IMPLEMENTED: -32025,
41
+ UNSUPPORTED_TRANSPORT: -32030,
42
+ SUBSCRIPTION_OVERFLOW: -32031,
43
+ ENGINE_FAILURE: -32099,
44
+ });
45
+ /** Total runtime guard for `JsonRpcId`. Rejects NaN, Infinity, booleans, objects. */
46
+ export function isValidJsonRpcId(value) {
47
+ if (value === null)
48
+ return true;
49
+ if (typeof value === 'string')
50
+ return true;
51
+ if (typeof value === 'number' && Number.isFinite(value))
52
+ return true;
53
+ return false;
54
+ }