@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,104 @@
1
+ /** Select metadata explicitly, so registry entries never expose authoring callbacks. */
2
+ export function snapshotOperationMetadata(operation) {
3
+ return Object.freeze({
4
+ name: operation.name,
5
+ mcpExposable: operation.mcpExposable,
6
+ summary: operation.summary,
7
+ destructive: operation.destructive,
8
+ inputSchema: operation.inputSchema,
9
+ outputSchema: operation.outputSchema,
10
+ tags: frozenArray(operation.tags),
11
+ access: freezeAccessPolicy(operation.access),
12
+ transports: frozenRecord(operation.transports),
13
+ unknownKeyPolicy: frozenRecord(operation.unknownKeyPolicy),
14
+ ...optionalMetadata(operation),
15
+ });
16
+ }
17
+ function optionalMetadata(operation) {
18
+ return {
19
+ ...(operation.description === undefined ? {} : { description: operation.description }),
20
+ ...(operation.behavior === undefined ? {} : { behavior: freezeBehavior(operation.behavior) }),
21
+ ...(operation.conflictReasonTokens === undefined
22
+ ? {}
23
+ : { conflictReasonTokens: frozenArray(operation.conflictReasonTokens) }),
24
+ ...(operation.discoverable === undefined ? {} : { discoverable: operation.discoverable }),
25
+ ...(operation.supportsDryRun === true ? { supportsDryRun: true } : {}),
26
+ ...(operation.mcpTool === undefined ? {} : { mcpTool: frozenRecord(operation.mcpTool) }),
27
+ ...(operation.producibleFaults === undefined
28
+ ? {}
29
+ : { producibleFaults: frozenArray(operation.producibleFaults) }),
30
+ ...(operation.parameterizedAccess === undefined
31
+ ? {}
32
+ : { parameterizedAccess: freezeParameterizedAccess(operation.parameterizedAccess) }),
33
+ };
34
+ }
35
+ function freezeBehavior(behavior) {
36
+ return deepFreeze(structuredClone(behavior));
37
+ }
38
+ function deepFreeze(value) {
39
+ if (value !== null && typeof value === 'object') {
40
+ for (const child of Object.values(value))
41
+ deepFreeze(child);
42
+ Object.freeze(value);
43
+ }
44
+ return value;
45
+ }
46
+ function frozenArray(values) {
47
+ return Object.isFrozen(values) ? values : Object.freeze([...values]);
48
+ }
49
+ function frozenRecord(value) {
50
+ return Object.isFrozen(value) ? value : Object.freeze({ ...value });
51
+ }
52
+ function freezeAccessPolicy(policy) {
53
+ if (policy.kind === 'scoped') {
54
+ const scopes = freezeScopeRequirement(policy.scopes);
55
+ return Object.isFrozen(policy) && scopes === policy.scopes
56
+ ? policy
57
+ : Object.freeze({ kind: policy.kind, scopes });
58
+ }
59
+ if (policy.kind === 'scopedAlternatives')
60
+ return freezeAlternatives(policy);
61
+ if (policy.kind === 'optionalAuth') {
62
+ const authenticatedScopes = freezeScopeRequirement(policy.authenticatedScopes);
63
+ return Object.isFrozen(policy) && authenticatedScopes === policy.authenticatedScopes
64
+ ? policy
65
+ : Object.freeze({ kind: policy.kind, authenticatedScopes });
66
+ }
67
+ return frozenRecord(policy);
68
+ }
69
+ function freezeAlternatives(policy) {
70
+ const alternatives = policy.alternatives.map(freezeScopeRequirement);
71
+ if (Object.isFrozen(policy) &&
72
+ Object.isFrozen(policy.alternatives) &&
73
+ alternatives.every((alternative, index) => alternative === policy.alternatives[index]))
74
+ return policy;
75
+ return Object.freeze({ kind: policy.kind, alternatives: frozenNonEmpty(alternatives) });
76
+ }
77
+ function freezeScopeRequirement(requirement) {
78
+ if (Object.isFrozen(requirement) && Object.isFrozen(requirement.scopes))
79
+ return requirement;
80
+ return Object.freeze({ kind: requirement.kind, scopes: frozenNonEmpty(requirement.scopes) });
81
+ }
82
+ function frozenNonEmpty(values) {
83
+ const [first, ...rest] = values;
84
+ if (first === undefined)
85
+ throw new Error('expected a non-empty collection');
86
+ return Object.freeze([first, ...rest]);
87
+ }
88
+ function freezeParameterizedAccess(hint) {
89
+ const variants = hint.variants.map((variant) => {
90
+ const access = freezeAccessPolicy(variant.access);
91
+ return Object.isFrozen(variant) && access === variant.access
92
+ ? variant
93
+ : Object.freeze({ value: variant.value, access });
94
+ });
95
+ if (Object.isFrozen(hint) &&
96
+ Object.isFrozen(hint.variants) &&
97
+ variants.every((variant, index) => variant === hint.variants[index]))
98
+ return hint;
99
+ return Object.freeze({
100
+ discriminator: hint.discriminator,
101
+ ...(hint.defaultValue === undefined ? {} : { defaultValue: hint.defaultValue }),
102
+ variants: Object.freeze(variants),
103
+ });
104
+ }
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ import type { FlattenedZodIssue, OperationFault, TransportKind } from "../operation-fault.js";
3
+ import type { FaultPolicy, TransportAvailability, UnknownKeyPolicy } from "./types.js";
4
+ export declare const SUPPORTED_TRANSPORTS: ReadonlyArray<TransportKind>;
5
+ export declare const UNSAFE_PROTOTYPE_KEYS: ReadonlySet<string>;
6
+ /** Maps a transport to its key in {@link UnknownKeyPolicy}. */
7
+ export declare function transportToPolicyKey(transport: TransportKind): keyof UnknownKeyPolicy;
8
+ /** Maps a transport to its key in {@link TransportAvailability}. */
9
+ export declare function transportToAvailabilityKey(transport: Exclude<TransportKind, 'mcp'>): keyof TransportAvailability;
10
+ /**
11
+ * Extract the top-level keys of an object schema. The registry validates at
12
+ * construction time that every `inputSchema` is a `z.ZodObject`.
13
+ */
14
+ export declare function extractTopLevelObjectKeys(schema: z.ZodType): ReadonlySet<string>;
15
+ /**
16
+ * Build a prototype-safe shallow projection of `rawInput` containing only
17
+ * keys present in `knownKeys`.
18
+ */
19
+ export declare function sanitizeTopLevel(rawInput: Record<string, unknown>, knownKeys: ReadonlySet<string>): Record<string, unknown>;
20
+ export declare function flattenZodIssues(issues: ReadonlyArray<{
21
+ path: ReadonlyArray<PropertyKey>;
22
+ message: string;
23
+ code: string;
24
+ }>): ReadonlyArray<FlattenedZodIssue>;
25
+ /**
26
+ * Translate a thrown value from `invoke` into a transport-neutral
27
+ * OperationFault.
28
+ *
29
+ * A thrown `OperationFault` is checked against the operation's declared
30
+ * faults. Any other value goes to the host's `policy.classifyError` first (the
31
+ * host's own typed errors, matched by class so the classification is robust
32
+ * against error-message rewording), then to the message-pattern heuristics,
33
+ * which exist as a last-resort generic catch-all.
34
+ *
35
+ * **Producible-faults enforcement.** When `operation` is supplied (the
36
+ * dispatch pipeline always supplies it), any direct `OperationFault`
37
+ * throw whose `code` is NOT in the operation's `producibleFaults` ∪
38
+ * universal-defaults set is a declaration violation. `policy.strict` decides
39
+ * what happens, and it is strict when the host supplies nothing:
40
+ *
41
+ * - Strict: the fault is replaced by an `EngineFailure` that carries the
42
+ * diagnostic, so the developer notices and either declares the fault or
43
+ * migrates the throw to `raiseFault`.
44
+ * - Not strict: a `console.warn`. The original fault is preserved on the
45
+ * wire to keep clients' actionable semantics intact.
46
+ *
47
+ * This makes the producibleFaults declarations runtime-load-bearing for
48
+ * direct throws too — not just calls routed through the `raiseFault`
49
+ * helper.
50
+ */
51
+ export declare function classifyEngineError(error: unknown, operation?: {
52
+ name: string;
53
+ producibleFaults?: ReadonlyArray<string>;
54
+ }, policy?: FaultPolicy): OperationFault;
55
+ /**
56
+ * Diagnostic returned by `findUndeclaredFault` in strict mode when an
57
+ * operation raises a fault code that isn't in its `producibleFaults`
58
+ * declaration. `classifyEngineError` surfaces its message as an
59
+ * `EngineFailure` so test failures point at the declaration mismatch
60
+ * rather than silently passing through.
61
+ */
62
+ export declare class UndeclaredFaultError extends Error {
63
+ /** Stable machine-readable discriminant; equals the class name, as a `WeftError`'s does. */
64
+ readonly code = "UndeclaredFaultError";
65
+ /** The operation that produced it. */
66
+ readonly operationName: string;
67
+ /** The code the operation produced. */
68
+ readonly faultCode: string;
69
+ constructor(operationName: string, faultCode: string);
70
+ }
@@ -0,0 +1,242 @@
1
+ import { z } from 'zod';
2
+ import { UNIVERSAL_FAULT_DEFAULTS } from "./universal-faults.js";
3
+ export const SUPPORTED_TRANSPORTS = [
4
+ 'http-rest',
5
+ 'jsonRpcHttp',
6
+ 'jsonRpcWebSocket',
7
+ 'jsonRpcStdio',
8
+ ];
9
+ export const UNSAFE_PROTOTYPE_KEYS = new Set([
10
+ '__proto__',
11
+ 'prototype',
12
+ 'constructor',
13
+ ]);
14
+ /** Maps a transport to its key in {@link UnknownKeyPolicy}. */
15
+ export function transportToPolicyKey(transport) {
16
+ return transport === 'http-rest' ? 'http' : 'jsonRpc';
17
+ }
18
+ /** Maps a transport to its key in {@link TransportAvailability}. */
19
+ export function transportToAvailabilityKey(transport) {
20
+ switch (transport) {
21
+ case 'http-rest':
22
+ return 'http';
23
+ case 'jsonRpcHttp':
24
+ return 'jsonRpcHttp';
25
+ case 'jsonRpcWebSocket':
26
+ return 'jsonRpcWebSocket';
27
+ case 'jsonRpcStdio':
28
+ return 'jsonRpcStdio';
29
+ default: {
30
+ const exhaustiveCheck = transport;
31
+ throw new Error(`Unknown transport kind: ${JSON.stringify(exhaustiveCheck)}`);
32
+ }
33
+ }
34
+ }
35
+ /**
36
+ * Extract the top-level keys of an object schema. The registry validates at
37
+ * construction time that every `inputSchema` is a `z.ZodObject`.
38
+ */
39
+ export function extractTopLevelObjectKeys(schema) {
40
+ if (!(schema instanceof z.ZodObject)) {
41
+ throw new Error('extractTopLevelObjectKeys called with a non-object schema — the operation registry should have rejected this at construction');
42
+ }
43
+ return new Set(Object.keys(schema.shape).filter((key) => !UNSAFE_PROTOTYPE_KEYS.has(key)));
44
+ }
45
+ /**
46
+ * Build a prototype-safe shallow projection of `rawInput` containing only
47
+ * keys present in `knownKeys`.
48
+ */
49
+ export function sanitizeTopLevel(rawInput, knownKeys) {
50
+ const out = Object.create(null);
51
+ for (const key of Object.keys(rawInput)) {
52
+ if (UNSAFE_PROTOTYPE_KEYS.has(key))
53
+ continue;
54
+ if (knownKeys.has(key)) {
55
+ out[key] = rawInput[key];
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+ export function flattenZodIssues(issues) {
61
+ return issues.map((issue) => ({
62
+ path: issue.path.map((segment) => typeof segment === 'string' || typeof segment === 'number' ? segment : String(segment)),
63
+ message: issue.message,
64
+ code: issue.code,
65
+ }));
66
+ }
67
+ /**
68
+ * Translate a thrown value from `invoke` into a transport-neutral
69
+ * OperationFault.
70
+ *
71
+ * A thrown `OperationFault` is checked against the operation's declared
72
+ * faults. Any other value goes to the host's `policy.classifyError` first (the
73
+ * host's own typed errors, matched by class so the classification is robust
74
+ * against error-message rewording), then to the message-pattern heuristics,
75
+ * which exist as a last-resort generic catch-all.
76
+ *
77
+ * **Producible-faults enforcement.** When `operation` is supplied (the
78
+ * dispatch pipeline always supplies it), any direct `OperationFault`
79
+ * throw whose `code` is NOT in the operation's `producibleFaults` ∪
80
+ * universal-defaults set is a declaration violation. `policy.strict` decides
81
+ * what happens, and it is strict when the host supplies nothing:
82
+ *
83
+ * - Strict: the fault is replaced by an `EngineFailure` that carries the
84
+ * diagnostic, so the developer notices and either declares the fault or
85
+ * migrates the throw to `raiseFault`.
86
+ * - Not strict: a `console.warn`. The original fault is preserved on the
87
+ * wire to keep clients' actionable semantics intact.
88
+ *
89
+ * This makes the producibleFaults declarations runtime-load-bearing for
90
+ * direct throws too — not just calls routed through the `raiseFault`
91
+ * helper.
92
+ */
93
+ export function classifyEngineError(error, operation, policy) {
94
+ if (isOperationFault(error)) {
95
+ const violation = findUndeclaredFault(operation, error.code, policy);
96
+ if (violation !== null) {
97
+ // Strict mode caught an undeclared fault. Surface as
98
+ // EngineFailure with the diagnostic message so the test runner
99
+ // can assert against `result.fault.message` and the test fails
100
+ // loudly instead of silently passing through the original code.
101
+ return {
102
+ code: 'EngineFailure',
103
+ message: violation.message,
104
+ data: {},
105
+ };
106
+ }
107
+ return error;
108
+ }
109
+ const hostFault = policy?.classifyError?.(error);
110
+ if (hostFault !== undefined)
111
+ return hostFault;
112
+ if (error instanceof Error) {
113
+ return classifyErrorMessage(error);
114
+ }
115
+ return { code: 'EngineFailure', message: 'internal error', data: {} };
116
+ }
117
+ /**
118
+ * Diagnostic returned by `findUndeclaredFault` in strict mode when an
119
+ * operation raises a fault code that isn't in its `producibleFaults`
120
+ * declaration. `classifyEngineError` surfaces its message as an
121
+ * `EngineFailure` so test failures point at the declaration mismatch
122
+ * rather than silently passing through.
123
+ */
124
+ export class UndeclaredFaultError extends Error {
125
+ /** Stable machine-readable discriminant; equals the class name, as a `WeftError`'s does. */
126
+ code = 'UndeclaredFaultError';
127
+ /** The operation that produced it. */
128
+ operationName;
129
+ /** The code the operation produced. */
130
+ faultCode;
131
+ constructor(operationName, faultCode) {
132
+ super(`[weft] Operation "${operationName}" raised undeclared fault "${faultCode}". ` +
133
+ "Add it to the operation's `producibleFaults` array or migrate the throw to " +
134
+ '`raiseFault(operation, fault)`.');
135
+ this.name = this.code;
136
+ this.operationName = operationName;
137
+ this.faultCode = faultCode;
138
+ }
139
+ }
140
+ /** Strict unless the host said otherwise: a host that supplies nothing gets strict mode. */
141
+ function isStrictFaultPolicy(policy) {
142
+ const strict = policy?.strict;
143
+ if (strict === undefined)
144
+ return true;
145
+ return typeof strict === 'function' ? strict() : strict;
146
+ }
147
+ function findUndeclaredFault(operation, code, policy) {
148
+ if (operation === undefined)
149
+ return null;
150
+ if (UNIVERSAL_FAULT_DEFAULTS.has(code))
151
+ return null;
152
+ const declared = operation.producibleFaults;
153
+ if (declared !== undefined && declared.includes(code))
154
+ return null;
155
+ if (isStrictFaultPolicy(policy)) {
156
+ // Strict mode: hand the diagnostic back so the regression is observable
157
+ // through the test framework's normal failure path, with its message
158
+ // intact instead of swallowed as a bare `EngineFailure`.
159
+ return new UndeclaredFaultError(operation.name, code);
160
+ }
161
+ // Production: log only. Original fault is preserved on the wire so
162
+ // clients keep their actionable Conflict semantics.
163
+ console.warn(`[weft] Operation "${operation.name}" raised undeclared fault "${code}". ` +
164
+ "Add it to the operation's `producibleFaults` array or migrate the throw to " +
165
+ '`raiseFault(operation, fault)`.');
166
+ return null;
167
+ }
168
+ function classifyErrorMessage(error) {
169
+ let rawMessage;
170
+ try {
171
+ rawMessage = error.message;
172
+ }
173
+ catch {
174
+ return { code: 'EngineFailure', message: 'internal error', data: {} };
175
+ }
176
+ if (typeof rawMessage !== 'string') {
177
+ return { code: 'EngineFailure', message: 'internal error', data: {} };
178
+ }
179
+ const message = rawMessage.toLowerCase();
180
+ if (message.includes('not found')) {
181
+ return {
182
+ code: 'NotFound',
183
+ message: 'not found',
184
+ data: { resource: 'unknown' },
185
+ };
186
+ }
187
+ if (message.includes('already exists')) {
188
+ return {
189
+ code: 'Conflict',
190
+ message: 'conflict',
191
+ data: { reason: 'resource already exists' },
192
+ };
193
+ }
194
+ if (message.includes('timeout') || message.includes('timed out')) {
195
+ return {
196
+ code: 'Timeout',
197
+ message: 'operation timed out',
198
+ data: {},
199
+ };
200
+ }
201
+ return { code: 'EngineFailure', message: 'internal error', data: {} };
202
+ }
203
+ const FAULT_CODES = {
204
+ Unauthorized: true,
205
+ Forbidden: true,
206
+ NotFound: true,
207
+ Conflict: true,
208
+ Unprocessable: true,
209
+ Timeout: true,
210
+ PayloadTooLarge: true,
211
+ NotImplemented: true,
212
+ UnsupportedTransport: true,
213
+ SubscriptionOverflow: true,
214
+ InvalidParams: true,
215
+ MethodNotFound: true,
216
+ StaleRevision: true,
217
+ RateLimited: true,
218
+ Unavailable: true,
219
+ UnsupportedCapability: true,
220
+ EngineFailure: true,
221
+ };
222
+ function isOperationFault(value) {
223
+ if (typeof value !== 'object' || value === null)
224
+ return false;
225
+ let code;
226
+ let message;
227
+ let data;
228
+ try {
229
+ code = value.code;
230
+ message = value.message;
231
+ data = value.data;
232
+ }
233
+ catch {
234
+ return false;
235
+ }
236
+ return (typeof code === 'string' &&
237
+ typeof message === 'string' &&
238
+ typeof data === 'object' &&
239
+ data !== null &&
240
+ !Array.isArray(data) &&
241
+ Object.hasOwn(FAULT_CODES, code));
242
+ }
@@ -0,0 +1,23 @@
1
+ import type { OperationFault } from "../operation-fault.js";
2
+ import { type DispatchContext, type DispatchResult, type OperationContext, type OperationMetadata, type PipelineTrace, type PipelineTraceMarker, type UnknownKeyPolicy } from "./types.js";
3
+ export type PipelineParseOutcome<Input = unknown> = {
4
+ kind: 'ok';
5
+ input: Input;
6
+ } | {
7
+ kind: 'failure';
8
+ fault: OperationFault;
9
+ };
10
+ /** Verify that an operation is available on the current transport. */
11
+ export declare function checkTransport<Input, SchemaOutput, Host>(operation: OperationMetadata<Input, SchemaOutput, Host>, context: DispatchContext<Host>): DispatchResult<never> | null;
12
+ /** Verify the operation's static access policy against the caller principal. */
13
+ export declare function checkAccess<Input, SchemaOutput, Host>(operation: OperationMetadata<Input, SchemaOutput, Host>, context: DispatchContext<Host>): DispatchResult<never> | null;
14
+ /** Run the optional parameter-aware authorization hook. */
15
+ export declare function checkAuthorization<Input, SchemaOutput, Host>(operation: OperationMetadata<Input, SchemaOutput, Host>, context: OperationContext<Input, Host>): Promise<DispatchResult<never> | null>;
16
+ /**
17
+ * Input parsing stage: apply the catalog's top-level unknown-key policy,
18
+ * run the schema's `safeParse`, and re-attach passthrough extras onto a
19
+ * prototype-safe null-prototype object.
20
+ */
21
+ export declare function parseAndApplyUnknownKeyPolicy<Input, Host = unknown>(operation: OperationMetadata<Input, unknown, Host>, rawInput: unknown, policyKey: keyof UnknownKeyPolicy, pipelineTrace?: PipelineTrace): PipelineParseOutcome<Input>;
22
+ /** Emit one pipeline trace marker when a trace observer is installed. */
23
+ export declare function tracePipeline(pipelineTrace: PipelineTrace | undefined, marker: PipelineTraceMarker): void;
@@ -0,0 +1,226 @@
1
+ import { z } from 'zod';
2
+ import { evaluateAccess } from "../authorization.js";
3
+ import { isPlainObject } from "../json-schema-utilities.js";
4
+ import { SUPPORTED_TRANSPORTS, UNSAFE_PROTOTYPE_KEYS, extractTopLevelObjectKeys, flattenZodIssues, sanitizeTopLevel, transportToAvailabilityKey, } from "./pipeline-helpers.js";
5
+ import {} from "./types.js";
6
+ /** Verify that an operation is available on the current transport. */
7
+ export function checkTransport(operation, context) {
8
+ // An MCP tool call reaches exactly the operations the catalog marks `mcpExposable`.
9
+ const available = context.transport === 'mcp'
10
+ ? operation.mcpExposable
11
+ : operation.transports[transportToAvailabilityKey(context.transport)];
12
+ if (available)
13
+ return null;
14
+ const supported = SUPPORTED_TRANSPORTS.filter((transport) => transport !== 'mcp' && operation.transports[transportToAvailabilityKey(transport)]);
15
+ if (operation.mcpExposable)
16
+ supported.push('mcp');
17
+ return failure({
18
+ code: 'UnsupportedTransport',
19
+ message: `operation "${operation.name}" does not support transport "${context.transport}"`,
20
+ data: { transport: context.transport, supported },
21
+ });
22
+ }
23
+ /** Verify the operation's static access policy against the caller principal. */
24
+ export function checkAccess(operation, context) {
25
+ const access = evaluateAccess(operation.access, context.principal);
26
+ if (access.allowed)
27
+ return null;
28
+ if (access.classification === 'unauthorized') {
29
+ return failure({
30
+ code: 'Unauthorized',
31
+ message: access.reason,
32
+ data: { reason: access.reason },
33
+ });
34
+ }
35
+ return failure({
36
+ code: 'Forbidden',
37
+ message: access.reason,
38
+ data: { reason: access.reason },
39
+ });
40
+ }
41
+ /** Run the optional parameter-aware authorization hook. */
42
+ export async function checkAuthorization(operation, context) {
43
+ if (operation.authorize === undefined)
44
+ return null;
45
+ let decision;
46
+ try {
47
+ decision = await operation.authorize(context);
48
+ }
49
+ catch {
50
+ return failure({ code: 'EngineFailure', message: 'internal error', data: {} });
51
+ }
52
+ if (!isAuthorizationDecision(decision)) {
53
+ return failure({ code: 'EngineFailure', message: 'internal error', data: {} });
54
+ }
55
+ if (!decision.allowed) {
56
+ if (decision.classification === 'unauthorized') {
57
+ return failure({
58
+ code: 'Unauthorized',
59
+ message: decision.reason,
60
+ data: { reason: decision.reason },
61
+ });
62
+ }
63
+ return failure({
64
+ code: 'Forbidden',
65
+ message: decision.reason,
66
+ data: { reason: decision.reason },
67
+ });
68
+ }
69
+ return null;
70
+ }
71
+ /**
72
+ * Input parsing stage: apply the catalog's top-level unknown-key policy,
73
+ * run the schema's `safeParse`, and re-attach passthrough extras onto a
74
+ * prototype-safe null-prototype object.
75
+ */
76
+ export function parseAndApplyUnknownKeyPolicy(operation, rawInput, policyKey, pipelineTrace) {
77
+ const policy = operation.unknownKeyPolicy[policyKey];
78
+ const knownKeys = readKnownTopLevelKeys(operation);
79
+ if (knownKeys.kind === 'failure')
80
+ return knownKeys;
81
+ const preParse = buildPreParseInput(rawInput, policy, knownKeys.keys);
82
+ if (preParse.kind === 'failure')
83
+ return preParse;
84
+ const parseResult = safeParseInput(operation.inputSchema, preParse.input);
85
+ if (parseResult.kind === 'failure')
86
+ return parseResult;
87
+ tracePipeline(pipelineTrace, 'parsed');
88
+ const parsed = parseResult.input;
89
+ if (policy !== 'passthrough') {
90
+ tracePipeline(pipelineTrace, 'unknown-key-policy-applied');
91
+ return { kind: 'ok', input: parsed };
92
+ }
93
+ const passthroughOutput = buildPassthroughOutput(parsed, preParse.passthroughExtras);
94
+ tracePipeline(pipelineTrace, 'unknown-key-policy-applied');
95
+ return { kind: 'ok', input: passthroughOutput };
96
+ }
97
+ /** Emit one pipeline trace marker when a trace observer is installed. */
98
+ export function tracePipeline(pipelineTrace, marker) {
99
+ if (pipelineTrace === undefined)
100
+ return;
101
+ pipelineTrace(marker);
102
+ }
103
+ function readKnownTopLevelKeys(operation) {
104
+ try {
105
+ return { kind: 'ok', keys: extractTopLevelObjectKeys(operation.inputSchema) };
106
+ }
107
+ catch {
108
+ return {
109
+ kind: 'failure',
110
+ fault: { code: 'EngineFailure', message: 'internal error', data: {} },
111
+ };
112
+ }
113
+ }
114
+ function buildPreParseInput(rawInput, policy, knownKeys) {
115
+ if (!isPlainObject(rawInput)) {
116
+ return { kind: 'ok', input: rawInput, passthroughExtras: [] };
117
+ }
118
+ const rawRecord = rawInput;
119
+ const unknownTopLevel = Object.keys(rawRecord).filter((key) => !knownKeys.has(key));
120
+ if (unknownTopLevel.length === 0) {
121
+ return { kind: 'ok', input: rawInput, passthroughExtras: [] };
122
+ }
123
+ if (policy === 'reject') {
124
+ return {
125
+ kind: 'failure',
126
+ fault: {
127
+ code: 'InvalidParams',
128
+ message: 'unrecognized top-level keys',
129
+ data: {
130
+ issues: [
131
+ {
132
+ path: [],
133
+ message: `unrecognized top-level keys: ${unknownTopLevel.join(', ')}`,
134
+ code: 'unrecognized_keys',
135
+ },
136
+ ],
137
+ },
138
+ },
139
+ };
140
+ }
141
+ return {
142
+ kind: 'ok',
143
+ input: sanitizeTopLevel(rawRecord, knownKeys),
144
+ passthroughExtras: collectPassthroughExtras(rawRecord, unknownTopLevel, policy),
145
+ };
146
+ }
147
+ function collectPassthroughExtras(rawInput, unknownTopLevel, policy) {
148
+ if (policy !== 'passthrough')
149
+ return [];
150
+ return unknownTopLevel
151
+ .filter((key) => !UNSAFE_PROTOTYPE_KEYS.has(key))
152
+ .map((key) => [key, rawInput[key]]);
153
+ }
154
+ function buildPassthroughOutput(parsed, passthroughExtras) {
155
+ if (!isPlainObject(parsed))
156
+ return parsed;
157
+ Object.setPrototypeOf(parsed, null);
158
+ for (const [key, value] of passthroughExtras) {
159
+ if (key in parsed)
160
+ continue;
161
+ if (UNSAFE_PROTOTYPE_KEYS.has(key))
162
+ continue;
163
+ Object.defineProperty(parsed, key, {
164
+ configurable: true,
165
+ enumerable: true,
166
+ value,
167
+ writable: true,
168
+ });
169
+ }
170
+ return parsed;
171
+ }
172
+ function safeParseInput(inputSchema, input) {
173
+ let parseResult;
174
+ try {
175
+ parseResult = inputSchema.safeParse(input);
176
+ }
177
+ catch {
178
+ return {
179
+ kind: 'failure',
180
+ fault: { code: 'EngineFailure', message: 'internal error', data: {} },
181
+ };
182
+ }
183
+ if (!parseResult.success) {
184
+ return {
185
+ kind: 'failure',
186
+ fault: {
187
+ code: 'InvalidParams',
188
+ message: 'invalid params',
189
+ data: { issues: flattenZodIssues(parseResult.error.issues) },
190
+ },
191
+ };
192
+ }
193
+ return { kind: 'ok', input: parseResult.data };
194
+ }
195
+ function isAuthorizationDecision(value) {
196
+ if (typeof value !== 'object' || value === null)
197
+ return false;
198
+ const allowed = readObjectProperty(value, 'allowed');
199
+ if (!allowed.ok)
200
+ return false;
201
+ if (allowed.value === true)
202
+ return true;
203
+ if (allowed.value !== false)
204
+ return false;
205
+ const reason = readObjectProperty(value, 'reason');
206
+ if (!reason.ok || typeof reason.value !== 'string')
207
+ return false;
208
+ const classification = readObjectProperty(value, 'classification');
209
+ if (!classification.ok)
210
+ return false;
211
+ return isAuthorizationFailureClassification(classification.value);
212
+ }
213
+ function readObjectProperty(value, property) {
214
+ try {
215
+ return { ok: true, value: Reflect.get(value, property) };
216
+ }
217
+ catch {
218
+ return { ok: false };
219
+ }
220
+ }
221
+ function isAuthorizationFailureClassification(value) {
222
+ return value === undefined || value === 'unauthorized' || value === 'forbidden';
223
+ }
224
+ function failure(fault) {
225
+ return { ok: false, fault };
226
+ }
@@ -0,0 +1,7 @@
1
+ import { type DispatchContext, type DispatchResult } from "./types.js";
2
+ /**
3
+ * Single request/response dispatch pipeline. Every request/response transport
4
+ * call goes through the same transport, access, input validation,
5
+ * authorization, invocation, and output-validation stages.
6
+ */
7
+ export declare function executeOperation(operationName: string, rawInput: unknown, context: DispatchContext): Promise<DispatchResult<unknown>>;