@distilled.cloud/core 1.0.0-rc.17 → 1.0.0-rc.19

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 (314) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/grpc.js +2 -0
  6. package/lib/_bundle/grpc.js.map +1 -0
  7. package/lib/_bundle/rest.js +1 -1
  8. package/lib/_bundle/rest.js.map +1 -1
  9. package/lib/_bundle/xml.js +1 -1
  10. package/lib/_bundle/xml.js.map +1 -1
  11. package/lib/annotations.d.ts +17 -0
  12. package/lib/annotations.d.ts.map +1 -0
  13. package/lib/annotations.js +2 -0
  14. package/lib/annotations.js.map +1 -0
  15. package/lib/api.d.ts +52 -1
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -1
  18. package/lib/category.d.ts.map +1 -1
  19. package/lib/config.d.ts +54 -13
  20. package/lib/config.d.ts.map +1 -1
  21. package/lib/config.js +1 -1
  22. package/lib/error-category.d.ts.map +1 -1
  23. package/lib/errors.d.ts +3 -13
  24. package/lib/errors.d.ts.map +1 -1
  25. package/lib/errors.js +1 -1
  26. package/lib/graphql.d.ts +26 -5
  27. package/lib/graphql.d.ts.map +1 -1
  28. package/lib/graphql.types.d.ts.map +1 -1
  29. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  30. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  31. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  32. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  33. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  34. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  35. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  36. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  37. package/lib/grpc-transport-node-http2.d.ts +19 -0
  38. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  39. package/lib/grpc-transport-node-http2.js +2 -0
  40. package/lib/grpc-transport-node-http2.js.map +1 -0
  41. package/lib/grpc-transport.d.ts +76 -0
  42. package/lib/grpc-transport.d.ts.map +1 -0
  43. package/lib/grpc-transport.js +1 -0
  44. package/lib/hpack.d.ts +34 -0
  45. package/lib/hpack.d.ts.map +1 -0
  46. package/lib/hpack.js +2 -0
  47. package/lib/hpack.js.map +1 -0
  48. package/lib/index.d.ts +6 -2
  49. package/lib/index.d.ts.map +1 -1
  50. package/lib/index.js +4 -0
  51. package/lib/pagination.d.ts +55 -3
  52. package/lib/pagination.d.ts.map +1 -1
  53. package/lib/pagination.js +1 -1
  54. package/lib/protobuf.d.ts +92 -0
  55. package/lib/protobuf.d.ts.map +1 -0
  56. package/lib/protobuf.js +1 -0
  57. package/lib/protocol-grpc.d.ts +86 -0
  58. package/lib/protocol-grpc.d.ts.map +1 -0
  59. package/lib/protocol-grpc.js +1 -0
  60. package/lib/protocol-http.d.ts +38 -9
  61. package/lib/protocol-http.d.ts.map +1 -1
  62. package/lib/protocol-http.js +1 -1
  63. package/lib/protocol-rest.d.ts +60 -42
  64. package/lib/protocol-rest.d.ts.map +1 -1
  65. package/lib/protocol-rest.js +1 -1
  66. package/lib/response-validation.d.ts +5 -4
  67. package/lib/response-validation.d.ts.map +1 -1
  68. package/lib/schema-lite-typed.js +1 -2
  69. package/lib/sdk-error.d.ts +27 -0
  70. package/lib/sdk-error.d.ts.map +1 -0
  71. package/lib/sdk-error.js +1 -0
  72. package/lib/sensitive.d.ts +28 -0
  73. package/lib/sensitive.d.ts.map +1 -0
  74. package/lib/sensitive.js +2 -0
  75. package/lib/sensitive.js.map +1 -0
  76. package/lib/telemetry-debug.d.ts +6 -0
  77. package/lib/telemetry-debug.d.ts.map +1 -0
  78. package/lib/telemetry-debug.js +2 -0
  79. package/lib/telemetry-debug.js.map +1 -0
  80. package/lib/telemetry-hooks.d.ts +32 -0
  81. package/lib/telemetry-hooks.d.ts.map +1 -0
  82. package/lib/telemetry-hooks.js +2 -0
  83. package/lib/telemetry-hooks.js.map +1 -0
  84. package/lib/telemetry-host-rules.d.ts +23 -0
  85. package/lib/telemetry-host-rules.d.ts.map +1 -0
  86. package/lib/telemetry-host-rules.js +2 -0
  87. package/lib/telemetry-host-rules.js.map +1 -0
  88. package/lib/telemetry-lambda-context.d.ts +17 -0
  89. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  90. package/lib/telemetry-lambda-context.js +2 -0
  91. package/lib/telemetry-lambda-context.js.map +1 -0
  92. package/lib/telemetry-message-context.d.ts +52 -0
  93. package/lib/telemetry-message-context.d.ts.map +1 -0
  94. package/lib/telemetry-message-context.js +2 -0
  95. package/lib/telemetry-message-context.js.map +1 -0
  96. package/lib/telemetry-metrics.d.ts +6 -0
  97. package/lib/telemetry-metrics.d.ts.map +1 -0
  98. package/lib/telemetry-metrics.js +2 -0
  99. package/lib/telemetry-metrics.js.map +1 -0
  100. package/lib/telemetry-name-template.d.ts +13 -0
  101. package/lib/telemetry-name-template.d.ts.map +1 -0
  102. package/lib/telemetry-name-template.js +2 -0
  103. package/lib/telemetry-name-template.js.map +1 -0
  104. package/lib/telemetry-stream.d.ts +11 -0
  105. package/lib/telemetry-stream.d.ts.map +1 -0
  106. package/lib/telemetry-stream.js +2 -0
  107. package/lib/telemetry-stream.js.map +1 -0
  108. package/lib/telemetry-xray.d.ts +28 -0
  109. package/lib/telemetry-xray.d.ts.map +1 -0
  110. package/lib/telemetry-xray.js +2 -0
  111. package/lib/telemetry-xray.js.map +1 -0
  112. package/lib/telemetry.d.ts +288 -0
  113. package/lib/telemetry.d.ts.map +1 -0
  114. package/lib/telemetry.js +3 -0
  115. package/lib/telemetry.js.map +1 -0
  116. package/lib/trait.d.ts +7 -0
  117. package/lib/trait.d.ts.map +1 -1
  118. package/lib/trait.js +1 -1
  119. package/lib/xml.d.ts.map +1 -1
  120. package/package.json +3 -5
  121. package/src/annotations.ts +53 -0
  122. package/src/api.ts +316 -43
  123. package/src/category.ts +21 -22
  124. package/src/config.ts +58 -29
  125. package/src/error-category.ts +12 -14
  126. package/src/errors.ts +11 -7
  127. package/src/graphql.ts +191 -63
  128. package/src/graphql.types.ts +5 -1
  129. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  130. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  131. package/src/grpc-transport-node-http2.ts +234 -0
  132. package/src/grpc-transport.ts +118 -0
  133. package/src/hpack.ts +331 -0
  134. package/src/index.ts +6 -2
  135. package/src/pagination.ts +193 -8
  136. package/src/protobuf.ts +1332 -0
  137. package/src/protocol-grpc.ts +641 -0
  138. package/src/protocol-http.ts +87 -67
  139. package/src/protocol-rest.ts +183 -191
  140. package/src/response-validation.ts +8 -5
  141. package/src/sdk-error.ts +33 -0
  142. package/src/sensitive.ts +154 -0
  143. package/src/telemetry-debug.ts +179 -0
  144. package/src/telemetry-hooks.ts +33 -0
  145. package/src/telemetry-host-rules.ts +39 -0
  146. package/src/telemetry-lambda-context.ts +46 -0
  147. package/src/telemetry-message-context.ts +170 -0
  148. package/src/telemetry-metrics.ts +69 -0
  149. package/src/telemetry-name-template.ts +26 -0
  150. package/src/telemetry-stream.ts +100 -0
  151. package/src/telemetry-xray.ts +66 -0
  152. package/src/telemetry.ts +832 -0
  153. package/src/trait.ts +10 -0
  154. package/src/xml.ts +10 -1
  155. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  156. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  157. package/lib/codegen/boolean-string-enums.js +0 -147
  158. package/lib/codegen/boolean-string-enums.js.map +0 -1
  159. package/lib/codegen/chunk.d.ts +0 -7
  160. package/lib/codegen/chunk.d.ts.map +0 -1
  161. package/lib/codegen/chunk.js +0 -139
  162. package/lib/codegen/chunk.js.map +0 -1
  163. package/lib/codegen/cli.d.ts +0 -80
  164. package/lib/codegen/cli.d.ts.map +0 -1
  165. package/lib/codegen/cli.js +0 -166
  166. package/lib/codegen/cli.js.map +0 -1
  167. package/lib/codegen/datafy.d.ts +0 -14
  168. package/lib/codegen/datafy.d.ts.map +0 -1
  169. package/lib/codegen/datafy.js +0 -853
  170. package/lib/codegen/datafy.js.map +0 -1
  171. package/lib/codegen/dedupe.d.ts +0 -5
  172. package/lib/codegen/dedupe.d.ts.map +0 -1
  173. package/lib/codegen/dedupe.js +0 -153
  174. package/lib/codegen/dedupe.js.map +0 -1
  175. package/lib/codegen/emit.d.ts +0 -125
  176. package/lib/codegen/emit.d.ts.map +0 -1
  177. package/lib/codegen/emit.js +0 -99
  178. package/lib/codegen/emit.js.map +0 -1
  179. package/lib/codegen/format.d.ts +0 -11
  180. package/lib/codegen/format.d.ts.map +0 -1
  181. package/lib/codegen/format.js +0 -32
  182. package/lib/codegen/format.js.map +0 -1
  183. package/lib/codegen/generated-at.d.ts +0 -29
  184. package/lib/codegen/generated-at.d.ts.map +0 -1
  185. package/lib/codegen/generated-at.js +0 -78
  186. package/lib/codegen/generated-at.js.map +0 -1
  187. package/lib/codegen/generator.d.ts +0 -353
  188. package/lib/codegen/generator.d.ts.map +0 -1
  189. package/lib/codegen/generator.js +0 -810
  190. package/lib/codegen/generator.js.map +0 -1
  191. package/lib/codegen/graph.d.ts +0 -36
  192. package/lib/codegen/graph.d.ts.map +0 -1
  193. package/lib/codegen/graph.js +0 -136
  194. package/lib/codegen/graph.js.map +0 -1
  195. package/lib/codegen/graphql-client.d.ts +0 -70
  196. package/lib/codegen/graphql-client.d.ts.map +0 -1
  197. package/lib/codegen/graphql-client.js +0 -439
  198. package/lib/codegen/graphql-client.js.map +0 -1
  199. package/lib/codegen/graphql.d.ts +0 -207
  200. package/lib/codegen/graphql.d.ts.map +0 -1
  201. package/lib/codegen/graphql.js +0 -786
  202. package/lib/codegen/graphql.js.map +0 -1
  203. package/lib/codegen/latin1.d.ts +0 -3
  204. package/lib/codegen/latin1.d.ts.map +0 -1
  205. package/lib/codegen/latin1.js +0 -126
  206. package/lib/codegen/latin1.js.map +0 -1
  207. package/lib/codegen/members.d.ts +0 -32
  208. package/lib/codegen/members.d.ts.map +0 -1
  209. package/lib/codegen/members.js +0 -62
  210. package/lib/codegen/members.js.map +0 -1
  211. package/lib/codegen/model-diff.d.ts +0 -10
  212. package/lib/codegen/model-diff.d.ts.map +0 -1
  213. package/lib/codegen/model-diff.js +0 -67
  214. package/lib/codegen/model-diff.js.map +0 -1
  215. package/lib/codegen/naming.d.ts +0 -29
  216. package/lib/codegen/naming.d.ts.map +0 -1
  217. package/lib/codegen/naming.js +0 -74
  218. package/lib/codegen/naming.js.map +0 -1
  219. package/lib/codegen/openapi-cli.d.ts +0 -52
  220. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  221. package/lib/codegen/openapi-cli.js +0 -84
  222. package/lib/codegen/openapi-cli.js.map +0 -1
  223. package/lib/codegen/openapi.d.ts +0 -209
  224. package/lib/codegen/openapi.d.ts.map +0 -1
  225. package/lib/codegen/openapi.js +0 -1548
  226. package/lib/codegen/openapi.js.map +0 -1
  227. package/lib/codegen/operations.d.ts +0 -24
  228. package/lib/codegen/operations.d.ts.map +0 -1
  229. package/lib/codegen/operations.js +0 -56
  230. package/lib/codegen/operations.js.map +0 -1
  231. package/lib/codegen/pagination.d.ts +0 -39
  232. package/lib/codegen/pagination.d.ts.map +0 -1
  233. package/lib/codegen/pagination.js +0 -31
  234. package/lib/codegen/pagination.js.map +0 -1
  235. package/lib/codegen/patch-audit.d.ts +0 -84
  236. package/lib/codegen/patch-audit.d.ts.map +0 -1
  237. package/lib/codegen/patch-audit.js +0 -366
  238. package/lib/codegen/patch-audit.js.map +0 -1
  239. package/lib/codegen/patches.d.ts +0 -129
  240. package/lib/codegen/patches.d.ts.map +0 -1
  241. package/lib/codegen/patches.js +0 -472
  242. package/lib/codegen/patches.js.map +0 -1
  243. package/lib/codegen/prelude.d.ts +0 -15
  244. package/lib/codegen/prelude.d.ts.map +0 -1
  245. package/lib/codegen/prelude.js +0 -60
  246. package/lib/codegen/prelude.js.map +0 -1
  247. package/lib/codegen/privatize.d.ts +0 -21
  248. package/lib/codegen/privatize.d.ts.map +0 -1
  249. package/lib/codegen/privatize.js +0 -176
  250. package/lib/codegen/privatize.js.map +0 -1
  251. package/lib/codegen/proto.d.ts +0 -121
  252. package/lib/codegen/proto.d.ts.map +0 -1
  253. package/lib/codegen/proto.js +0 -960
  254. package/lib/codegen/proto.js.map +0 -1
  255. package/lib/codegen/pure.d.ts +0 -6
  256. package/lib/codegen/pure.d.ts.map +0 -1
  257. package/lib/codegen/pure.js +0 -91
  258. package/lib/codegen/pure.js.map +0 -1
  259. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  260. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  261. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  262. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  263. package/lib/codegen/spec-path.d.ts +0 -16
  264. package/lib/codegen/spec-path.d.ts.map +0 -1
  265. package/lib/codegen/spec-path.js +0 -101
  266. package/lib/codegen/spec-path.js.map +0 -1
  267. package/lib/codegen/table.d.ts +0 -5
  268. package/lib/codegen/table.d.ts.map +0 -1
  269. package/lib/codegen/table.js +0 -249
  270. package/lib/codegen/table.js.map +0 -1
  271. package/lib/debug.d.ts +0 -2
  272. package/lib/debug.d.ts.map +0 -1
  273. package/lib/debug.js +0 -1
  274. package/lib/json-patch.d.ts +0 -58
  275. package/lib/json-patch.d.ts.map +0 -1
  276. package/lib/json-patch.js +0 -2
  277. package/lib/json-patch.js.map +0 -1
  278. package/lib/schema-lite-typed.js.map +0 -1
  279. package/lib/testing.d.ts +0 -40
  280. package/lib/testing.d.ts.map +0 -1
  281. package/lib/testing.js +0 -2
  282. package/lib/testing.js.map +0 -1
  283. package/src/codegen/boolean-string-enums.ts +0 -155
  284. package/src/codegen/chunk.ts +0 -147
  285. package/src/codegen/cli.ts +0 -293
  286. package/src/codegen/datafy.ts +0 -874
  287. package/src/codegen/dedupe.ts +0 -173
  288. package/src/codegen/emit.ts +0 -200
  289. package/src/codegen/format.ts +0 -49
  290. package/src/codegen/generated-at.ts +0 -88
  291. package/src/codegen/generator.ts +0 -1229
  292. package/src/codegen/graph.ts +0 -151
  293. package/src/codegen/graphql-client.ts +0 -545
  294. package/src/codegen/graphql.ts +0 -1145
  295. package/src/codegen/latin1.ts +0 -131
  296. package/src/codegen/members.ts +0 -79
  297. package/src/codegen/model-diff.ts +0 -67
  298. package/src/codegen/naming.ts +0 -85
  299. package/src/codegen/openapi-cli.ts +0 -141
  300. package/src/codegen/openapi.ts +0 -1845
  301. package/src/codegen/operations.ts +0 -73
  302. package/src/codegen/pagination.ts +0 -64
  303. package/src/codegen/patch-audit.ts +0 -480
  304. package/src/codegen/patches.ts +0 -581
  305. package/src/codegen/prelude.ts +0 -70
  306. package/src/codegen/privatize.ts +0 -200
  307. package/src/codegen/proto.ts +0 -1092
  308. package/src/codegen/pure.ts +0 -94
  309. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  310. package/src/codegen/spec-path.ts +0 -112
  311. package/src/codegen/table.ts +0 -254
  312. package/src/debug.ts +0 -8
  313. package/src/json-patch.ts +0 -273
  314. package/src/testing.ts +0 -74
