@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,561 @@
1
+ /**
2
+ * Generates a typed client for any operation catalog.
3
+ *
4
+ * The core, {@link createOperationClientSources}, takes a catalog snapshot and the options that
5
+ * name the catalog's package, its server and its connection, and returns the generated files as a
6
+ * map from file name to source. It reads no file and imports no formatter: the caller writes the
7
+ * files and passes the formatter, so the package depends on neither `prettier` nor a file system.
8
+ * The generated client imports `@lostgradient/backchannel/client` for its runtime.
9
+ *
10
+ * @module generator
11
+ */
12
+ import { compareStrings } from "../internals.js";
13
+ import { join } from 'node:path';
14
+ import { renderOperationBehaviors } from "./operation-behaviors.js";
15
+ import { referencedRootAliases, renderAliasDeclarations, selectAliases, } from "./operation-client-aliases.js";
16
+ import { GENERATED_HEADER, operationDomains, operationDomainSource, subscriptionTypesSource, } from "./operation-client-domains.js";
17
+ import { canonicalKey, parseSchema, renderNode } from "./operation-client-schema.js";
18
+ import { svelteClientSource } from "./operation-client-svelte.js";
19
+ const DEFAULT_RUNTIME_SPECIFIER = '@lostgradient/backchannel/client';
20
+ const DEFAULT_OUTPUT_FILE = 'operation-client.generated.ts';
21
+ const SUBSCRIPTION_TYPES_FILE = 'subscription-operations.generated.ts';
22
+ const DEFAULT_SUBSCRIPTION_ROUTE_PREFIX = '/v1/subscriptions';
23
+ /**
24
+ * Generate a typed client from a catalog snapshot: one file of types per domain, a file of shared
25
+ * type aliases when any repeat, and the main file that holds the operation names, the REST
26
+ * bindings, the type maps and the factory. Output is deterministic for a given snapshot and
27
+ * options, so a checked-in copy can be compared against a fresh run.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { createOperationClientSources } from '@lostgradient/backchannel/generator';
32
+ *
33
+ * const sources = await createOperationClientSources(
34
+ * { generatedBy: 'weft catalog snapshot', version: 1, operations: [] },
35
+ * {
36
+ * packageName: '@example/probe',
37
+ * serverName: 'Probe',
38
+ * factoryName: 'createProbeClient',
39
+ * outputDirectory: 'src/client/generated',
40
+ * format: async (source) => source,
41
+ * },
42
+ * );
43
+ * console.log([...sources.keys()]);
44
+ * ```
45
+ */
46
+ export async function createOperationClientSources(snapshot, options) {
47
+ const outputFile = options.outputFile ?? DEFAULT_OUTPUT_FILE;
48
+ const runtimeSpecifier = options.runtimeSpecifier ?? DEFAULT_RUNTIME_SPECIFIER;
49
+ const restPathPrefix = options.restPathPrefix ?? '';
50
+ const excludedRestTags = options.excludedRestTags ?? [];
51
+ const connection = options.connection ?? defaultConnection(runtimeSpecifier);
52
+ const catalogOperations = snapshot.operations
53
+ .filter((operation) => operation.kind === 'unary' && operation.transports.jsonRpcHttp)
54
+ .toSorted((left, right) => compareStrings(left.name, right.name));
55
+ const restOnlyOperations = snapshot.operations
56
+ .filter((operation) => isGenericRestClientOperation(operation, excludedRestTags))
57
+ .toSorted((left, right) => compareStrings(left.name, right.name));
58
+ const clientOperations = [...catalogOperations, ...restOnlyOperations].toSorted((left, right) => compareStrings(left.name, right.name));
59
+ const catalogNames = catalogOperations.map((operation) => ` '${operation.name}',`);
60
+ const dryRunNames = catalogOperations
61
+ .filter((operation) => operation.supportsDryRun)
62
+ .map((operation) => JSON.stringify(operation.name))
63
+ .join(' | ');
64
+ const dryRunParameter = dryRunNames ? `, ${dryRunNames}` : '';
65
+ const clientNames = clientOperations.map((operation) => ` '${operation.name}',`);
66
+ const restBindings = restOnlyOperations.map((operation) => {
67
+ const rest = operation.rest;
68
+ if (rest === undefined)
69
+ throw new Error(`missing REST binding for ${operation.name}`);
70
+ const clientPath = restPathPrefix !== '' && rest.path.startsWith(restPathPrefix)
71
+ ? rest.path.slice(restPathPrefix.length)
72
+ : rest.path;
73
+ return ` '${operation.name}': ${JSON.stringify({ ...rest, path: clientPath })},`;
74
+ });
75
+ const subscriptionOperations = selectSubscriptions(snapshot, options);
76
+ const schemaRoots = [
77
+ ...clientOperations.flatMap((operation) => [operation.inputSchema, operation.outputSchema]),
78
+ ...subscriptionOperations.flatMap((operation) => [
79
+ operation.inputSchema,
80
+ operation.eventSchema ?? {},
81
+ ]),
82
+ ];
83
+ const parsedRoots = schemaRoots.map(parseSchema);
84
+ const definitions = new Map(parsedRoots.flatMap((parsed) => [...parsed.definitions]));
85
+ const roots = [...parsedRoots.map((parsed) => parsed.root), ...definitions.values()];
86
+ const { aliasNameByKey, nodeByKey } = selectAliases(roots);
87
+ const allAliases = new Map(aliasNameByKey);
88
+ for (const name of definitions.keys())
89
+ allAliases.set(canonicalKey({ kind: 'reference', name }), name);
90
+ const domains = operationDomains(clientOperations, options.domainName);
91
+ const imports = domains
92
+ .map((domain) => `import type { ${domain.typeName} } from './${domain.fileName}';`)
93
+ .join('\n');
94
+ const types = domains.map((domain) => domain.typeName).join(' & ') || '{}';
95
+ const aliasDeclarations = [
96
+ ...renderAliasDeclarations(aliasNameByKey, nodeByKey),
97
+ ...[...definitions.entries()]
98
+ .toSorted(([left], [right]) => compareStrings(left, right))
99
+ .map(([name, node]) => `type ${name} = ${renderNode(node, allAliases)};`),
100
+ ];
101
+ const referencedAliases = options.referencedSharedTypesOnly
102
+ ? referencedRootAliases(parsedRoots.map((parsed) => parsed.root), allAliases)
103
+ : undefined;
104
+ const declarationNames = [
105
+ ...[...aliasNameByKey.values()].toSorted(compareStrings),
106
+ ...[...definitions.keys()].toSorted(compareStrings),
107
+ ];
108
+ const sources = new Map();
109
+ const includes = (entry) => options.entries === undefined || options.entries.includes(entry);
110
+ if (options.svelte && includes('svelte') && !includes('client'))
111
+ throw new Error('Svelte bindings require the client entry');
112
+ if (options.portableEntries && includes('fetch') && !includes('portable'))
113
+ throw new Error('The Fetch entry requires the portable entry');
114
+ for (const domain of domains)
115
+ sources.set(domain.fileName, operationDomainSource(domain, allAliases));
116
+ if (aliasDeclarations.length)
117
+ sources.set('shared-operation-types.generated.ts', `${GENERATED_HEADER}\n${aliasDeclarations.map((declaration, index) => `${referencedAliases === undefined || referencedAliases.has(declarationNames[index]) ? 'export ' : ''}${declaration}`).join('\n')}\n`);
118
+ if (subscriptionOperations.length)
119
+ sources.set(SUBSCRIPTION_TYPES_FILE, subscriptionTypesSource(subscriptionOperations, allAliases));
120
+ const names = exampleNames(options.examples, catalogOperations, restOnlyOperations, subscriptionOperations);
121
+ const behaviors = renderOperationBehaviors(snapshot.operations);
122
+ if (behaviors !== undefined && includes('behaviors'))
123
+ sources.set('operation-behaviors.generated.ts', behaviors);
124
+ if (includes('client'))
125
+ sources.set(outputFile, options.typeOnlyClient
126
+ ? `${GENERATED_HEADER}\n${imports}\nexport type ClientOperationTypes = ${types};\n`
127
+ : mainSource({
128
+ options,
129
+ connection,
130
+ runtimeSpecifier,
131
+ restPathPrefix,
132
+ imports,
133
+ types,
134
+ catalogNames,
135
+ dryRunParameter,
136
+ clientNames,
137
+ restBindings,
138
+ subscriptionNames: subscriptionOperations.map((operation) => ` '${operation.name}',`),
139
+ names,
140
+ }));
141
+ if (options.portableEntries && (includes('portable') || includes('fetch'))) {
142
+ const portableFile = 'portable-operation-client.generated.ts';
143
+ if (includes('portable'))
144
+ sources.set(portableFile, `${GENERATED_HEADER}
145
+ import { createCatalogClient, type CatalogClient, type CatalogTransport } from '${runtimeSpecifier}';
146
+ ${imports}
147
+
148
+ const operationNames = [
149
+ ${catalogNames.join('\n')}
150
+ ] as const;
151
+
152
+ type CatalogOperationTypes = Pick<${types}, (typeof operationNames)[number]>;
153
+
154
+ /** Bind this catalog to a host-provided transport. */
155
+ export function ${options.factoryName}WithTransport(transport: CatalogTransport): CatalogClient<CatalogOperationTypes${dryRunParameter}> {
156
+ return createCatalogClient<CatalogOperationTypes${dryRunParameter}>(operationNames, transport);
157
+ }
158
+ `);
159
+ if (includes('fetch'))
160
+ sources.set('fetch-operation-client.generated.ts', `${GENERATED_HEADER}
161
+ import { httpJsonRpcTransport, type JsonRpcHttpConnection${subscriptionOperations.length ? ', createSubscriptionClient, sseSubscriptionTransport' : ''} } from '${runtimeSpecifier}';
162
+ import { ${options.factoryName}WithTransport } from './${portableFile}';
163
+ ${subscriptionOperations.length
164
+ ? `import type { SubscriptionOperationTypes } from './${SUBSCRIPTION_TYPES_FILE}';
165
+
166
+ const subscriptionNames = [
167
+ ${subscriptionOperations.map((operation) => ` '${operation.name}',`).join('\n')}
168
+ ] as const;\n`
169
+ : ''}
170
+
171
+ /** Bind this catalog to the Fetch JSON-RPC transport. */
172
+ export function ${options.factoryName}WithFetch(connection: JsonRpcHttpConnection) {
173
+ ${subscriptionOperations.length
174
+ ? `return {
175
+ ...${options.factoryName}WithTransport(httpJsonRpcTransport(connection)),
176
+ ...createSubscriptionClient<SubscriptionOperationTypes>(
177
+ subscriptionNames,
178
+ sseSubscriptionTransport({ ...connection, routePrefix: ${JSON.stringify(options.subscriptionRoutes?.pathPrefix ?? DEFAULT_SUBSCRIPTION_ROUTE_PREFIX)} }),
179
+ ),
180
+ };`
181
+ : `return ${options.factoryName}WithTransport(httpJsonRpcTransport(connection));`}
182
+ }
183
+ `);
184
+ }
185
+ if (options.svelte && includes('svelte')) {
186
+ sources.set('operation-client.svelte.ts', svelteClientSource(clientOperations, subscriptionOperations, outputFile, options.serverName, options.svelteCommands, options.svelteProvider));
187
+ }
188
+ const formatted = new Map();
189
+ for (const [fileName, contents] of sources) {
190
+ formatted.set(fileName, await options.format(contents, join(options.outputDirectory, fileName)));
191
+ }
192
+ return formatted;
193
+ }
194
+ /**
195
+ * The subscriptions that get a method: with `subscriptions: 'generic'`, every operation of kind
196
+ * `subscription` whose HTTP route is enabled and that the route options let through.
197
+ */
198
+ function selectSubscriptions(snapshot, options) {
199
+ if (options.subscriptions !== 'generic')
200
+ return [];
201
+ const include = options.subscriptionRoutes?.include ?? (() => true);
202
+ return snapshot.operations
203
+ .filter((operation) => operation.kind === 'subscription' && operation.transports.http && include(operation))
204
+ .toSorted((left, right) => compareStrings(left.name, right.name));
205
+ }
206
+ function defaultConnection(runtimeSpecifier) {
207
+ return {
208
+ typeName: 'JsonRpcHttpConnection',
209
+ transportName: 'httpJsonRpcTransport',
210
+ importSpecifier: runtimeSpecifier,
211
+ description: [
212
+ 'Pass the base URL of the handler, absolute or a path the browser resolves, and any',
213
+ 'headers every call needs.',
214
+ ],
215
+ example: "{ baseUrl: 'https://api.example.test' }",
216
+ };
217
+ }
218
+ /** Each example name the caller left out falls back to an operation the snapshot holds. */
219
+ function exampleNames(examples, catalogOperations, restOnlyOperations, subscriptionOperations) {
220
+ const first = catalogOperations[0]?.name ?? 'example.operation';
221
+ return {
222
+ list: examples?.list ?? first,
223
+ callable: examples?.callable ?? first,
224
+ cancel: examples?.cancel ?? first,
225
+ restOnly: examples?.restOnly ?? restOnlyOperations[0]?.name ?? first,
226
+ subscription: examples?.subscription ?? subscriptionOperations[0]?.name ?? first,
227
+ };
228
+ }
229
+ function importList(names) {
230
+ return names.map((name) => ` ${name},`).join('\n');
231
+ }
232
+ function runtimeImports(input) {
233
+ const { connection, runtimeSpecifier } = input;
234
+ const runtimeNames = [
235
+ 'createCatalogClient',
236
+ 'type ClientRestOperationBinding',
237
+ 'type CatalogClient',
238
+ ...(input.subscriptionNames.length > 0
239
+ ? ['createSubscriptionClient', 'sseSubscriptionTransport', 'type SubscriptionClient']
240
+ : []),
241
+ ];
242
+ const connectionNames = [connection.transportName, `type ${connection.typeName}`];
243
+ if (connection.importSpecifier === runtimeSpecifier) {
244
+ return `import {\n${importList([...runtimeNames, ...connectionNames])}\n} from '${runtimeSpecifier}';`;
245
+ }
246
+ return `import {\n${importList(runtimeNames)}\n} from '${runtimeSpecifier}';\nimport {\n${importList(connectionNames)}\n} from '${connection.importSpecifier}';`;
247
+ }
248
+ function pathNote(restPathPrefix) {
249
+ return restPathPrefix === ''
250
+ ? 'Paths are as the server serves them.'
251
+ : `Paths are client-relative: the server's \`${restPathPrefix}\` prefix is stripped.`;
252
+ }
253
+ function mainSource(input) {
254
+ const { options, connection, restPathPrefix, names } = input;
255
+ const packageName = options.packageName;
256
+ const server = options.serverName;
257
+ const factory = options.factoryName;
258
+ const exampleLines = connection.example
259
+ .split('\n')
260
+ .map((line, index) => (index === 0 ? line : ` * ${line}`))
261
+ .join('\n');
262
+ const description = connection.description
263
+ .map((line, index) => (index === 0 ? line : ` * ${line}`))
264
+ .join('\n');
265
+ const parameter = `connection: ${connection.typeName}${connection.defaultValue === undefined ? '' : ` = ${connection.defaultValue}`}`;
266
+ const subscribed = input.subscriptionNames.length > 0;
267
+ const subscriptionTypesImport = subscribed
268
+ ? `\nimport type { SubscriptionOperationTypes } from './${SUBSCRIPTION_TYPES_FILE}';`
269
+ : '';
270
+ const routePrefix = options.subscriptionRoutes?.pathPrefix ?? DEFAULT_SUBSCRIPTION_ROUTE_PREFIX;
271
+ return `${GENERATED_HEADER}
272
+ ${input.imports}${subscriptionTypesImport}
273
+
274
+ ${runtimeImports(input)}
275
+
276
+ /**
277
+ * Every unary operation this server exposes over JSON-RPC, sorted by name.
278
+ *
279
+ * This is exactly the set {@link ${factory}} turns into client methods,
280
+ * so it also answers "can I call this over JSON-RPC?" at runtime — worth
281
+ * checking when the name arrived as a string from a CLI argument or a queued
282
+ * job, before you hand it to the client.
283
+ *
284
+ * @example
285
+ * \`\`\`ts
286
+ * import { CATALOG_OPERATION_NAMES } from '${packageName}';
287
+ *
288
+ * const requested = '${names.callable}';
289
+ * const callable = CATALOG_OPERATION_NAMES.some((name) => name === requested);
290
+ * console.log(callable); // true
291
+ * \`\`\`
292
+ */
293
+ export const CATALOG_OPERATION_NAMES = [
294
+ ${input.catalogNames.join('\n')}
295
+ ] as const;
296
+
297
+ /**
298
+ * The name of any operation callable over JSON-RPC — the union behind
299
+ * {@link CATALOG_OPERATION_NAMES}.
300
+ *
301
+ * Annotate with this when an operation name reaches you from somewhere
302
+ * untyped and you would rather the compiler reject a name this server does
303
+ * not serve than discover it on the first round trip.
304
+ *
305
+ * @example
306
+ * \`\`\`ts
307
+ * import type { CatalogOperationName } from '${packageName}';
308
+ *
309
+ * const operation: CatalogOperationName = '${names.list}';
310
+ * console.log(operation);
311
+ * \`\`\`
312
+ */
313
+ export type CatalogOperationName = (typeof CATALOG_OPERATION_NAMES)[number];
314
+
315
+ /**
316
+ * Every operation the generated client can reach, sorted by name: the JSON-RPC
317
+ * catalog in {@link CATALOG_OPERATION_NAMES} plus those served only over REST.
318
+ *
319
+ * Reach for this when you want the client's whole surface — building a
320
+ * permission table, generating documentation, checking coverage — and for
321
+ * {@link CATALOG_OPERATION_NAMES} when you specifically need the JSON-RPC
322
+ * subset.
323
+ *
324
+ * @example
325
+ * \`\`\`ts
326
+ * import { CATALOG_OPERATION_NAMES, CLIENT_OPERATION_NAMES } from '${packageName}';
327
+ *
328
+ * const restOnly = CLIENT_OPERATION_NAMES.filter(
329
+ * (name) => !CATALOG_OPERATION_NAMES.some((catalogName) => catalogName === name),
330
+ * );
331
+ * console.log(restOnly.length);
332
+ * \`\`\`
333
+ */
334
+ export const CLIENT_OPERATION_NAMES = [
335
+ ${input.clientNames.join('\n')}
336
+ ] as const;
337
+
338
+ /**
339
+ * The name of any operation the generated client can reach — the union behind
340
+ * {@link CLIENT_OPERATION_NAMES}.
341
+ *
342
+ * Wider than {@link CatalogOperationName}, which covers only the JSON-RPC
343
+ * subset. Use this one for code that handles REST-only operations too.
344
+ *
345
+ * @example
346
+ * \`\`\`ts
347
+ * import type { ClientOperationName } from '${packageName}';
348
+ *
349
+ * const operation: ClientOperationName = '${names.list}';
350
+ * console.log(operation);
351
+ * \`\`\`
352
+ */
353
+ export type ClientOperationName = (typeof CLIENT_OPERATION_NAMES)[number];
354
+
355
+ /**
356
+ * HTTP method, path template and input placement for each operation the client
357
+ * reaches over REST rather than JSON-RPC.
358
+ *
359
+ * The generated client already uses this table to build its requests, so read
360
+ * it directly only when you are working outside the client — proxying ${server}
361
+ * behind your own router, or writing a gateway that has to reproduce the same
362
+ * routes. ${pathNote(restPathPrefix)}
363
+ *
364
+ * @example
365
+ * \`\`\`ts
366
+ * import { CLIENT_REST_OPERATION_BINDINGS } from '${packageName}';
367
+ *
368
+ * for (const [operation, binding] of Object.entries(CLIENT_REST_OPERATION_BINDINGS)) {
369
+ * console.log(binding.method + ' ' + binding.path + ' ' + operation);
370
+ * }
371
+ * \`\`\`
372
+ */
373
+ export const CLIENT_REST_OPERATION_BINDINGS = {
374
+ ${input.restBindings.join('\n')}
375
+ } as const satisfies Readonly<Record<string, ClientRestOperationBinding>>;
376
+
377
+ /**
378
+ * Input and output types for every operation the client can reach, keyed by
379
+ * operation name and assembled from the per-domain generated modules.
380
+ *
381
+ * You seldom name this directly — {@link ${factory}} applies it for you.
382
+ * It earns its keep when you write code generic over operations, such as a
383
+ * logging or retry wrapper that has to preserve each operation's own input and
384
+ * output types instead of widening them to \`unknown\`.
385
+ *
386
+ * @example
387
+ * \`\`\`ts
388
+ * import type { ClientOperationTypes } from '${packageName}';
389
+ *
390
+ * type CancelInput = ClientOperationTypes['${names.cancel}']['input'];
391
+ *
392
+ * declare const input: CancelInput;
393
+ * console.log(input);
394
+ * \`\`\`
395
+ */
396
+ export type ClientOperationTypes = ${input.types};
397
+
398
+ /**
399
+ * The {@link ClientOperationTypes} entries for operations reachable over
400
+ * JSON-RPC, which is the surface {@link ${factory}} builds against.
401
+ *
402
+ * Use this rather than {@link ClientOperationTypes} when your code runs
403
+ * against a JSON-RPC transport and should not reference an operation that only
404
+ * exists over REST.
405
+ *
406
+ * @example
407
+ * \`\`\`ts
408
+ * import type { CatalogOperationTypes } from '${packageName}';
409
+ *
410
+ * type AlertsOutput = CatalogOperationTypes['${names.list}']['output'];
411
+ *
412
+ * declare const alerts: AlertsOutput;
413
+ * console.log(alerts);
414
+ * \`\`\`
415
+ */
416
+ export type CatalogOperationTypes = Pick<ClientOperationTypes, CatalogOperationName>;
417
+
418
+ /**
419
+ * A client shaped over the JSON-RPC operations in {@link CatalogOperationTypes}.
420
+ * This is the type returned by {@link ${factory}}.
421
+ *
422
+ * @example
423
+ * \`\`\`ts
424
+ * import type { CatalogOperations } from '${packageName}';
425
+ *
426
+ * declare const client: CatalogOperations;
427
+ * const listAlerts = client['${names.list}'];
428
+ * console.log(typeof listAlerts);
429
+ * \`\`\`
430
+ */
431
+ export type CatalogOperations = CatalogClient<CatalogOperationTypes${input.dryRunParameter}>;
432
+
433
+ /**
434
+ * A client shaped over every operation, REST included: each operation name is
435
+ * a method taking that operation's input and resolving to its output.
436
+ *
437
+ * {@link ${factory}} returns the narrower {@link CatalogOperations} shape. Name this
438
+ * one when you build a client over a transport that also covers the REST-only
439
+ * operations.
440
+ *
441
+ * @example
442
+ * \`\`\`ts
443
+ * import type { ClientOperations } from '${packageName}';
444
+ *
445
+ * declare const client: ClientOperations;
446
+ * const diagnostics = client['${names.restOnly}'];
447
+ * console.log(typeof diagnostics);
448
+ * \`\`\`
449
+ */
450
+ export type ClientOperations = CatalogClient<ClientOperationTypes>;
451
+ ${subscribed ? subscriptionBlock(input) : ''}
452
+ /**
453
+ * Build a typed client for a remote ${server} server, with one method per operation
454
+ * in {@link CATALOG_OPERATION_NAMES}${subscribed ? ' and one per subscription in {@link SUBSCRIPTION_OPERATION_NAMES}' : ''}.
455
+ *
456
+ * Calls travel as JSON-RPC over HTTP. ${description}
457
+ *
458
+ * @example
459
+ * \`\`\`ts
460
+ * import { ${factory}, type ClientOperationTypes } from '${packageName}';
461
+ *
462
+ * const client = ${factory}(${exampleLines});
463
+ *
464
+ * declare const input: ClientOperationTypes['${names.list}']['input'];
465
+ * const alerts = await client['${names.list}'](input);
466
+ * console.log(alerts);
467
+ * \`\`\`
468
+ */
469
+ ${subscribed
470
+ ? `export function ${factory}(${parameter}): CatalogOperations & SubscriptionOperations {
471
+ return {
472
+ ...createCatalogClient<CatalogOperationTypes${input.dryRunParameter}>(
473
+ CATALOG_OPERATION_NAMES,
474
+ ${connection.transportName}(connection),
475
+ ),
476
+ ...createSubscriptionClient<SubscriptionOperationTypes>(
477
+ SUBSCRIPTION_OPERATION_NAMES,
478
+ sseSubscriptionTransport({ ...connection, routePrefix: ${JSON.stringify(routePrefix)} }),
479
+ ),
480
+ };
481
+ }`
482
+ : `export function ${factory}(${parameter}): CatalogOperations {
483
+ return createCatalogClient<CatalogOperationTypes${input.dryRunParameter}>(
484
+ CATALOG_OPERATION_NAMES,
485
+ ${connection.transportName}(connection),
486
+ );
487
+ }`}
488
+ `;
489
+ }
490
+ /** The names, the type and the type map of the subscription methods, with their documentation. */
491
+ function subscriptionBlock(input) {
492
+ const { options, names } = input;
493
+ const packageName = options.packageName;
494
+ return `
495
+ /**
496
+ * Every subscription this server streams over Server-Sent Events, sorted by name.
497
+ *
498
+ * This is exactly the set {@link ${options.factoryName}} turns into subscription methods.
499
+ *
500
+ * @example
501
+ * \`\`\`ts
502
+ * import { SUBSCRIPTION_OPERATION_NAMES } from '${packageName}';
503
+ *
504
+ * console.log(SUBSCRIPTION_OPERATION_NAMES.length);
505
+ * \`\`\`
506
+ */
507
+ export const SUBSCRIPTION_OPERATION_NAMES = [
508
+ ${input.subscriptionNames.join('\n')}
509
+ ] as const;
510
+
511
+ /**
512
+ * The name of any subscription the generated client opens — the union behind
513
+ * {@link SUBSCRIPTION_OPERATION_NAMES}.
514
+ *
515
+ * @example
516
+ * \`\`\`ts
517
+ * import type { SubscriptionOperationName } from '${packageName}';
518
+ *
519
+ * const operation: SubscriptionOperationName = '${names.subscription}';
520
+ * console.log(operation);
521
+ * \`\`\`
522
+ */
523
+ export type SubscriptionOperationName = (typeof SUBSCRIPTION_OPERATION_NAMES)[number];
524
+
525
+ /**
526
+ * A client shaped over the subscriptions in {@link SubscriptionOperationTypes}: each name is a
527
+ * method taking that operation's input and an optional \`{ signal, fetch, lastEventId }\`, and
528
+ * returning an \`AsyncIterable\` of its typed events and one replay-complete marker.
529
+ *
530
+ * @example
531
+ * \`\`\`ts
532
+ * import type { SubscriptionOperations } from '${packageName}';
533
+ *
534
+ * declare const client: SubscriptionOperations;
535
+ * const controller = new AbortController();
536
+ *
537
+ * for await (const message of client['${names.subscription}']({}, { signal: controller.signal })) {
538
+ * if (message.type === 'event') console.log(message.id, message.data);
539
+ * }
540
+ * \`\`\`
541
+ */
542
+ export type SubscriptionOperations = SubscriptionClient<SubscriptionOperationTypes>;
543
+ `;
544
+ }
545
+ /**
546
+ * Ordinary REST-only unary operations can use the generated JSON request
547
+ * transport. A tag in `excludedTags` marks operations whose octet-stream and NDJSON wire formats
548
+ * need a byte-oriented facade rather than schema-shaped JSON.
549
+ */
550
+ function isGenericRestClientOperation(operation, excludedTags) {
551
+ if (operation.kind !== 'unary')
552
+ return false;
553
+ if (!operation.transports.http || operation.transports.jsonRpcHttp)
554
+ return false;
555
+ if (excludedTags.some((tag) => operation.tags.includes(tag)))
556
+ return false;
557
+ const rest = operation.rest;
558
+ if (rest === undefined || rest.success.kind === 'streaming')
559
+ return false;
560
+ return Object.values(rest.inputSources).every((source) => source.kind !== 'body' || source.mediaType !== 'application/octet-stream');
561
+ }
@@ -0,0 +1,3 @@
1
+ import type { CatalogOperationSnapshot } from "../operation-catalog-snapshot.js";
2
+ /** Emit only declared public metadata, with no server or transport imports. */
3
+ export declare function renderOperationBehaviors(operations: readonly CatalogOperationSnapshot[]): string | undefined;
@@ -0,0 +1,16 @@
1
+ import { compareStrings } from "../json-schema-utilities.js";
2
+ /** Emit only declared public metadata, with no server or transport imports. */
3
+ export function renderOperationBehaviors(operations) {
4
+ if (!operations.some((operation) => operation.behavior !== undefined))
5
+ return undefined;
6
+ const descriptors = Object.fromEntries(operations
7
+ .toSorted((a, b) => compareStrings(a.name, b.name))
8
+ .map((operation) => [
9
+ operation.name,
10
+ {
11
+ mcpExposable: operation.mcpExposable ?? false,
12
+ ...(operation.behavior === undefined ? {} : { behavior: operation.behavior }),
13
+ },
14
+ ]));
15
+ return `export const CATALOG_OPERATION_BEHAVIORS = ${JSON.stringify(descriptors, null, 2)} as const;\n`;
16
+ }
@@ -0,0 +1,32 @@
1
+ import { type TypeNode } from "./operation-client-schema.js";
2
+ export type AliasSelection = {
3
+ readonly aliasNameByKey: ReadonlyMap<string, string>;
4
+ readonly nodeByKey: ReadonlyMap<string, TypeNode>;
5
+ };
6
+ /** Names referenced from operation roots after alias substitution. */
7
+ export declare function referencedRootAliases(roots: readonly TypeNode[], aliases: ReadonlyMap<string, string>): Set<string>;
8
+ /**
9
+ * Select which structural shapes to hoist into aliases. Prunes to a fixed point
10
+ * so that every surviving alias is referenced at least twice across the emitted
11
+ * alias bodies and operation entries. Returns both the name map and the original
12
+ * nodes so declarations render without round-tripping through the string key.
13
+ */
14
+ export declare function selectAliases(roots: ReadonlyArray<TypeNode>): AliasSelection;
15
+ export declare function isHoistWorthy(node: TypeNode, count: number): boolean;
16
+ /**
17
+ * Assign a stable, readable, content-derived name to each candidate shape.
18
+ * `hashFn` is injectable so the collision guard can be exercised in tests;
19
+ * it defaults to the real FNV-1a hash.
20
+ */
21
+ export declare function assignAliasNames(candidates: ReadonlyMap<string, TypeNode>, hashFn?: (value: string) => string): Map<string, string>;
22
+ /**
23
+ * Build the alias name `Shared<hint>_<hash>` for an object node: a readable
24
+ * hint drawn from the first sorted field names plus a stable content hash.
25
+ */
26
+ export declare function aliasNameFor(node: TypeNode, hashFn?: (value: string) => string): string;
27
+ /**
28
+ * Render the `type Shared… = …;` declarations, sorted by alias name. Each body
29
+ * is rendered from its original {@link TypeNode} with its own key suppressed, so
30
+ * nested aliases substitute but the alias never references itself.
31
+ */
32
+ export declare function renderAliasDeclarations(aliasNameByKey: ReadonlyMap<string, string>, nodeByKey: ReadonlyMap<string, TypeNode>): string[];