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

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 (259) 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/rest.js +1 -1
  6. package/lib/_bundle/rest.js.map +1 -1
  7. package/lib/annotations.d.ts +15 -0
  8. package/lib/annotations.d.ts.map +1 -0
  9. package/lib/annotations.js +2 -0
  10. package/lib/annotations.js.map +1 -0
  11. package/lib/api.d.ts +15 -0
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -1
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/config.d.ts +54 -13
  16. package/lib/config.d.ts.map +1 -1
  17. package/lib/config.js +1 -1
  18. package/lib/debug.d.ts.map +1 -1
  19. package/lib/error-category.d.ts.map +1 -1
  20. package/lib/errors.d.ts +2 -13
  21. package/lib/errors.d.ts.map +1 -1
  22. package/lib/errors.js +1 -1
  23. package/lib/graphql.d.ts +14 -0
  24. package/lib/graphql.d.ts.map +1 -1
  25. package/lib/index.d.ts +3 -2
  26. package/lib/index.d.ts.map +1 -1
  27. package/lib/index.js +1 -0
  28. package/lib/pagination.d.ts +34 -2
  29. package/lib/pagination.d.ts.map +1 -1
  30. package/lib/pagination.js +1 -1
  31. package/lib/protocol-http.d.ts +30 -6
  32. package/lib/protocol-http.d.ts.map +1 -1
  33. package/lib/protocol-http.js +1 -1
  34. package/lib/protocol-rest.d.ts +53 -39
  35. package/lib/protocol-rest.d.ts.map +1 -1
  36. package/lib/protocol-rest.js +1 -1
  37. package/lib/response-validation.d.ts +4 -3
  38. package/lib/response-validation.d.ts.map +1 -1
  39. package/lib/schema-lite-typed.js +1 -2
  40. package/lib/telemetry-debug.d.ts +14 -0
  41. package/lib/telemetry-debug.d.ts.map +1 -0
  42. package/lib/telemetry-debug.js +2 -0
  43. package/lib/telemetry-debug.js.map +1 -0
  44. package/lib/telemetry-hooks.d.ts +32 -0
  45. package/lib/telemetry-hooks.d.ts.map +1 -0
  46. package/lib/telemetry-hooks.js +2 -0
  47. package/lib/telemetry-hooks.js.map +1 -0
  48. package/lib/telemetry-host-rules.d.ts +23 -0
  49. package/lib/telemetry-host-rules.d.ts.map +1 -0
  50. package/lib/telemetry-host-rules.js +2 -0
  51. package/lib/telemetry-host-rules.js.map +1 -0
  52. package/lib/telemetry-lambda-context.d.ts +17 -0
  53. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  54. package/lib/telemetry-lambda-context.js +2 -0
  55. package/lib/telemetry-lambda-context.js.map +1 -0
  56. package/lib/telemetry-message-context.d.ts +52 -0
  57. package/lib/telemetry-message-context.d.ts.map +1 -0
  58. package/lib/telemetry-message-context.js +2 -0
  59. package/lib/telemetry-message-context.js.map +1 -0
  60. package/lib/telemetry-metrics.d.ts +6 -0
  61. package/lib/telemetry-metrics.d.ts.map +1 -0
  62. package/lib/telemetry-metrics.js +2 -0
  63. package/lib/telemetry-metrics.js.map +1 -0
  64. package/lib/telemetry-name-template.d.ts +13 -0
  65. package/lib/telemetry-name-template.d.ts.map +1 -0
  66. package/lib/telemetry-name-template.js +2 -0
  67. package/lib/telemetry-name-template.js.map +1 -0
  68. package/lib/telemetry-stream.d.ts +9 -0
  69. package/lib/telemetry-stream.d.ts.map +1 -0
  70. package/lib/telemetry-stream.js +2 -0
  71. package/lib/telemetry-stream.js.map +1 -0
  72. package/lib/telemetry-xray.d.ts +28 -0
  73. package/lib/telemetry-xray.d.ts.map +1 -0
  74. package/lib/telemetry-xray.js +2 -0
  75. package/lib/telemetry-xray.js.map +1 -0
  76. package/lib/telemetry.d.ts +269 -0
  77. package/lib/telemetry.d.ts.map +1 -0
  78. package/lib/telemetry.js +3 -0
  79. package/lib/telemetry.js.map +1 -0
  80. package/package.json +1 -3
  81. package/src/annotations.ts +37 -0
  82. package/src/api.ts +123 -24
  83. package/src/category.ts +21 -22
  84. package/src/config.ts +58 -29
  85. package/src/debug.ts +9 -6
  86. package/src/error-category.ts +12 -14
  87. package/src/errors.ts +7 -7
  88. package/src/graphql.ts +123 -18
  89. package/src/index.ts +3 -2
  90. package/src/pagination.ts +119 -6
  91. package/src/protocol-http.ts +63 -43
  92. package/src/protocol-rest.ts +201 -140
  93. package/src/response-validation.ts +4 -3
  94. package/src/telemetry-debug.ts +135 -0
  95. package/src/telemetry-hooks.ts +33 -0
  96. package/src/telemetry-host-rules.ts +39 -0
  97. package/src/telemetry-lambda-context.ts +46 -0
  98. package/src/telemetry-message-context.ts +170 -0
  99. package/src/telemetry-metrics.ts +69 -0
  100. package/src/telemetry-name-template.ts +26 -0
  101. package/src/telemetry-stream.ts +91 -0
  102. package/src/telemetry-xray.ts +66 -0
  103. package/src/telemetry.ts +768 -0
  104. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  105. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  106. package/lib/codegen/boolean-string-enums.js +0 -147
  107. package/lib/codegen/boolean-string-enums.js.map +0 -1
  108. package/lib/codegen/chunk.d.ts +0 -7
  109. package/lib/codegen/chunk.d.ts.map +0 -1
  110. package/lib/codegen/chunk.js +0 -139
  111. package/lib/codegen/chunk.js.map +0 -1
  112. package/lib/codegen/cli.d.ts +0 -80
  113. package/lib/codegen/cli.d.ts.map +0 -1
  114. package/lib/codegen/cli.js +0 -166
  115. package/lib/codegen/cli.js.map +0 -1
  116. package/lib/codegen/datafy.d.ts +0 -14
  117. package/lib/codegen/datafy.d.ts.map +0 -1
  118. package/lib/codegen/datafy.js +0 -853
  119. package/lib/codegen/datafy.js.map +0 -1
  120. package/lib/codegen/dedupe.d.ts +0 -5
  121. package/lib/codegen/dedupe.d.ts.map +0 -1
  122. package/lib/codegen/dedupe.js +0 -153
  123. package/lib/codegen/dedupe.js.map +0 -1
  124. package/lib/codegen/emit.d.ts +0 -125
  125. package/lib/codegen/emit.d.ts.map +0 -1
  126. package/lib/codegen/emit.js +0 -99
  127. package/lib/codegen/emit.js.map +0 -1
  128. package/lib/codegen/format.d.ts +0 -11
  129. package/lib/codegen/format.d.ts.map +0 -1
  130. package/lib/codegen/format.js +0 -32
  131. package/lib/codegen/format.js.map +0 -1
  132. package/lib/codegen/generated-at.d.ts +0 -29
  133. package/lib/codegen/generated-at.d.ts.map +0 -1
  134. package/lib/codegen/generated-at.js +0 -78
  135. package/lib/codegen/generated-at.js.map +0 -1
  136. package/lib/codegen/generator.d.ts +0 -353
  137. package/lib/codegen/generator.d.ts.map +0 -1
  138. package/lib/codegen/generator.js +0 -810
  139. package/lib/codegen/generator.js.map +0 -1
  140. package/lib/codegen/graph.d.ts +0 -36
  141. package/lib/codegen/graph.d.ts.map +0 -1
  142. package/lib/codegen/graph.js +0 -136
  143. package/lib/codegen/graph.js.map +0 -1
  144. package/lib/codegen/graphql-client.d.ts +0 -70
  145. package/lib/codegen/graphql-client.d.ts.map +0 -1
  146. package/lib/codegen/graphql-client.js +0 -439
  147. package/lib/codegen/graphql-client.js.map +0 -1
  148. package/lib/codegen/graphql.d.ts +0 -207
  149. package/lib/codegen/graphql.d.ts.map +0 -1
  150. package/lib/codegen/graphql.js +0 -786
  151. package/lib/codegen/graphql.js.map +0 -1
  152. package/lib/codegen/latin1.d.ts +0 -3
  153. package/lib/codegen/latin1.d.ts.map +0 -1
  154. package/lib/codegen/latin1.js +0 -126
  155. package/lib/codegen/latin1.js.map +0 -1
  156. package/lib/codegen/members.d.ts +0 -32
  157. package/lib/codegen/members.d.ts.map +0 -1
  158. package/lib/codegen/members.js +0 -62
  159. package/lib/codegen/members.js.map +0 -1
  160. package/lib/codegen/model-diff.d.ts +0 -10
  161. package/lib/codegen/model-diff.d.ts.map +0 -1
  162. package/lib/codegen/model-diff.js +0 -67
  163. package/lib/codegen/model-diff.js.map +0 -1
  164. package/lib/codegen/naming.d.ts +0 -29
  165. package/lib/codegen/naming.d.ts.map +0 -1
  166. package/lib/codegen/naming.js +0 -74
  167. package/lib/codegen/naming.js.map +0 -1
  168. package/lib/codegen/openapi-cli.d.ts +0 -52
  169. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  170. package/lib/codegen/openapi-cli.js +0 -84
  171. package/lib/codegen/openapi-cli.js.map +0 -1
  172. package/lib/codegen/openapi.d.ts +0 -209
  173. package/lib/codegen/openapi.d.ts.map +0 -1
  174. package/lib/codegen/openapi.js +0 -1548
  175. package/lib/codegen/openapi.js.map +0 -1
  176. package/lib/codegen/operations.d.ts +0 -24
  177. package/lib/codegen/operations.d.ts.map +0 -1
  178. package/lib/codegen/operations.js +0 -56
  179. package/lib/codegen/operations.js.map +0 -1
  180. package/lib/codegen/pagination.d.ts +0 -39
  181. package/lib/codegen/pagination.d.ts.map +0 -1
  182. package/lib/codegen/pagination.js +0 -31
  183. package/lib/codegen/pagination.js.map +0 -1
  184. package/lib/codegen/patch-audit.d.ts +0 -84
  185. package/lib/codegen/patch-audit.d.ts.map +0 -1
  186. package/lib/codegen/patch-audit.js +0 -366
  187. package/lib/codegen/patch-audit.js.map +0 -1
  188. package/lib/codegen/patches.d.ts +0 -129
  189. package/lib/codegen/patches.d.ts.map +0 -1
  190. package/lib/codegen/patches.js +0 -472
  191. package/lib/codegen/patches.js.map +0 -1
  192. package/lib/codegen/prelude.d.ts +0 -15
  193. package/lib/codegen/prelude.d.ts.map +0 -1
  194. package/lib/codegen/prelude.js +0 -60
  195. package/lib/codegen/prelude.js.map +0 -1
  196. package/lib/codegen/privatize.d.ts +0 -21
  197. package/lib/codegen/privatize.d.ts.map +0 -1
  198. package/lib/codegen/privatize.js +0 -176
  199. package/lib/codegen/privatize.js.map +0 -1
  200. package/lib/codegen/proto.d.ts +0 -121
  201. package/lib/codegen/proto.d.ts.map +0 -1
  202. package/lib/codegen/proto.js +0 -960
  203. package/lib/codegen/proto.js.map +0 -1
  204. package/lib/codegen/pure.d.ts +0 -6
  205. package/lib/codegen/pure.d.ts.map +0 -1
  206. package/lib/codegen/pure.js +0 -91
  207. package/lib/codegen/pure.js.map +0 -1
  208. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  209. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  210. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  211. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  212. package/lib/codegen/spec-path.d.ts +0 -16
  213. package/lib/codegen/spec-path.d.ts.map +0 -1
  214. package/lib/codegen/spec-path.js +0 -101
  215. package/lib/codegen/spec-path.js.map +0 -1
  216. package/lib/codegen/table.d.ts +0 -5
  217. package/lib/codegen/table.d.ts.map +0 -1
  218. package/lib/codegen/table.js +0 -249
  219. package/lib/codegen/table.js.map +0 -1
  220. package/lib/json-patch.d.ts +0 -58
  221. package/lib/json-patch.d.ts.map +0 -1
  222. package/lib/json-patch.js +0 -2
  223. package/lib/json-patch.js.map +0 -1
  224. package/lib/schema-lite-typed.js.map +0 -1
  225. package/lib/testing.d.ts +0 -40
  226. package/lib/testing.d.ts.map +0 -1
  227. package/lib/testing.js +0 -2
  228. package/lib/testing.js.map +0 -1
  229. package/src/codegen/boolean-string-enums.ts +0 -155
  230. package/src/codegen/chunk.ts +0 -147
  231. package/src/codegen/cli.ts +0 -293
  232. package/src/codegen/datafy.ts +0 -874
  233. package/src/codegen/dedupe.ts +0 -173
  234. package/src/codegen/emit.ts +0 -200
  235. package/src/codegen/format.ts +0 -49
  236. package/src/codegen/generated-at.ts +0 -88
  237. package/src/codegen/generator.ts +0 -1229
  238. package/src/codegen/graph.ts +0 -151
  239. package/src/codegen/graphql-client.ts +0 -545
  240. package/src/codegen/graphql.ts +0 -1145
  241. package/src/codegen/latin1.ts +0 -131
  242. package/src/codegen/members.ts +0 -79
  243. package/src/codegen/model-diff.ts +0 -67
  244. package/src/codegen/naming.ts +0 -85
  245. package/src/codegen/openapi-cli.ts +0 -141
  246. package/src/codegen/openapi.ts +0 -1845
  247. package/src/codegen/operations.ts +0 -73
  248. package/src/codegen/pagination.ts +0 -64
  249. package/src/codegen/patch-audit.ts +0 -480
  250. package/src/codegen/patches.ts +0 -581
  251. package/src/codegen/prelude.ts +0 -70
  252. package/src/codegen/privatize.ts +0 -200
  253. package/src/codegen/proto.ts +0 -1092
  254. package/src/codegen/pure.ts +0 -94
  255. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  256. package/src/codegen/spec-path.ts +0 -112
  257. package/src/codegen/table.ts +0 -254
  258. package/src/json-patch.ts +0 -273
  259. package/src/testing.ts +0 -74