@@ -1,1229 +0,0 @@
1
- import { booleanStringEnums, STRING_ENCODED_TRAIT } from "./boolean-string-enums.ts";
2
- import {
3
- enumDecl,
4
- errorClass,
5
- errorUnionAlias,
6
- interfaceDecl,
7
- interfaceField,
8
- operationConst,
9
- PURE,
10
- suspendConst,
11
- } from "./emit.ts";
12
- import { orderIndex, reachableFrom, shapeDeps, topoOrder, type ShapeMap } from "./graph.ts";
13
- import { ADDITIONAL_PROPERTIES_TRAIT, memberBases, smithyWireName } from "./members.ts";
14
- /**
15
- * The generic smithy→SDK service generator (dev-time only).
16
- *
17
- * One driver compiles a Smithy JSON model into an Effect SDK service module.
18
- * Everything provider-specific arrives through {@link SdkSpec}: import
19
- * header, trait vocabulary (which trait ids mean payload/file/nullable/…),
20
- * the `T.*` pipe expressions to emit for each binding, how operations are
21
- * declared (protocol/retry/error names), and naming policies. The driver
22
- * owns the pipeline: operation discovery, reachability, topological order,
23
- * schema/interface emission, error classes, pagination validation, and
24
- * operation consts.
25
- *
26
- * A provider's `scripts/generate.ts` reduces to: load models (its own
27
- * pipeline — docs-derived specs, patches, …), define its {@link SdkSpec},
28
- * call {@link generateService} per model, write files.
29
- */
30
- import { camel as _camel, local, lowerFirst, oneLine, q, tsKey, upperFirst } from "./naming.ts";
31
- import {
32
- collectOperations,
33
- collectOpErrorIds,
34
- ensureNamedIo,
35
- modelNamespace,
36
- type OpEntry,
37
- } from "./operations.ts";
38
- import { validatePaginated } from "./pagination.ts";
39
- import { JSON_PRELUDE, makeSchemaRef, makeTsRef, TS_JSON_PRELUDE } from "./prelude.ts";
40
-
41
- const PAGINATED_TRAIT = "smithy.api#paginated";
42
-
43
- /**
44
- * Error categories, derived from the STANDARD Smithy error traits.
45
- *
46
- * `smithy.api#httpError` and `smithy.api#retryable` are how every Smithy
47
- * model — AWS's included — says what kind of failure an error is. The
48
- * categories the runtime acts on (`core/category.ts`, and `isTransientError`
49
- * in `core/retry.ts`) are a reading of those two traits, so the reading
50
- * belongs here, once, for every provider.
51
- *
52
- * A model that wants its errors classified states the status the API
53
- * actually returns:
54
- *
55
- * "traits": { "smithy.api#error": "client", "smithy.api#httpError": 404 }
56
- *
57
- * and the error class is emitted with `.pipe(C.withNotFoundError)`. A model
58
- * with no `httpError` gets no categories — the same as today.
59
- */
60
- export const errorCategories = (
61
- traits: Record<string, any> | undefined,
62
- /** Categories a provider knows that the traits don't say (AWS's spec file). */
63
- extra: readonly string[] = [],
64
- ): string[] => {
65
- const categories: string[] = [];
66
- const add = (name: string) => {
67
- if (!categories.includes(name)) categories.push(name);
68
- };
69
- const status = traits?.["smithy.api#httpError"] as number | undefined;
70
- if (typeof status === "number") {
71
- if (status === 401 || status === 403) add("AuthError");
72
- else if (status === 402) add("QuotaError");
73
- else if (
74
- status === 400 ||
75
- status === 404 ||
76
- status === 405 ||
77
- status === 406 ||
78
- status === 410 ||
79
- status === 413 ||
80
- status === 415 ||
81
- status === 422
82
- ) {
83
- add("BadRequestError");
84
- } else if (status === 408 || status === 504) add("TimeoutError");
85
- else if (status === 409) add("ConflictError");
86
- else if (status === 429) add("ThrottlingError");
87
- else if (status >= 500 && status < 600) add("ServerError");
88
- }
89
- const retryable = traits?.["smithy.api#retryable"];
90
- if (retryable !== undefined) {
91
- add("RetryableError");
92
- if (retryable?.throttling) add("ThrottlingError");
93
- }
94
- for (const name of extra) add(name);
95
- return categories;
96
- };
97
-
98
- /** `["NotFoundError"]` → `C.withNotFoundError`. */
99
- const categoryPipes = (traits: Record<string, any> | undefined): string[] =>
100
- errorCategories(traits).map((name) => `C.with${name}`);
101
-
102
- /** A member's resolved binding. The four generic kinds plus provider extras. */
103
- export type MemberBinding = "label" | "query" | "header" | "body" | (string & {});
104
-
105
- export interface EmittedMember {
106
- readonly name: string;
107
- readonly tsName: string;
108
- readonly wire: string;
109
- readonly target: string;
110
- readonly binding: MemberBinding;
111
- readonly required: boolean;
112
- readonly nullable: boolean;
113
- readonly doc: string | undefined;
114
- readonly traits: Record<string, any>;
115
- }
116
-
117
- export interface PaginationProfile {
118
- /** Protocol const for paginated ops. Defaults to operationDecl.protocol. */
119
- readonly protocol?: string;
120
- /** Strategy expression passed as makePaginated's second argument. */
121
- readonly strategy?: string;
122
- /** Items path fallback when the trait omits `items`. */
123
- readonly itemsFallback: string;
124
- /** Output names accepted even when not modeled (delivered by the protocol). */
125
- readonly syntheticOutputs?: readonly string[];
126
- /**
127
- * Extra interface field + struct member appended to paginated outputs
128
- * that don't already model them (what the protocol delivers beyond the
129
- * modeled shape — e.g. cloudflare's `resultInfo` from the envelope's
130
- * `result_info`). `imports` are pulled from the pagination module in the
131
- * header.
132
- */
133
- readonly injectOutputMember?: {
134
- readonly tsName: string;
135
- readonly interfaceLines: readonly string[];
136
- readonly structLine: string;
137
- readonly imports?: readonly string[];
138
- };
139
- }
140
-
141
- export interface OperationEmit {
142
- readonly op: OpEntry;
143
- readonly opName: string;
144
- readonly exportName: string;
145
- readonly inputName: string;
146
- readonly outputName: string;
147
- /**
148
- * The output as a TS type and as a schema expression. These differ from
149
- * {@link outputName} when the operation's output IS a prelude shape
150
- * (e.g. stripe's freeform `smithy.api#Document` responses): the bare
151
- * local name isn't declared in the module, so it must resolve through
152
- * the prelude maps (`unknown` / `S.Unknown`) instead.
153
- */
154
- readonly outputTsType: string;
155
- readonly outputSchema: string;
156
- /** Declared error class names present in the model. */
157
- readonly errorNames: readonly string[];
158
- readonly doc: string | undefined;
159
- /** The validated pagination trait, when the op paginates. */
160
- readonly pagination: unknown | undefined;
161
- }
162
-
163
- export interface SdkSpec {
164
- /** Namespace fallback for models with no operations. Default `"smithy.unknown"`. */
165
- readonly namespaceFallback?: string;
166
- /** PURE marker before schema consts. Default: the shared single marker. */
167
- readonly pure?: string;
168
- /** Prelude scalar → schema expression map. Default {@link JSON_PRELUDE}. */
169
- readonly prelude?: Record<string, string>;
170
- /** Prelude scalar → TS type map. Default {@link TS_JSON_PRELUDE}. */
171
- readonly tsPrelude?: Record<string, string>;
172
- /** Use Codec for service-free, same-type schemas; Schema leaves services unspecified. */
173
- readonly schemaType?: "Schema" | "Codec";
174
- /** Wire member name → TS-facing name. Default: identity. */
175
- readonly memberName?: (name: string) => string;
176
- /** Operation shape name → exported const name. Default: lowerFirst. */
177
- readonly opExportName?: (name: string) => string;
178
- /**
179
- * Emit the one-line smithy doc comment above shapes and error classes.
180
- * Default true. AWS turns this off — its models carry multi-kilobyte HTML
181
- * docs per shape and the SDK only surfaces operation-level docs.
182
- */
183
- readonly shapeDocs?: boolean;
184
- /**
185
- * Extra reachability roots beyond the operations' I/O shapes. AWS seeds
186
- * the error shapes here so their member targets are emitted (error class
187
- * fields reference schema consts); the error shapes themselves are still
188
- * emitted as error classes, not schemas.
189
- */
190
- readonly extraRoots?: (selected: readonly OpEntry[], shapes: ShapeMap) => Iterable<string>;
191
-
192
- /**
193
- * Provider member bindings as data, checked in order between the generic
194
- * header binding and `smithy.api#httpPayload`. The driver's cascade:
195
- * label → query → header → extraBindings → rawBody (httpPayload) → body.
196
- *
197
- * `pipe` is emitted for the member; `tsType` overrides its interface
198
- * type (e.g. file uploads → `(File | Blob)[]`).
199
- */
200
- readonly extraBindings?: ReadonlyArray<{
201
- readonly trait: string;
202
- readonly binding: MemberBinding;
203
- readonly pipe: string;
204
- readonly tsType?: string;
205
- /**
206
- * Bare-payload form: when this binding is the sole member of a
207
- * (non-paginated) output structure, the whole response IS that
208
- * member's value — the driver emits the member's type directly and
209
- * pipes the schema through this root marker for the protocol.
210
- */
211
- readonly rootPipe?: string;
212
- }>;
213
- /**
214
- * Which wire-name rule a binding follows. Defaults: the three generic
215
- * kinds map to themselves, everything else to `"other"` (jsonName).
216
- */
217
- readonly wireKind?: (binding: MemberBinding) => "label" | "query" | "header" | "other";
218
- /** Trait id marking a member nullable (`S.NullOr` + `| null`). */
219
- readonly nullableTrait?: string;
220
- /**
221
- * Blanket-nullable optionals: every optional body member types and
222
- * decodes as `X | null` in addition to being omittable (`?: X | null`,
223
- * `S.optional(S.NullOr(X))`). The cloudflare docs pipeline sets this —
224
- * the v4 API freely returns explicit nulls for absent optional fields,
225
- * and the v0 SDK surface modeled every optional that way.
226
- */
227
- readonly optionalsNullable?: boolean;
228
- /**
229
- * Member traits emitted as pipes when present: trait id → pipe builder
230
- * name in the SDK's traits module. The trait's value is JSON-inlined as
231
- * the argument (e.g. `"…#keyDictionary": "T.KeyDictionary"` →
232
- * `T.KeyDictionary({…})`).
233
- */
234
- readonly memberTraitPipes?: Readonly<Record<string, string>>;
235
- /**
236
- * Extra schema pipes appended after the generic ones, for anything the
237
- * data tables can't express. The driver emits `T.Label/T.Query/T.Header`
238
- * (wire-aware), `T.HttpBody()` for rawBody, and `T.Body(wire)` renames —
239
- * the SDK's traits module must export those core builders under these
240
- * names.
241
- */
242
- readonly memberExtraPipes?: (m: EmittedMember) => string[];
243
- /** Full override of member pipe emission (rarely needed). */
244
- readonly memberPipes?: (m: EmittedMember) => string[];
245
- /** Override the value schema before nullability, bindings and optionality. */
246
- readonly memberSchema?: (m: EmittedMember, ref: (target: string) => string) => string | undefined;
247
- /** Function override for member TS types beyond the binding table. */
248
- readonly memberTsType?: (
249
- m: EmittedMember,
250
- tsRef: (target: string) => string,
251
- ) => string | undefined;
252
-
253
- /**
254
- * Struct-level pipes for a shape (after the member struct): the http
255
- * trait on op inputs, service-wide key-dictionary stamping, etc.
256
- */
257
- readonly structPipes?: (ctx: {
258
- readonly id: string;
259
- readonly isOpIo: boolean;
260
- readonly httpTrait: unknown | undefined;
261
- /** Traits of the operation whose INPUT this shape is (undefined otherwise). */
262
- readonly opTraits: Readonly<Record<string, unknown>> | undefined;
263
- }) => string[];
264
-
265
- /**
266
- * Pagination profiles. A profile is the codegen-side description of one
267
- * paginated wire variant: the Protocol const that decodes it, the
268
- * strategy passed to makePaginated, the trait-validation rules, and any
269
- * output member the protocol delivers beyond the modeled shape. SDKs
270
- * with several pagination styles declare several profiles and select
271
- * per-op via {@link SdkSpec.paginationProfileFor}.
272
- */
273
- readonly paginationProfiles?: Readonly<Record<string, PaginationProfile>>;
274
- /**
275
- * Select the profile for a paginated op (from its `smithy.api#paginated`
276
- * trait / shape). Default: the sole declared profile; with several
277
- * profiles this becomes required for ops to paginate.
278
- */
279
- readonly paginationProfileFor?: (trait: any, op: OpEntry) => string | undefined;
280
-
281
- /**
282
- * Service-wide fallback key dictionary stamped on op I/O roots (emitted
283
- * as a `KEY_DICTIONARY` header const + `T.KeyDictionary(KEY_DICTIONARY)`
284
- * root pipe). `doc` is the const's doc comment. An entry may list several
285
- * wire spellings (first = canonical encode name; decode accepts all).
286
- */
287
- readonly rootKeyDictionary?: {
288
- readonly dict: Record<string, string | ReadonlyArray<string>>;
289
- readonly doc: string;
290
- };
291
-
292
- /** Banner suffix: `AUTO-GENERATED by scripts/generate.ts from <note>`. */
293
- readonly sourceNote?: string;
294
-
295
- /**
296
- * Operation aliases: re-export the canonical op (and its
297
- * Request/Response/Error types) under each alias name. Skipped when the
298
- * target wasn't emitted or the alias name is taken.
299
- */
300
- readonly opAliases?: ReadonlyArray<{
301
- readonly alias: string;
302
- readonly target: string;
303
- }>;
304
-
305
- /**
306
- * Full shape-emission override, checked before the driver's own shape
307
- * handling. Return the emitted lines to own a shape (e.g. AWS's
308
- * newtypes, structural unions, event streams), or undefined to let the
309
- * driver emit it. `selfIdx` is the shape's position in emission order
310
- * for forward-ref decisions.
311
- */
312
- readonly shapeOverride?: (ctx: {
313
- readonly id: string;
314
- readonly def: any;
315
- readonly name: string;
316
- readonly selfIdx: number;
317
- readonly ref: (target: string, selfIdx: number) => string;
318
- readonly tsRef: (target: string) => string;
319
- readonly members: (d: any) => EmittedMember[];
320
- }) => string[] | undefined;
321
-
322
- /**
323
- * Union emission style. `"opaque-cases"`: the TS type is the case union
324
- * and the schema is `S.Unknown.pipe(T.UnionCases([...case key sets]))` —
325
- * the protocol discriminates by key-set at decode time (for APIs that
326
- * return every case's keys with nulls, like Cloudflare's).
327
- * `"untagged"`: validate the value directly against the case schemas.
328
- * `"primitive"`: emit unwrapped unions of primitive or enum values.
329
- */
330
- readonly unionStyle?: "opaque-cases" | "untagged" | "primitive";
331
- /** Full override of union emission. */
332
- readonly union?: (ctx: {
333
- readonly name: string;
334
- readonly caseTargets: readonly string[];
335
- readonly caseKeys: readonly (readonly string[])[];
336
- readonly tsRef: (target: string) => string;
337
- }) => string[];
338
-
339
- /**
340
- * Trait id carrying error matchers: when present on an error shape, the
341
- * class is wrapped in `T.applyErrorMatchers(<cls>, <trait value>)`.
342
- */
343
- readonly errorMatchersTrait?: string;
344
- /** Error-class emission details. All optional. */
345
- readonly errors?: {
346
- /**
347
- * Full override of one error class's emission (mirrors shapeOverride):
348
- * return the emitted lines to own the error, or undefined to fall back
349
- * to the driver's field/wrap-based emission.
350
- */
351
- readonly override?: (ctx: {
352
- readonly id: string;
353
- readonly def: any;
354
- readonly name: string;
355
- }) => string[] | undefined;
356
- /**
357
- * Field lines used when the error shape declares no members.
358
- * Default: `code` (integer) + `message` (string) — the common REST
359
- * error envelope.
360
- */
361
- readonly defaultFields?: (prelude: Record<string, string>) => string[];
362
- /** Field line for a declared member. Default: prelude-mapped schema. */
363
- readonly field?: (name: string, target: string) => string;
364
- /** Optional wrapper (e.g. matcher application) from the shape's traits. */
365
- readonly wrap?: (traits: Record<string, any>) => ((cls: string) => string) | undefined;
366
- };
367
-
368
- /**
369
- * Declarative operation emission — the names the op consts are built
370
- * from. `operation` overrides this entirely when a provider needs full
371
- * control of the emitted shape.
372
- */
373
- readonly operationDecl?: {
374
- /** Requirements type in the OperationMethod annotation. */
375
- readonly contextType: string;
376
- /** Base of the per-op error union alias (e.g. `CloudflareOpError`). */
377
- readonly commonErrorType: string;
378
- /** Error classes appended to every op's `errors: [...]` list. */
379
- readonly commonErrorClasses: readonly string[];
380
- readonly protocol: string;
381
- /** The retry tag expression (e.g. `Retry.Retry`). Omit to disable retries. */
382
- readonly retry?: string;
383
- /**
384
- * Extra config lines inserted before the pagination entry (e.g. AWS's
385
- * `operationName` and `endpointHostPrefix`).
386
- */
387
- readonly extraConfig?: (ctx: OperationEmit) => string[];
388
- /**
389
- * Per-operation `protocol` / `contextType` replacing the declared
390
- * defaults, e.g. an unauthenticated login endpoint on a public protocol
391
- * whose context has no credentials. Return `undefined` for the defaults.
392
- * The header only imports the defaults; a spec that overrides must add
393
- * the extra imports itself (see {@link SdkSpec.postProcess}).
394
- */
395
- readonly overrides?: (ctx: OperationEmit) =>
396
- | {
397
- readonly protocol?: string;
398
- readonly contextType?: string;
399
- }
400
- | undefined;
401
- };
402
- /** Full override of operation const emission. */
403
- readonly operation?: (ctx: OperationEmit) => string;
404
-
405
- /**
406
- * Module header override. The default builds the banner + imports from
407
- * {@link SdkSpec.operationDecl} names and the conventional module layout
408
- * (`../traits.ts`, `../protocol.ts`, `../pagination.ts`, `../errors.ts`,
409
- * `../retry.ts`), re-exports the op error/context types, and emits the
410
- * `KEY_DICTIONARY` const when {@link SdkSpec.rootKeyDictionary} is set.
411
- */
412
- readonly header?: (ctx: { readonly hasPaginated: boolean; readonly model: any }) => string;
413
-
414
- /** Final pass over the assembled module (e.g. pruning unused imports). */
415
- readonly postProcess?: (code: string) => string;
416
-
417
- /**
418
- * Trailing sections after operations (e.g. route-alias re-exports).
419
- * Receives the set of emitted op export names (mutable — additions are
420
- * visible to subsequent alias checks).
421
- */
422
- readonly footer?: (ctx: { readonly emittedOps: Set<string> }) => string[];
423
- }
424
-
425
- export interface GeneratedService {
426
- code: string;
427
- operations: number;
428
- }
429
-
430
- /** Compile one Smithy model into a service module. */
431
- export const generateService = (model: any, spec: SdkSpec): GeneratedService => {
432
- // `"true" | "false"` request members become real booleans that travel as
433
- // their string spelling (see boolean-string-enums.ts).
434
- booleanStringEnums(model);
435
- const shapes: ShapeMap = model.shapes;
436
- const pure = spec.pure ?? PURE;
437
- const prelude = spec.prelude ?? JSON_PRELUDE;
438
- const tsPrelude = spec.tsPrelude ?? TS_JSON_PRELUDE;
439
- const memberName = spec.memberName ?? ((n: string) => n);
440
- const opExportName = spec.opExportName ?? lowerFirst;
441
-
442
- // 1. Operations — synthesize named Request/Response for Unit I/O so every
443
- // operation has an input shape that can carry operation-level traits.
444
- const operations = collectOperations(shapes);
445
- const httpFor: Record<string, any> = {}; // input shape id → http trait
446
- const opTraitsFor: Record<string, Record<string, unknown>> = {}; // input shape id → op traits
447
- const ns = modelNamespace(operations, shapes, spec.namespaceFallback ?? "smithy.unknown");
448
-
449
- const selected: OpEntry[] = [];
450
- for (const op of operations) {
451
- selected.push(op);
452
-
453
- const { input, output } = ensureNamedIo(shapes, op, ns);
454
- op.def.__input = input;
455
- op.def.__output = output;
456
-
457
- const http = op.def.traits?.["smithy.api#http"];
458
- if (http) httpFor[input] = http;
459
- if (op.def.traits) opTraitsFor[input] = op.def.traits;
460
- }
461
-
462
- if (selected.length === 0) return { code: "", operations: 0 };
463
-
464
- // 2. Reachability + dependencies-first order (cycles suspend at refs).
465
- const roots = [
466
- ...selected.flatMap((op) => [op.def.__input, op.def.__output]),
467
- ...(spec.extraRoots?.(selected, shapes) ?? []),
468
- ];
469
- const reachable = reachableFrom(shapes, roots, shapeDeps);
470
- const order = topoOrder(shapes, reachable, shapeDeps);
471
- const indexOf = orderIndex(order);
472
-
473
- /**
474
- * Shape id → the id whose emitted body it shares.
475
- *
476
- * Structural aliasing (see the struct emission below) has to cascade: a
477
- * parent only matches another parent if their MEMBERS render identically,
478
- * and a member renders as its target's name. So every reference resolves
479
- * through this map first — once `…ItemGroupRuleGroup` is aliased onto a
480
- * canonical shape, the parents referencing it start rendering the same
481
- * text and collapse in turn.
482
- *
483
- * Filled in topological order, so a canonical target is always a shape
484
- * that was already emitted — a back-reference, never a forward one.
485
- */
486
- const canonicalId = new Map<string, string>();
487
- const canon = (target: string): string => canonicalId.get(target) ?? target;
488
-
489
- const rawRef = makeSchemaRef(prelude, indexOf);
490
- const rawTsRef = makeTsRef(tsPrelude);
491
- const ref = (target: string, selfIdx: number) => rawRef(canon(target), selfIdx);
492
- const tsRef = (target: string) => rawTsRef(canon(target));
493
-
494
- // Direction classification for enum openness. Enum ALIASES are emitted
495
- // CLOSED (exhaustively matchable on reads); request-reachable shapes
496
- // re-open enum references inline (`X | (string & {})`) so consumers can
497
- // send tomorrow's values without an SDK update.
498
- const requestReachable = reachableFrom(
499
- shapes,
500
- selected.map((op) => op.def.__input),
501
- shapeDeps,
502
- );
503
- // Discriminant enums: single-value enums required by a union-arm
504
- // structure (e.g. the worker binding `type: "ai"` literals). These stay
505
- // CLOSED even on the request side — consumers and the union's TS
506
- // narrowing rely on the exact literal (v0 parity).
507
- const discriminantEnums = new Set<string>();
508
- for (const d of Object.values(shapes) as any[]) {
509
- if (d?.type !== "union") continue;
510
- for (const um of Object.values(d.members ?? {}) as any[]) {
511
- const arm = shapes[um.target];
512
- if (arm?.type !== "structure") continue;
513
- for (const am of Object.values(arm.members ?? {}) as any[]) {
514
- const t = shapes[am.target];
515
- if (
516
- (t?.type === "enum" || t?.type === "intEnum") &&
517
- Object.keys(t.members ?? {}).length === 1 &&
518
- am.traits?.["smithy.api#required"] !== undefined
519
- ) {
520
- discriminantEnums.add(am.target);
521
- }
522
- }
523
- }
524
- }
525
- /**
526
- * TS reference with direction-aware enum openness. Any reference inside a
527
- * request-reachable shape re-opens the enum inline — including shapes
528
- * shared with responses (a value you can SEND must accept undocumented
529
- * members, and response runtime is open regardless). References inside
530
- * pure response/error shapes stay the plain closed alias, and so do
531
- * union-arm discriminant literals.
532
- */
533
- const tsRefAt = (rawTarget: string, ownerId: string): string => {
534
- const target = canon(rawTarget);
535
- const base = tsRef(target);
536
- if (!requestReachable.has(ownerId)) return base;
537
- if (discriminantEnums.has(target)) return base;
538
- const d = shapes[target];
539
- if (d?.type === "enum") return `${base} | (string & {})`;
540
- if (d?.type === "intEnum") return `${base} | (number & {})`;
541
- return base;
542
- };
543
-
544
- const wireKind =
545
- spec.wireKind ??
546
- ((b: MemberBinding): "label" | "query" | "header" | "other" =>
547
- b === "label" ? "label" : b === "query" ? "query" : b === "header" ? "header" : "other");
548
-
549
- // The generic binding cascade; provider bindings slot in after headers.
550
- const extraBindingOf = (traits: Record<string, any>): MemberBinding | undefined => {
551
- for (const b of spec.extraBindings ?? []) {
552
- if (b.trait in traits) return b.binding;
553
- }
554
- return undefined;
555
- };
556
- const bindingOf = (traits: Record<string, any>): MemberBinding =>
557
- "smithy.api#httpLabel" in traits
558
- ? "label"
559
- : "smithy.api#httpQuery" in traits
560
- ? "query"
561
- : "smithy.api#httpHeader" in traits
562
- ? "header"
563
- : (extraBindingOf(traits) ?? ("smithy.api#httpPayload" in traits ? "rawBody" : "body"));
564
-
565
- // Shapes reachable from any response/error root — used to scope the
566
- // blanket-nullable-optionals rule to reads (the wire returns explicit
567
- // nulls; requests only accept null where a nullable trait says so).
568
- const responseReachable =
569
- spec.optionalsNullable === true
570
- ? reachableFrom(
571
- shapes,
572
- [...selected.map((op) => op.def.__output), ...collectOpErrorIds(selected, shapes)],
573
- shapeDeps,
574
- )
575
- : undefined;
576
-
577
- const memberInfos = (d: any, ownerId?: string): EmittedMember[] =>
578
- memberBases(d, memberName).map((base) => {
579
- const traits = base.traits;
580
- const binding = bindingOf(traits);
581
- return {
582
- ...base,
583
- binding,
584
- wire: smithyWireName(traits, base.name, wireKind(binding)),
585
- nullable:
586
- (spec.nullableTrait ? spec.nullableTrait in traits : false) ||
587
- // Blanket-nullable optionals (v0 surface): every optional BODY
588
- // member of a response-reachable shape accepts/announces null
589
- // in addition to being omittable.
590
- (responseReachable !== undefined &&
591
- ownerId !== undefined &&
592
- responseReachable.has(ownerId) &&
593
- !base.required &&
594
- binding === "body"),
595
- };
596
- });
597
-
598
- /** The single value a one-value enum shape fixes, if `target` is one. */
599
- const soleEnumValue = (target: string): string | undefined => {
600
- const d = shapes[target];
601
- if (d?.type !== "enum") return undefined;
602
- const values = Object.values(d.members ?? {}).map(
603
- (m: any) => m.traits?.["smithy.api#enumValue"],
604
- );
605
- return values.length === 1 && typeof values[0] === "string" ? values[0] : undefined;
606
- };
607
-
608
- /**
609
- * The member every case of a union pins to a different literal — the tag
610
- * the API itself discriminates by (`type: "zone"`, `id: "browser_check"`).
611
- * Undefined unless every case is a structure carrying that member and no
612
- * two cases claim the same value.
613
- */
614
- const unionDiscriminator = (
615
- caseTargets: readonly string[],
616
- ): { key: string; values: string[] } | undefined => {
617
- if (caseTargets.length < 2) return undefined;
618
- const perCase = caseTargets.map((t) => {
619
- const cd = shapes[t];
620
- if (cd?.type !== "structure") return undefined;
621
- const tags = new Map<string, string>();
622
- for (const mi of memberInfos(cd)) {
623
- const value = soleEnumValue(mi.target);
624
- if (value !== undefined) tags.set(mi.tsName, value);
625
- }
626
- return tags;
627
- });
628
- if (perCase.some((tags) => tags === undefined || tags.size === 0)) {
629
- return undefined;
630
- }
631
- for (const key of perCase[0]!.keys()) {
632
- const values = perCase.map((tags) => tags!.get(key));
633
- if (values.some((v) => v === undefined)) continue;
634
- if (new Set(values).size !== values.length) continue;
635
- return { key, values: values as string[] };
636
- }
637
- return undefined;
638
- };
639
-
640
- // Generic pipes for the smithy bindings (the SDK's traits module exports
641
- // core's Label/Query/Header/HttpBody/Body builders under these names);
642
- // provider bindings and member traits append theirs via memberExtraPipes.
643
- const genericPipes = (info: EmittedMember): string[] => {
644
- switch (info.binding) {
645
- case "label":
646
- return [info.wire === info.tsName ? "T.Label()" : `T.Label(${q(info.wire)})`];
647
- case "query":
648
- return [info.wire === info.tsName ? "T.Query()" : `T.Query(${q(info.wire)})`];
649
- case "header":
650
- return [info.wire === info.tsName ? "T.Header()" : `T.Header(${q(info.wire)})`];
651
- case "rawBody":
652
- return ["T.HttpBody()"];
653
- case "body":
654
- return info.wire !== info.tsName ? [`T.Body(${q(info.wire)})`] : [];
655
- default:
656
- return [];
657
- }
658
- };
659
-
660
- const memberPipes =
661
- spec.memberPipes ??
662
- ((info: EmittedMember) => [
663
- ...genericPipes(info),
664
- // The binding table's pipe (envelope payloads, file uploads, …).
665
- ...(spec.extraBindings ?? [])
666
- .filter((b) => b.binding === info.binding && b.trait in info.traits)
667
- .map((b) => b.pipe),
668
- // Trait-table pipes: trait value JSON-inlined as the argument.
669
- ...Object.entries(spec.memberTraitPipes ?? {})
670
- .filter(([trait]) => info.traits[trait] !== undefined)
671
- .map(([trait, builder]) => `${builder}(${JSON.stringify(info.traits[trait])})`),
672
- ...(STRING_ENCODED_TRAIT in info.traits ? ["T.StringEncoded()"] : []),
673
- ...(spec.memberExtraPipes?.(info) ?? []),
674
- ]);
675
-
676
- const memberTsTypeOf = (
677
- info: EmittedMember,
678
- tsRefFn: (target: string) => string,
679
- ): string | undefined =>
680
- spec.memberTsType?.(info, tsRefFn) ??
681
- (spec.extraBindings ?? []).find((b) => b.binding === info.binding && b.tsType !== undefined)
682
- ?.tsType;
683
-
684
- const emitMember = (info: EmittedMember, selfIdx: number): string => {
685
- let expr =
686
- spec.memberSchema?.(info, (target) => ref(target, selfIdx)) ?? ref(info.target, selfIdx);
687
- if (info.nullable) expr = `S.NullOr(${expr})`;
688
- const pipes = memberPipes(info);
689
- if (pipes.length) expr = `${expr}.pipe(${pipes.join(", ")})`;
690
- if (!info.required) expr = `S.optional(${expr})`;
691
- return ` ${q(info.tsName)}: ${expr},`;
692
- };
693
-
694
- const opIoShapes = new Set<string>();
695
- for (const op of selected) {
696
- opIoShapes.add(op.def.__input);
697
- opIoShapes.add(op.def.__output);
698
- }
699
-
700
- // 3. Validate pagination traits: a paginated op must actually carry its
701
- // token on the input and its items member on the output, else it
702
- // degrades to a plain operation.
703
- const paginatedOutputs = new Set<string>();
704
- const paginatedItemsRoot = new Map<string, string>();
705
- /** Op id → its full (possibly dotted) items path, `""` when it has none. */
706
- const paginatedItemsPath = new Map<string, string>();
707
- /** Output shape id → the pagination profile that decodes it. */
708
- const outputProfile = new Map<string, PaginationProfile>();
709
- /** Op id → its pagination profile (drives protocol/strategy emission). */
710
- const opProfile = new Map<string, PaginationProfile>();
711
- const usedProfiles = new Set<PaginationProfile>();
712
- const profileNames = Object.keys(spec.paginationProfiles ?? {});
713
- if (profileNames.length > 0) {
714
- for (const op of selected) {
715
- const pg = op.def.traits?.[PAGINATED_TRAIT];
716
- if (!pg) continue;
717
- // Which profile decodes this op's pages: the selector's answer, or
718
- // the sole declared profile.
719
- const profileName =
720
- spec.paginationProfileFor?.(pg, op) ??
721
- (profileNames.length === 1 ? profileNames[0] : undefined);
722
- const profile = profileName ? spec.paginationProfiles![profileName] : undefined;
723
- if (!profile) continue;
724
- const inNames = new Set(memberInfos(shapes[op.def.__input] ?? {}).map((m) => m.tsName));
725
- const outNames = new Set(memberInfos(shapes[op.def.__output] ?? {}).map((m) => m.tsName));
726
- const { ok, itemsRoot } = validatePaginated({
727
- trait: pg,
728
- inputNames: inNames,
729
- outputNames: outNames,
730
- itemsFallback: profile.itemsFallback,
731
- syntheticOutputs: new Set(profile.syntheticOutputs ?? []),
732
- });
733
- if (ok) {
734
- op.def.__pagination = pg;
735
- paginatedOutputs.add(op.def.__output);
736
- paginatedItemsRoot.set(op.def.__output, itemsRoot);
737
- paginatedItemsPath.set(op.id, String(pg.items ?? profile.itemsFallback ?? ""));
738
- outputProfile.set(op.def.__output, profile);
739
- opProfile.set(op.id, profile);
740
- usedProfiles.add(profile);
741
- }
742
- }
743
- }
744
-
745
- // 4. Error classes from the operations' errors lists.
746
- const out: string[] = [];
747
- // Emitted struct body → the name that owns it, for structural aliasing.
748
- // Keyed on the emitted TEXT, so two shapes collapse only when what they
749
- // would emit is byte-identical — including member names, targets, docs and
750
- // pipes. References are already resolved to names at this point, so a
751
- // difference anywhere in the tree shows up as different text.
752
- const structBodies = new Map<string, { id: string; name: string }>();
753
- // Set when any error carries CATEGORY_TRAIT, so the header only imports
754
- // the category module when something actually uses it.
755
- let usesCategories = false;
756
- const errorIds = collectOpErrorIds(selected, shapes);
757
- const errorIdSet = new Set(errorIds);
758
- const errorNames = new Set(errorIds.map(local));
759
-
760
- const shapeDocs = spec.shapeDocs ?? true;
761
-
762
- for (const id of errorIds) {
763
- const d = shapes[id];
764
- const name = local(id);
765
- const doc = oneLine(d.traits?.["smithy.api#documentation"]);
766
- if (doc && shapeDocs) out.push(`/** ${doc} */`);
767
- const overridden = spec.errors?.override?.({ id, def: d, name });
768
- if (overridden) {
769
- out.push(...overridden);
770
- continue;
771
- }
772
- const errorField =
773
- spec.errors?.field ??
774
- ((mn: string, target: string) => ` ${tsKey(mn)}: ${prelude[local(target)] ?? "S.Unknown"},`);
775
- const fields =
776
- d.members && Object.keys(d.members).length
777
- ? Object.entries(d.members).map(([mn, m]: [string, any]) => errorField(mn, m.target))
778
- : (spec.errors?.defaultFields?.(prelude) ?? [
779
- errorField("code", "smithy.api#Integer"),
780
- errorField("message", "smithy.api#String"),
781
- ]);
782
- const matchers = spec.errorMatchersTrait ? d.traits?.[spec.errorMatchersTrait] : undefined;
783
- const categories = categoryPipes(d.traits);
784
- if (categories.length) usesCategories = true;
785
- out.push(
786
- errorClass({
787
- name,
788
- fields,
789
- pipes: categories.length ? `.pipe(${categories.join(", ")})` : undefined,
790
- wrap:
791
- spec.errors?.wrap?.(d.traits ?? {}) ??
792
- (matchers
793
- ? (cls) => `T.applyErrorMatchers(\n${cls},\n${JSON.stringify(matchers)},\n)`
794
- : undefined),
795
- }),
796
- );
797
- }
798
-
799
- // 5. Every reachable shape in dependency order: explicit TS type next to
800
- // a schema const cast to `S.Schema<T>` (the compile-perf pattern).
801
- order.forEach((id, i) => {
802
- if (errorIdSet.has(id)) return; // emitted as an error class above
803
- const d = shapes[id];
804
- const name = local(id);
805
- const doc = oneLine(d.traits?.["smithy.api#documentation"]);
806
- if (doc && shapeDocs) out.push(`/** ${doc} */`);
807
-
808
- const override = spec.shapeOverride?.({
809
- id,
810
- def: d,
811
- name,
812
- selfIdx: i,
813
- ref,
814
- tsRef,
815
- members: memberInfos,
816
- });
817
- if (override) {
818
- out.push(...override);
819
- return;
820
- }
821
-
822
- if (d.type === "structure") {
823
- // Bare-payload response: single trait-marked member — the response IS
824
- // that member's value; emit its type + a root marker for the protocol.
825
- const memberEntriesAll = Object.entries(d.members ?? {});
826
- const soleMemberRoot =
827
- !paginatedOutputs.has(id) && memberEntriesAll.length === 1
828
- ? (spec.extraBindings ?? []).find(
829
- (b) =>
830
- b.rootPipe !== undefined &&
831
- b.trait in ((memberEntriesAll[0]![1] as any).traits ?? {}),
832
- )
833
- : undefined;
834
- if (soleMemberRoot) {
835
- const [, m] = memberEntriesAll[0]! as [string, any];
836
- // Alias responses are op roots too — they must carry the service
837
- // key dictionary so opaque content (union cases, freeform maps)
838
- // nested in the payload decodes with the same wire mapping as
839
- // struct-form roots.
840
- const rootPipes = [
841
- soleMemberRoot.rootPipe,
842
- ...(spec.rootKeyDictionary && opIoShapes.has(id)
843
- ? [`T.KeyDictionary(KEY_DICTIONARY)`]
844
- : []),
845
- ];
846
- out.push(`export type ${name} = ${tsRef(m.target)};`);
847
- out.push(
848
- suspendConst({
849
- name,
850
- pure,
851
- multiline: true,
852
- annotateIdentifier: true,
853
- castTo: `S.${spec.schemaType ?? "Schema"}<${name}>`,
854
- expr: `${ref(m.target, i)}.pipe(${rootPipes.join(", ")})`,
855
- }),
856
- );
857
- return;
858
- }
859
-
860
- // Paginated outputs always deliver their items member — required.
861
- const itemsRoot = paginatedItemsRoot.get(id);
862
- const infos = memberInfos(d, id).map((info) =>
863
- info.tsName === itemsRoot ? { ...info, required: true } : info,
864
- );
865
- const fields = infos.flatMap((info) =>
866
- interfaceField({
867
- name: info.tsName,
868
- optional: !info.required,
869
- doc: info.doc,
870
- type:
871
- memberTsTypeOf(info, tsRef) ??
872
- `${tsRefAt(info.target, id)}${info.nullable ? " | null" : ""}`,
873
- }),
874
- );
875
- const members = infos.map((info) => emitMember(info, i));
876
- const inject = outputProfile.get(id)?.injectOutputMember;
877
- if (inject && !infos.some((m) => m.tsName === inject.tsName)) {
878
- fields.push(...inject.interfaceLines);
879
- members.push(inject.structLine);
880
- }
881
- const closed = members.length ? `S.Struct({\n${members.join("\n")}\n})` : `S.Struct({})`;
882
- // Open object: keys beyond the declared members are typed `unknown`.
883
- // A typed value (OpenAPI `additionalProperties: {schema}`) would have
884
- // to accept every declared member's type too, so it stays `unknown`.
885
- const open = ADDITIONAL_PROPERTIES_TRAIT in (d.traits ?? {});
886
- if (open) fields.push(` [key: string]: unknown;`);
887
- const struct = open ? `S.StructWithRest(${closed}, [S.Record(S.String, S.Unknown)])` : closed;
888
- const structCtx = {
889
- id,
890
- isOpIo: opIoShapes.has(id),
891
- httpTrait: httpFor[id],
892
- opTraits: opTraitsFor[id],
893
- };
894
- const pipes = spec.structPipes?.(structCtx) ?? [
895
- ...(structCtx.httpTrait ? [`T.Http(${JSON.stringify(structCtx.httpTrait)})`] : []),
896
- ...(spec.rootKeyDictionary && structCtx.isOpIo ? [`T.KeyDictionary(KEY_DICTIONARY)`] : []),
897
- ];
898
- const tail = pipes.map((p) => `.pipe(${p})`).join("");
899
-
900
- // Shapes whose emitted body is byte-identical are one shape wearing
901
- // many names. The docs pipelines generate a fresh copy of every nested
902
- // shape per operation, so cloudflare's zero_trust carries 374 copies of
903
- // `{ group?: unknown }` — one per operation x application type x
904
- // include/exclude/require — and 72% of its 16,800 structures are
905
- // redundant that way.
906
- //
907
- // Emit the body once and alias the rest to it. The public name is kept,
908
- // so nothing about the surface changes; only the duplicate bodies go.
909
- // Operation I/O is excluded: those carry the operation's Http trait and
910
- // must never be merged onto one another.
911
- const bodyKey = `${JSON.stringify(fields)}|${struct}${tail}`;
912
- const canonical = structCtx.isOpIo ? undefined : structBodies.get(bodyKey);
913
- if (canonical !== undefined) {
914
- out.push(`export type ${name} = ${canonical.name};`);
915
- out.push(`export const ${name} = ${canonical.name};\n`);
916
- // Later shapes referencing this one now render the canonical name,
917
- // which is what lets their bodies collapse too.
918
- canonicalId.set(id, canonical.id);
919
- } else {
920
- if (!structCtx.isOpIo) {
921
- structBodies.set(bodyKey, { id, name });
922
- }
923
- out.push(interfaceDecl(name, fields));
924
- out.push(
925
- suspendConst({
926
- name,
927
- pure,
928
- multiline: true,
929
- annotateIdentifier: true,
930
- castTo: `S.${spec.schemaType ?? "Schema"}<${name}>`,
931
- expr: `${struct}${tail}`,
932
- }),
933
- );
934
- }
935
- } else if (d.type === "list") {
936
- const nullable =
937
- spec.nullableTrait !== undefined && spec.nullableTrait in (d.member.traits ?? {});
938
- const item = ref(d.member.target, i);
939
- out.push(
940
- `export type ${name} = Array<${tsRefAt(d.member.target, id)}${nullable ? " | null" : ""}>;`,
941
- );
942
- out.push(
943
- `export const ${name} = ${pure}S.Array(${nullable ? `S.NullOr(${item})` : item}) as any as S.${spec.schemaType ?? "Schema"}<${name}>;\n`,
944
- );
945
- } else if (d.type === "map") {
946
- const nullable =
947
- spec.nullableTrait !== undefined && spec.nullableTrait in (d.value.traits ?? {});
948
- const value = ref(d.value.target, i);
949
- out.push(
950
- `export type ${name} = { [key: string]: ${tsRefAt(d.value.target, id)}${nullable ? " | null" : ""} | undefined };`,
951
- );
952
- out.push(
953
- `export const ${name} = ${pure}S.Record(S.String, ${nullable ? `S.NullOr(${value})` : value}) as any as S.${spec.schemaType ?? "Schema"}<${name}>;\n`,
954
- );
955
- } else if (d.type === "union") {
956
- // A union arm targeting the union itself carries no information
957
- // (`type X = X | A | B` ≡ `A | B`) and is an illegal circular type
958
- // alias. Specs produce them: atlas's OnlineArchiveSchedule is a
959
- // discriminated oneOf whose DEFAULT arm is `allOf: [$ref <the union
960
- // itself>]`, so the arm resolves back to its own parent.
961
- const caseTargets = Object.values(d.members ?? {})
962
- .map((m: any) => m.target)
963
- .filter((t: string) => t !== id);
964
- const caseKeys = caseTargets.map((t: string) => {
965
- const cd = shapes[t];
966
- return cd?.type === "structure" ? memberInfos(cd).map((mi) => mi.tsName) : [];
967
- });
968
- if (spec.union) {
969
- out.push(...spec.union({ name, caseTargets, caseKeys, tsRef }));
970
- } else if (spec.unionStyle === "untagged") {
971
- out.push(
972
- `export type ${name} = ${caseTargets.map((t) => tsRefAt(t, id)).join(" | ") || "never"};`,
973
- `export const ${name} = ${pure}S.Union([${caseTargets.map((t) => ref(t, i)).join(", ")}]) as any as S.${spec.schemaType ?? "Schema"}<${name}>;\n`,
974
- );
975
- } else if (
976
- spec.unionStyle === "primitive" &&
977
- caseTargets.length > 0 &&
978
- caseTargets.every(
979
- (target) =>
980
- ["string", "number", "boolean"].includes(tsRef(target)) ||
981
- shapes[target]?.type === "enum" ||
982
- shapes[target]?.type === "intEnum",
983
- )
984
- ) {
985
- // Primitive unions keep response enums open to match S.String/S.Number.
986
- const primitiveType = (target: string) => {
987
- const type = tsRef(target);
988
- if (shapes[target]?.type === "enum") return `${type} | (string & {})`;
989
- if (shapes[target]?.type === "intEnum") return `${type} | (number & {})`;
990
- return type;
991
- };
992
- out.push(
993
- `export type ${name} = ${caseTargets.map(primitiveType).join(" | ")};`,
994
- `export const ${name}: S.Codec<${name}> = ${pure}S.Union([${caseTargets.map((t) => ref(t, i)).join(", ")}]);\n`,
995
- );
996
- } else if (spec.unionStyle === "opaque-cases") {
997
- const disc = unionDiscriminator(caseTargets);
998
- out.push(
999
- `export type ${name} = ${caseTargets.map((t) => tsRefAt(t, id)).join(" | ") || "unknown"};`,
1000
- `export const ${name} = ${pure}S.Unknown.pipe(T.UnionCases(${JSON.stringify(caseKeys)}${disc ? `, ${JSON.stringify(disc)}` : ""}));\n`,
1001
- );
1002
- } else {
1003
- throw new Error(`no union emission configured for shape ${id} — set unionStyle or union`);
1004
- }
1005
- } else if (d.type === "enum") {
1006
- const values = Object.values(d.members ?? {})
1007
- .map((m: any) => m.traits?.["smithy.api#enumValue"])
1008
- .filter((v: unknown): v is string => typeof v === "string");
1009
- out.push(...enumDecl({ name, values, pure }));
1010
- } else if (d.type === "intEnum") {
1011
- // CLOSED numeric literal union alias (`type Y = 1 | 30`); INPUT
1012
- // references re-open it inline (`Y | (number & {})`). Schema stays
1013
- // S.Number (protocols never validate enum membership).
1014
- const values = Object.values(d.members ?? {})
1015
- .map((m: any) => m.traits?.["smithy.api#enumValue"])
1016
- .filter((v: unknown): v is number => typeof v === "number");
1017
- const union = values.length ? values.join(" | ") : "number";
1018
- out.push(`export type ${name} = ${union};`, `export const ${name} = S.Number;\n`);
1019
- }
1020
- });
1021
-
1022
- // 6. Operations — declarative emission from the names in operationDecl,
1023
- // unless the provider overrides the whole shape.
1024
- /**
1025
- * The element type `.items()` yields, resolved from the pagination
1026
- * trait's items PATH against the response shape.
1027
- *
1028
- * `makePaginated` can't infer this — the path is a runtime string — and
1029
- * the structural `API.PaginatedItem` fallback only recognizes bare arrays
1030
- * and `{ result: […] }` envelopes, so every other envelope degrades to
1031
- * `unknown` (distilled #302). Resolving it here and passing it as an
1032
- * explicit type argument is what makes `.items()` typed.
1033
- *
1034
- * Returns undefined when the path doesn't lead to a list, which leaves
1035
- * the annotation on the structural fallback rather than asserting a type
1036
- * the shape doesn't support.
1037
- */
1038
- const paginatedItemTsType = (outputId: string, itemsPath: string): string | undefined => {
1039
- // No items path: `.items()` is a page passthrough at runtime, so an
1040
- // item IS a whole response.
1041
- if (!itemsPath) return tsRef(outputId);
1042
- let id: string = outputId;
1043
- // Whether the path crossed a list on the way down (`"edges.node"` on a
1044
- // Relay connection). When it did, the path itself is what fans out, so
1045
- // the value it lands on IS one item — it needn't be a list again.
1046
- let fannedOut = false;
1047
- for (const segment of itemsPath.split(".")) {
1048
- let def: any = shapes[id];
1049
- if (def?.type === "list") {
1050
- id = def.member.target as string;
1051
- def = shapes[id];
1052
- fannedOut = true;
1053
- }
1054
- if (def?.type !== "structure") return undefined;
1055
- const info = memberInfos(def).find((m) => m.tsName === segment);
1056
- if (!info) return undefined;
1057
- id = info.target;
1058
- }
1059
- const last: any = shapes[id];
1060
- if (last?.type === "list") return tsRef(last.member.target);
1061
- return fannedOut ? tsRef(id) : undefined;
1062
- };
1063
-
1064
- const usedProtocols = new Set<string>();
1065
- const emitOperation =
1066
- spec.operation ??
1067
- ((ctx: OperationEmit): string => {
1068
- const decl = spec.operationDecl;
1069
- if (!decl) {
1070
- throw new Error("SdkSpec needs either operationDecl or operation");
1071
- }
1072
- const errList = [...ctx.errorNames, ...decl.commonErrorClasses];
1073
- const overrides = decl.overrides?.(ctx);
1074
- const contextType = overrides?.contextType ?? decl.contextType;
1075
- const paginated = ctx.pagination !== undefined;
1076
- const itemTsType = paginated
1077
- ? paginatedItemTsType(ctx.op.def.__output, paginatedItemsPath.get(ctx.op.id) ?? "")
1078
- : undefined;
1079
- const typeAnnotation =
1080
- `API.${paginated ? "PaginatedOperationMethod" : "OperationMethod"}<\n` +
1081
- ` ${ctx.inputName},\n` +
1082
- ` ${ctx.outputTsType},\n` +
1083
- ` ${ctx.opName}Error,\n` +
1084
- ` ${contextType}` +
1085
- (itemTsType ? `,\n ${itemTsType}\n` : `\n`) +
1086
- `>`;
1087
- const protocol =
1088
- (paginated && opProfile.get(ctx.op.id)?.protocol) || overrides?.protocol || decl.protocol;
1089
- usedProtocols.add(protocol);
1090
- const config =
1091
- `{\n` +
1092
- ` input: ${ctx.inputName},\n` +
1093
- ` output: ${ctx.outputSchema},\n` +
1094
- ` errors: [${errList.join(", ")}],\n` +
1095
- ` protocol: ${protocol},\n` +
1096
- (decl.retry ? ` retry: ${decl.retry},\n` : "") +
1097
- (decl.extraConfig?.(ctx) ?? []).map((l) => ` ${l},\n`).join("") +
1098
- (paginated ? ` pagination: ${JSON.stringify(ctx.pagination)} as const,\n` : "") +
1099
- `}`;
1100
- return [
1101
- errorUnionAlias(ctx.opName, ctx.errorNames, decl.commonErrorType),
1102
- ...(ctx.doc ? [`/** ${ctx.doc} */`] : []),
1103
- operationConst({
1104
- exportName: ctx.exportName,
1105
- typeAnnotation,
1106
- factory: paginated ? "API.makePaginated" : "API.make",
1107
- pure,
1108
- extraArg: paginated ? opProfile.get(ctx.op.id)?.strategy : undefined,
1109
- config,
1110
- // `makePaginated` infers the items element from the structural
1111
- // fallback; an explicit item type needs the same `as any as`
1112
- // idiom the schema consts use.
1113
- castToAnnotation: itemTsType !== undefined,
1114
- }),
1115
- ].join("\n");
1116
- });
1117
-
1118
- for (const op of selected) {
1119
- const opName = local(op.id);
1120
- const errNames = ((op.def.errors ?? []) as Array<{ target: string }>)
1121
- .map((e) => local(e.target))
1122
- .filter((n) => errorNames.has(n));
1123
- out.push(
1124
- emitOperation({
1125
- op,
1126
- opName,
1127
- exportName: opExportName(opName),
1128
- inputName: local(op.def.__input),
1129
- outputName: local(op.def.__output),
1130
- outputTsType: tsRef(op.def.__output),
1131
- outputSchema: ref(op.def.__output, indexOf.size),
1132
- errorNames: errNames,
1133
- doc: oneLine(op.def.traits?.["smithy.api#documentation"]),
1134
- pagination: op.def.__pagination,
1135
- }),
1136
- );
1137
- }
1138
-
1139
- // 7. Alias re-exports, then provider trailing sections.
1140
- const emittedOps = new Set(selected.map((op) => opExportName(local(op.id))));
1141
- for (const { alias, target } of spec.opAliases ?? []) {
1142
- if (!emittedOps.has(target) || emittedOps.has(alias)) continue;
1143
- emittedOps.add(alias);
1144
- const A = upperFirst(alias);
1145
- const T2 = upperFirst(target);
1146
- out.push(
1147
- `// Alias of ${target} (same route, alternate export name upstream).\n` +
1148
- `export const ${alias} = ${target};\n` +
1149
- `export type ${A}Request = ${T2}Request;\n` +
1150
- `export type ${A}Response = ${T2}Response;\n` +
1151
- `export type ${A}Error = ${T2}Error;\n`,
1152
- );
1153
- }
1154
- if (spec.footer) {
1155
- out.push(...spec.footer({ emittedOps }));
1156
- }
1157
-
1158
- // Default header: banner + imports derived from operationDecl names and
1159
- // the conventional SDK module layout, op error/context type re-exports,
1160
- // and the KEY_DICTIONARY const when configured.
1161
- const defaultHeader = (ctx: { hasPaginated: boolean }): string => {
1162
- const decl = spec.operationDecl;
1163
- if (!decl) {
1164
- throw new Error("the default header needs operationDecl — or pass header");
1165
- }
1166
- const retryNs = decl.retry?.split(".")[0];
1167
- // Imports the used pagination profiles pull in: their protocol consts
1168
- // (from the protocol module) and strategy/injected-member names (from
1169
- // the pagination module).
1170
- const profileProtocols = [
1171
- ...new Set(
1172
- [...usedProfiles]
1173
- .map((p) => p.protocol)
1174
- .filter((p): p is string => p !== undefined && p !== decl.protocol),
1175
- ),
1176
- ];
1177
- const pagImports = [
1178
- ...new Set(
1179
- [...usedProfiles].flatMap((p) => [
1180
- ...(p.strategy ? [p.strategy] : []),
1181
- ...(p.injectOutputMember?.imports ?? []),
1182
- ]),
1183
- ),
1184
- ];
1185
- return (
1186
- `// AUTO-GENERATED by scripts/generate.ts${
1187
- spec.sourceNote ? ` from ${spec.sourceNote}` : ""
1188
- }. Do not edit.\n` +
1189
- // Lite schemas: Effect Schema is bundled only with ResponseValidation.strict.
1190
- `import * as S from "@distilled.cloud/core/schema-lite";\n` +
1191
- `import * as API from "@distilled.cloud/core/api";\n` +
1192
- (usesCategories ? `import * as C from "@distilled.cloud/core/category";\n` : "") +
1193
- `import * as T from "../traits.ts";\n` +
1194
- `import {\n` +
1195
- (spec.operation || usedProtocols.has(decl.protocol) ? ` ${decl.protocol},\n` : "") +
1196
- profileProtocols.map((p) => ` ${p},\n`).join("") +
1197
- ` type ${decl.commonErrorType},\n` +
1198
- ` type ${decl.contextType},\n` +
1199
- `} from "../protocol.ts";\n` +
1200
- (ctx.hasPaginated && pagImports.length
1201
- ? `import { ${pagImports.join(", ")} } from "../pagination.ts";\n`
1202
- : "") +
1203
- (decl.commonErrorClasses.length
1204
- ? `import { ${[...decl.commonErrorClasses].sort().join(", ")} } from "../errors.ts";\n`
1205
- : "") +
1206
- (retryNs ? `import * as ${retryNs} from "../retry.ts";\n\n` : "\n") +
1207
- // Re-exported so inferred provider types downstream can always name them.
1208
- `export type { ${decl.commonErrorType}, ${decl.contextType} };\n\n` +
1209
- (spec.rootKeyDictionary
1210
- ? `/** ${spec.rootKeyDictionary.doc} */\n` +
1211
- `const KEY_DICTIONARY: Record<string, string | ReadonlyArray<string>> = ${JSON.stringify(spec.rootKeyDictionary.dict)};\n\n`
1212
- : "")
1213
- );
1214
- };
1215
-
1216
- const header = (spec.header ?? defaultHeader)({
1217
- hasPaginated: paginatedOutputs.size > 0,
1218
- model,
1219
- });
1220
- const code = header + out.join("\n") + "\n";
1221
- return {
1222
- code: spec.postProcess?.(code) ?? code,
1223
- operations: selected.length,
1224
- };
1225
- };
1226
-
1227
- // Re-exported so provider specs can be written against the same helpers the
1228
- // driver uses, without importing every codegen module individually.
1229
- export { errorUnionAlias, operationConst, upperFirst, tsKey, q, local };