@@ -1,155 +0,0 @@
1
- /**
2
- * Boolean-valued string enums on request members (dev-time only).
3
- *
4
- * Plenty of APIs document a flag as the string enum `"true" | "false"`
5
- * rather than a JSON boolean — Cloudflare's `validation_enabled`, Clerk's
6
- * `include_invalid`, GrowthBook's `deleteMissing`, and so on. Taken
7
- * literally that surfaces as `"true" | "false" | (string & {})` and every
8
- * caller writes the ternary itself.
9
- *
10
- * {@link generateService} runs this pass over the loaded model before
11
- * emitting: REQUEST members of such an enum are retargeted to a real
12
- * `smithy.api#Boolean` and stamped {@link STRING_ENCODED_TRAIT}, which the
13
- * generator emits as `T.StringEncoded()` and the protocol honors by sending
14
- * the value's string spelling. The TS surface becomes `boolean` with the
15
- * wire unchanged. The model on disk keeps the string enum the description
16
- * documents.
17
- *
18
- * Deliberately narrow:
19
- *
20
- * • request-only shapes — an operation input, or a structure or list the
21
- * inputs reach and no output or error does. A member a response can
22
- * deliver would need the mirror-image decode, which the protocol does
23
- * not do, so a shape used both ways keeps its documented string type;
24
- * • the enum must be exactly `{"true", "false"}` — a three-value enum
25
- * that happens to include them is left alone.
26
- */
27
-
28
- /** Synthetic trait: send this member's value as its string spelling. */
29
- export const STRING_ENCODED_TRAIT = "distilled.protocols#stringEncoded";
30
-
31
- const BOOLEAN = "smithy.api#Boolean";
32
-
33
- export interface BooleanStringEnumResult {
34
- /** Request members retargeted to a real boolean. */
35
- members: number;
36
- /** List shapes whose element type was retargeted. */
37
- lists: number;
38
- }
39
-
40
- /** Enum shapes whose values are exactly `"true"` and `"false"`. */
41
- const booleanEnumIds = (shapes: Record<string, any>): Set<string> => {
42
- const out = new Set<string>();
43
- for (const [id, shape] of Object.entries(shapes)) {
44
- if (shape?.type !== "enum") continue;
45
- const values = Object.values(shape.members ?? {}).map(
46
- (m: any) => m?.traits?.["smithy.api#enumValue"],
47
- );
48
- if (values.length === 2 && values.includes("true") && values.includes("false")) {
49
- out.add(id);
50
- }
51
- }
52
- return out;
53
- };
54
-
55
- /** Every shape id a shape points at: members, list/map entries, mixins. */
56
- const targetsOf = (shape: any): string[] => {
57
- const out: string[] = [];
58
- for (const member of Object.values<any>(shape?.members ?? {})) {
59
- if (member?.target) out.push(member.target);
60
- }
61
- for (const key of ["member", "value", "key"] as const) {
62
- const target = shape?.[key]?.target;
63
- if (target) out.push(target);
64
- }
65
- for (const mixin of shape?.mixins ?? []) {
66
- if (mixin?.target) out.push(mixin.target);
67
- }
68
- return out;
69
- };
70
-
71
- const reachable = (
72
- shapes: Record<string, any>,
73
- roots: ReadonlyArray<string | undefined>,
74
- ): Set<string> => {
75
- const seen = new Set<string>();
76
- const stack = roots.filter((r): r is string => r !== undefined);
77
- while (stack.length > 0) {
78
- const id = stack.pop()!;
79
- if (seen.has(id) || shapes[id] === undefined) continue;
80
- seen.add(id);
81
- stack.push(...targetsOf(shapes[id]));
82
- }
83
- return seen;
84
- };
85
-
86
- /**
87
- * Shapes an operation input reaches that no output or error does. Operation
88
- * I/O is the spine; the `smithy.api#input`/`#output`/`#error` traits cover
89
- * models whose shapes are not wired through an operation, and a structure
90
- * the inputs never reach counts as a response root — unreachable from a
91
- * request, it can only describe something the API hands back.
92
- */
93
- const requestOnlyShapes = (shapes: Record<string, any>): Set<string> => {
94
- const requestRoots: Array<string | undefined> = [];
95
- const responseRoots: Array<string | undefined> = [];
96
- for (const [id, shape] of Object.entries<any>(shapes)) {
97
- if (shape?.type === "operation") {
98
- requestRoots.push(shape.input?.target);
99
- responseRoots.push(shape.output?.target);
100
- for (const error of shape.errors ?? []) responseRoots.push(error?.target);
101
- continue;
102
- }
103
- const traits = shape?.traits ?? {};
104
- if ("smithy.api#input" in traits) requestRoots.push(id);
105
- if ("smithy.api#output" in traits || "smithy.api#error" in traits) {
106
- responseRoots.push(id);
107
- }
108
- }
109
- const fromRequests = reachable(shapes, requestRoots);
110
- for (const [id, shape] of Object.entries<any>(shapes)) {
111
- if (shape?.type === "structure" && !fromRequests.has(id)) {
112
- responseRoots.push(id);
113
- }
114
- }
115
- const fromResponses = reachable(shapes, responseRoots);
116
- const out = new Set<string>();
117
- for (const id of fromRequests) {
118
- if (!fromResponses.has(id)) out.add(id);
119
- }
120
- return out;
121
- };
122
-
123
- export const booleanStringEnums = (model: any): BooleanStringEnumResult => {
124
- const shapes: Record<string, any> = model?.shapes ?? {};
125
- const boolEnums = booleanEnumIds(shapes);
126
- if (boolEnums.size === 0) return { members: 0, lists: 0 };
127
-
128
- const requestOnly = requestOnlyShapes(shapes);
129
- const boolLists = new Set<string>();
130
- for (const [id, shape] of Object.entries(shapes)) {
131
- if (shape?.type === "list" && boolEnums.has(shape.member?.target) && requestOnly.has(id)) {
132
- boolLists.add(id);
133
- }
134
- }
135
-
136
- let members = 0;
137
- const retargeted = new Set<string>();
138
- for (const [id, shape] of Object.entries<any>(shapes)) {
139
- if (shape?.type !== "structure" || !requestOnly.has(id)) continue;
140
- for (const member of Object.values<any>(shape.members ?? {})) {
141
- const isList = boolLists.has(member?.target);
142
- if (!boolEnums.has(member?.target) && !isList) continue;
143
- if (isList) {
144
- retargeted.add(member.target);
145
- } else {
146
- member.target = BOOLEAN;
147
- }
148
- member.traits = { ...member.traits, [STRING_ENCODED_TRAIT]: {} };
149
- members++;
150
- }
151
- }
152
- for (const id of retargeted) shapes[id].member.target = BOOLEAN;
153
-
154
- return { members, lists: retargeted.size };
155
- };
@@ -1,147 +0,0 @@
1
- /**
2
- * Move module-private schema initializers into chunked builder functions
3
- * (dev-time only; runtime helper: `@distilled.cloud/core/chunks`).
4
- *
5
- * const Customer = S.suspend(() => ...).annotate({ identifier: "Customer" }) as any as S.Schema<Customer>;
6
- * becomes
7
- * const Customer = /*@__PURE__*\/ __L.at(__c12, 3) as any as S.Schema<Customer>;
8
- * ...
9
- * function __c12(j: number): any { switch (j) { ... case 3: return S.suspend(() => ...).annotate({ identifier: "Customer" }); } }
10
- *
11
- * Builders are function declarations at the end of the module (hoisted, so
12
- * the consts can name them at import); their bodies run only on first use,
13
- * after the module has finished evaluating.
14
- */
15
- import { parseAst } from "rolldown/parseAst";
16
- import { valueRefs } from "./privatize.ts";
17
-
18
- type Node = { readonly type: string; readonly start: number; readonly end: number } & Record<
19
- string,
20
- unknown
21
- >;
22
-
23
- /** Schemas per builder function: smaller chunks compile less on first use. */
24
- export const CHUNK_SIZE = 32;
25
-
26
- const stripCasts = (n: Node): Node => {
27
- while (
28
- n.type === "TSAsExpression" ||
29
- n.type === "TSSatisfiesExpression" ||
30
- n.type === "ParenthesizedExpression"
31
- )
32
- n = n.expression as Node;
33
- return n;
34
- };
35
-
36
- export const chunkSchemas = (
37
- code: string,
38
- filename = "generated.ts",
39
- chunkSize = CHUNK_SIZE,
40
- ): { code: string; chunked: number } => {
41
- const program = parseAst(code, { sourceType: "module", lang: "ts" }, filename);
42
- const body = program.body as unknown as Node[];
43
- const items: Array<{ start: number; end: number; text: string; name: string; key: string }> = [];
44
- for (const st of body) {
45
- // Only module-private consts: exports keep their own initializer.
46
- if (st.type !== "VariableDeclaration" || (st.declarations as Node[]).length !== 1) continue;
47
- const d = (st.declarations as Node[])[0]!;
48
- if (!d.init) continue;
49
- const inner = stripCasts(d.init as Node);
50
- if (inner.type !== "CallExpression") continue;
51
- const text = code.slice(inner.start, inner.end);
52
- if (/\bAPI\.make/.test(text) || !/\bS\./.test(text)) continue;
53
- items.push({
54
- start: inner.start,
55
- end: inner.end,
56
- text,
57
- name: ((d.id as Node).name as string) ?? "",
58
- key: "",
59
- });
60
- }
61
- if (!items.length) return { code, chunked: 0 };
62
-
63
- // Group schemas only with schemas reached by exactly the same roots
64
- // (operations and error classes): a bundle that keeps one builder then
65
- // needs every schema in it, so nothing unused comes along.
66
- const refsOf = new Map<string, Set<string>>();
67
- const roots: Array<Set<string>> = [];
68
- for (const st of body) {
69
- const decl =
70
- st.type === "ExportNamedDeclaration" && st.declaration ? (st.declaration as Node) : st;
71
- if (decl.type === "VariableDeclaration") {
72
- for (const d of decl.declarations as Node[]) {
73
- const name = (d.id as Node).name as string | undefined;
74
- if (!name || !d.init) continue;
75
- const refs = valueRefs(d.init, new Set());
76
- refsOf.set(name, refs);
77
- const init = d.init as Node;
78
- if (/\bAPI\.make/.test(code.slice(init.start, init.end))) roots.push(refs);
79
- }
80
- } else if (decl.type === "ClassDeclaration" && decl.id) {
81
- const refs = valueRefs(decl.superClass, new Set());
82
- refsOf.set((decl.id as Node).name as string, refs);
83
- roots.push(refs);
84
- }
85
- }
86
- const reachedBy = new Map<string, number[]>();
87
- roots.forEach((rootRefs, r) => {
88
- const seen = new Set<string>();
89
- const stack = [...rootRefs];
90
- while (stack.length) {
91
- const n = stack.pop()!;
92
- if (seen.has(n) || !refsOf.has(n)) continue;
93
- seen.add(n);
94
- let list = reachedBy.get(n);
95
- if (!list) reachedBy.set(n, (list = []));
96
- list.push(r);
97
- for (const x of refsOf.get(n)!) stack.push(x);
98
- }
99
- });
100
- for (const it of items) it.key = (reachedBy.get(it.name) ?? []).join(",");
101
- const ordered = items
102
- .map((it, i) => [it, i] as const)
103
- .sort((a, b) => (a[0].key < b[0].key ? -1 : a[0].key > b[0].key ? 1 : a[1] - b[1]));
104
- const slot = new Map<(typeof items)[number], [number, number]>();
105
- let chunk = -1;
106
- let used = chunkSize;
107
- let lastKey: string | undefined;
108
- for (const [it] of ordered) {
109
- if (used >= chunkSize || it.key !== lastKey) {
110
- chunk++;
111
- used = 0;
112
- lastKey = it.key;
113
- }
114
- slot.set(it, [chunk, used++]);
115
- }
116
-
117
- const cases: string[][] = [];
118
- for (const it of items) {
119
- const [c, j] = slot.get(it)!;
120
- (cases[c] ??= [])[j] = `case ${j}: return ${it.text};`;
121
- }
122
-
123
- let out = code;
124
- for (let i = items.length - 1; i >= 0; i--) {
125
- const it = items[i]!;
126
- // The PURE marker in front of the old initializer, if any, now marks the `at` call.
127
- const marked = /\/\*[@#]__PURE__\*\/\s*$/.test(out.slice(Math.max(0, it.start - 20), it.start));
128
- const [c, j] = slot.get(it)!;
129
- out = `${out.slice(0, it.start)}${marked ? "" : "/*@__PURE__*/ "}__L.at(__c${c}, ${j})${out.slice(it.end)}`;
130
- }
131
- const lastImport = [...body].reverse().find((s) => s.type === "ImportDeclaration");
132
- const at = lastImport ? lastImport.end : 0;
133
- // Modules on lite schemas take `at` from schema-lite (lazy lite nodes).
134
- const helper = code.includes('"@distilled.cloud/core/schema-lite"')
135
- ? "@distilled.cloud/core/schema-lite"
136
- : "@distilled.cloud/core/chunks";
137
- out = `${out.slice(0, at)}\nimport * as __L from "${helper}";${out.slice(at)}`;
138
- out +=
139
- "\n// Schema builders: each runs one schema initializer, on that schema's first use.\n" +
140
- cases
141
- .map(
142
- (c, k) =>
143
- `function __c${k}(j: number): any {\n switch (j) {\n${c.map((x) => ` ${x}`).join("\n")}\n }\n}`,
144
- )
145
- .join("\n");
146
- return { code: out, chunked: items.length };
147
- };
@@ -1,293 +0,0 @@
1
- /**
2
- * The generic generator CLI harness (dev-time only).
3
- *
4
- * Owns the smithy→SDK pipeline every SDK package shares: scan the model
5
- * directory (plus optional hand-authored manual specs), compile each model
6
- * through {@link generateService} with the provider's {@link SdkSpec}, write
7
- * the service modules and the namespaced barrel. Patches are already in
8
- * `.generated-specs` (convert applies them, see `codegen/patches`).
9
- *
10
- * A provider's `scripts/generate.ts` is: trait consts + an SdkSpec + a
11
- * `runGeneratorCli` call.
12
- */
13
- import { NodeRuntime, NodeServices } from "@effect/platform-node";
14
- import { Console, Effect } from "effect";
15
- import { Flag } from "effect/cli";
16
- import { Command } from "effect/cli";
17
- import * as FileSystem from "effect/FileSystem";
18
- import * as Path from "effect/Path";
19
- import { chunkSchemas } from "./chunk.ts";
20
- import { dedupeSchemas } from "./dedupe.ts";
21
- import { barrel } from "./emit.ts";
22
- import { formatGenerated } from "./format.ts";
23
- import { stampGeneratedAt } from "./generated-at.ts";
24
- import { generateService, type SdkSpec } from "./generator.ts";
25
- import { toLatin1 } from "./latin1.ts";
26
- import { privatizeSchemas, typeOnlyNamespaceImports } from "./privatize.ts";
27
- import { annotateNestedCalls } from "./pure.ts";
28
- import { tableSchemas } from "./table.ts";
29
-
30
- export interface GeneratorCliOptions {
31
- /** Command description shown in --help. */
32
- readonly description: string;
33
- /** Absolute package root (usually `path.resolve(import.meta.dirname, "..")`). */
34
- readonly root: string;
35
- /** Model directory default (relative to root). Default `.generated-specs`. */
36
- readonly smithyDir?: string;
37
- /** Output directory default (relative to root). Default `src/services`. */
38
- readonly outDir?: string;
39
- /** Model files to skip (e.g. a shared protocols model). */
40
- readonly excludeModel?: (file: string) => boolean;
41
- /**
42
- * Where the models are, when they aren't a flat directory of `<resource>.json`.
43
- * AWS vendors Amazon's own repo, whose models sit at
44
- * `models/<service>/service/<version>/<service>-<version>.json`.
45
- *
46
- * Returns the model files to compile; manual specs are merged in after,
47
- * as usual.
48
- */
49
- readonly discoverModels?: (ctx: {
50
- readonly smithyDir: string;
51
- }) => Effect.Effect<
52
- ReadonlyArray<{ readonly file: string; readonly dir: string }>,
53
- never,
54
- FileSystem.FileSystem | Path.Path
55
- >;
56
- /**
57
- * Side effects to run before generating — e.g. AWS copies `partitions.json`
58
- * out of the smithy submodule, runtime data its endpoint resolver reads.
59
- */
60
- readonly prepare?: (ctx: {
61
- readonly root: string;
62
- readonly outDir: string;
63
- }) => Effect.Effect<void, never, FileSystem.FileSystem | Path.Path>;
64
- /**
65
- * The output module's name, when it isn't the model's filename. AWS names
66
- * modules after the service's `aws.api#service` sdkId (`amazon-s3.json` →
67
- * `s3.ts`), so the public surface reads `AWS.S3.getObject`.
68
- */
69
- readonly resourceName?: (ctx: { readonly model: any; readonly file: string }) => string;
70
- /** Barrel export name for a resource. Default: the resource name itself. */
71
- readonly barrelExportName?: (resource: string) => string;
72
- /**
73
- * The closing pass over the output directory. Defaults to formatting;
74
- * AWS lint-fixes first (see `codegen/format.ts`).
75
- */
76
- readonly finalize?: (dir: string) => Effect.Effect<void>;
77
- /**
78
- * Keep generating after a model fails, instead of stopping at the first.
79
- * AWS compiles 430 services in one run, and one broken model shouldn't
80
- * hide the state of the other 429. The run still FAILS at the end — the
81
- * failures are reported together rather than swallowed.
82
- */
83
- readonly continueOnModelError?: boolean;
84
- /** Directory of hand-authored models merged after the generated ones. */
85
- readonly manualSpecsDir?: string;
86
- /**
87
- * Generate never applies patches: convert does, so `.generated-specs` is
88
- * the patched model. Only `false` is accepted so a path is a type error
89
- * rather than a silently ignored setting.
90
- */
91
- readonly patchesDir?: false;
92
- /**
93
- * Model transform applied before generation (e.g. AWS dropping
94
- * unreachable foreign-namespace shapes from a vendored model). Does not
95
- * write back to `.generated-specs` — convert owns the committed model.
96
- */
97
- readonly transformModel?: (model: any, resource: string) => string | void;
98
- /** The provider spec — built per model (metadata may vary per model). */
99
- readonly spec: (model: any) => SdkSpec;
100
- }
101
-
102
- /** Run the generator CLI (NodeRuntime main — call at module top level). */
103
- export const runGeneratorCli = (options: GeneratorCliOptions): void => {
104
- const command = Command.make(
105
- "generate",
106
- {
107
- smithy: Flag.String("smithy").pipe(
108
- Flag.withDefault(options.smithyDir ?? ".generated-specs"),
109
- Flag.withDescription("Directory of Smithy JSON models"),
110
- ),
111
- out: Flag.String("out").pipe(
112
- Flag.withDefault(options.outDir ?? "src/services"),
113
- Flag.withDescription("Output directory for generated service modules"),
114
- ),
115
- resource: Flag.String("resource").pipe(
116
- Flag.withDefault(""),
117
- Flag.withDescription("Only generate this resource (e.g. ai)"),
118
- ),
119
- },
120
- (config) =>
121
- Effect.gen(function* () {
122
- const fs = yield* FileSystem.FileSystem;
123
- const path = yield* Path.Path;
124
- const root = options.root;
125
- const smithyDir = path.resolve(root, config.smithy);
126
- const outDir = path.resolve(root, config.out);
127
-
128
- yield* Console.log("⚙️ generate");
129
- yield* Console.log(` Smithy: ${smithyDir}`);
130
- yield* Console.log(` Output: ${outDir}`);
131
-
132
- yield* options.prepare?.({ root, outDir }) ?? Effect.void;
133
-
134
- // Generated models plus optional manual-specs (hand-authored models
135
- // for APIs the provider's spec source doesn't cover). A manual model
136
- // must not shadow a generated one.
137
- const generated = options.discoverModels
138
- ? yield* options.discoverModels({ smithyDir })
139
- : (yield* fs.readDirectory(smithyDir))
140
- .filter((f) => f.endsWith(".json") && !(options.excludeModel?.(f) ?? false))
141
- .map((f) => ({ file: f, dir: smithyDir }));
142
- const manualDir = options.manualSpecsDir
143
- ? path.resolve(root, options.manualSpecsDir)
144
- : undefined;
145
- const manual =
146
- manualDir && (yield* fs.exists(manualDir))
147
- ? (yield* fs.readDirectory(manualDir))
148
- .filter((f) => f.endsWith(".json"))
149
- .map((f) => ({ file: f, dir: manualDir }))
150
- : [];
151
- for (const m of manual) {
152
- if (generated.some((g) => g.file === m.file)) {
153
- return yield* Effect.die(
154
- new Error(
155
- `${options.manualSpecsDir}/${m.file} shadows a generated model — rename or delete it`,
156
- ),
157
- );
158
- }
159
- }
160
- const entries = [...generated, ...manual].sort((a, b) => a.file.localeCompare(b.file));
161
-
162
- yield* fs.makeDirectory(outDir, { recursive: true });
163
-
164
- const written: string[] = [];
165
- const failedModels: string[] = [];
166
- let totalOps = 0;
167
-
168
- for (const { file, dir } of entries) {
169
- const model = JSON.parse(yield* fs.readFileString(path.join(dir, file)));
170
- // The module's name — the model's filename unless the provider
171
- // derives it from the model itself (AWS: the service's sdkId).
172
- const resource = options.resourceName?.({ model, file }) ?? file.replace(/\.json$/, "");
173
- if (config.resource && resource !== config.resource) continue;
174
-
175
- if (options.transformModel) {
176
- const note = options.transformModel(model, resource);
177
- if (note) yield* Console.log(` ${note}`);
178
- }
179
-
180
- // `generateService` and the provider spec are synchronous and
181
- // throw; with continueOnModelError the throw is recorded and the
182
- // run moves on, so one broken model doesn't hide the state of
183
- // every model after it. The run still fails at the end.
184
- let generated;
185
- try {
186
- generated = generateService(model, options.spec(model));
187
- } catch (e) {
188
- if (!options.continueOnModelError) throw e;
189
- failedModels.push(`${resource}: ${e instanceof Error ? e.message : String(e)}`);
190
- yield* Console.error(`❌ ${resource}`);
191
- continue;
192
- }
193
- const { operations } = generated;
194
- if (operations === 0) continue;
195
- // Every nested call in a top-level initializer gets a PURE marker,
196
- // so one unused schema cannot pin others in a consumer's bundle.
197
- // Latin-1-only source halves the heap V8 keeps for the module text.
198
- // Structurally identical schemas become aliases of one schema, and
199
- // schema consts become module-private (types stay exported).
200
- const resourceFile = `${resource}.ts`;
201
- const marked = annotateNestedCalls(generated.code, resourceFile);
202
- const code = toLatin1(
203
- typeOnlyNamespaceImports(
204
- tableSchemas(
205
- chunkSchemas(
206
- privatizeSchemas(dedupeSchemas(marked, resourceFile).code, resourceFile).code,
207
- resourceFile,
208
- ).code,
209
- resourceFile,
210
- ).code,
211
- resourceFile,
212
- ),
213
- resourceFile,
214
- );
215
-
216
- yield* fs.writeFileString(path.join(outDir, `${resource}.ts`), code);
217
- written.push(resource);
218
- totalOps += operations;
219
- }
220
-
221
- // Barrel — namespace per resource to avoid op-name collisions.
222
- //
223
- // A FULL run is authoritative: the barrel is exactly what was
224
- // generated, so a resource whose model went away drops out of it.
225
- //
226
- // A `--resource` run only knows about the resource it generated, so
227
- // rewriting the barrel from that would delete every other export —
228
- // which is how #397 shipped a cloudflare barrel exporting `workers`
229
- // and nothing else, silently dropping 119 services. Merge into the
230
- // existing barrel instead, so `--resource` can still ADD a brand-new
231
- // resource without removing anything.
232
- const barrelPath = path.join(outDir, "index.ts");
233
- const filtered = config.resource !== "";
234
- // Sorted, not in generation order: a provider that discovers models
235
- // in some other order (AWS walks Amazon's directory tree) would
236
- // otherwise reshuffle the barrel on every run.
237
- let resources = [...written].sort((a, b) => `${a}.json`.localeCompare(`${b}.json`));
238
- if (filtered && (yield* fs.exists(barrelPath))) {
239
- // Recover the RESOURCE from each export line's path, not its name:
240
- // the two differ when barrelExportName renames (AWS exports
241
- // `S3` from `./s3.ts`).
242
- const existing = (yield* fs.readFileString(barrelPath))
243
- .split("\n")
244
- .map((line) => /^export \* as \S+ from "\.\/(.+)\.ts";/.exec(line)?.[1])
245
- .filter((name): name is string => name !== undefined);
246
- // Ordered exactly as a full run orders it: by MODEL FILENAME, so
247
- // the `.json` takes part in the collation (`ai_gateway.json` sorts
248
- // before `ai.json`, where the bare names sort the other way).
249
- // Otherwise a filtered run reshuffles the barrel into diff noise.
250
- resources = [...new Set([...existing, ...written])].sort((a, b) =>
251
- `${a}.json`.localeCompare(`${b}.json`),
252
- );
253
- }
254
-
255
- yield* fs.writeFileString(
256
- barrelPath,
257
- barrel(
258
- `// AUTO-GENERATED by scripts/generate.ts. Do not edit.\n`,
259
- resources.map((r) => ({
260
- name: options.barrelExportName?.(r) ?? r,
261
- path: `./${r}.ts`,
262
- })),
263
- ),
264
- );
265
-
266
- yield* (options.finalize ?? formatGenerated)(outDir);
267
-
268
- yield* Console.log(
269
- `\n✅ Generated ${totalOps} operations across ${written.length} resource modules.`,
270
- );
271
- yield* Console.log(` ${path.join(outDir, "index.ts")}`);
272
-
273
- // Models that failed under continueOnModelError. Reported together,
274
- // at the end, and the run FAILS — a generate that couldn't produce
275
- // a module must not exit 0 with the failure buried in the log.
276
- if (failedModels.length) {
277
- yield* Console.error(`\n❌ ${failedModels.length} model(s) failed to generate:`);
278
- for (const f of failedModels) yield* Console.error(` ${f}`);
279
- return yield* Effect.die(new Error(`${failedModels.length} model(s) failed to generate`));
280
- }
281
-
282
- const stamp = yield* Effect.sync(() => stampGeneratedAt(root));
283
- yield* Console.log(` package.json distilled.generatedAt = ${stamp.generatedAt}`);
284
- yield* Console.log(
285
- ` package.json distilled.specUpdatedAt = ${stamp.specUpdatedAt ?? "(unknown, unchanged)"}`,
286
- );
287
- }),
288
- ).pipe(Command.withDescription(options.description));
289
-
290
- NodeRuntime.runMain(
291
- Effect.provide(Command.run(command, { version: "1.0.0" }), NodeServices.layer),
292
- );
293
- };