@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,73 +0,0 @@
1
- import type { ShapeMap } from "./graph.ts";
2
- /**
3
- * Operation-level smithy helpers for the SDK generators (dev-time only).
4
- */
5
- import { local } from "./naming.ts";
6
-
7
- export interface OpEntry {
8
- id: string;
9
- def: any;
10
- }
11
-
12
- /** All operation shapes, sorted by local name. */
13
- export const collectOperations = (shapes: ShapeMap): OpEntry[] => {
14
- const operations: OpEntry[] = [];
15
- for (const [id, def] of Object.entries(shapes)) {
16
- if (def.type === "operation") operations.push({ id, def });
17
- }
18
- operations.sort((a, b) => local(a.id).localeCompare(local(b.id)));
19
- return operations;
20
- };
21
-
22
- /** The model's shape namespace (from the first operation, else any shape). */
23
- export const modelNamespace = (
24
- operations: readonly OpEntry[],
25
- shapes: ShapeMap,
26
- fallback: string,
27
- ): string =>
28
- operations.length
29
- ? operations[0].id.split("#")[0]
30
- : (Object.keys(shapes)[0]?.split("#")[0] ?? fallback);
31
-
32
- /**
33
- * Resolve an operation's input/output targets, synthesizing an empty named
34
- * structure for `smithy.api#Unit` so every operation has a shape that can
35
- * carry operation-level traits (mutates `shapes`).
36
- */
37
- export const ensureNamedIo = (
38
- shapes: ShapeMap,
39
- op: OpEntry,
40
- ns: string,
41
- ): { input: string; output: string } => {
42
- const opName = local(op.id);
43
- let input = op.def.input?.target ?? "smithy.api#Unit";
44
- let output = op.def.output?.target ?? "smithy.api#Unit";
45
- if (input === "smithy.api#Unit") {
46
- input = `${ns}#${opName}Request`;
47
- shapes[input] = { type: "structure", members: {} };
48
- }
49
- if (output === "smithy.api#Unit") {
50
- output = `${ns}#${opName}Response`;
51
- shapes[output] = { type: "structure", members: {} };
52
- }
53
- return { input, output };
54
- };
55
-
56
- /**
57
- * Every error shape id referenced by the operations' `errors` lists —
58
- * deduplicated, existing in the model, sorted by local name.
59
- */
60
- export const collectOpErrorIds = (operations: readonly OpEntry[], shapes: ShapeMap): string[] => {
61
- const errorIds: string[] = [];
62
- const seen = new Set<string>();
63
- for (const op of operations) {
64
- for (const e of op.def.errors ?? []) {
65
- if (!seen.has(e.target) && shapes[e.target]) {
66
- seen.add(e.target);
67
- errorIds.push(e.target);
68
- }
69
- }
70
- }
71
- errorIds.sort((a, b) => local(a).localeCompare(local(b)));
72
- return errorIds;
73
- };
@@ -1,64 +0,0 @@
1
- /**
2
- * Shared pagination-trait handling for the SDK generators (dev-time only).
3
- *
4
- * Both SDKs source `smithy.api#paginated`; AWS merges operation-level
5
- * config over service-level defaults, cloudflare validates the trait
6
- * against the operation's actual members (degrading to a plain op when it
7
- * can't work). Both behaviors live here.
8
- */
9
- import type { PaginatedTrait } from "../pagination.ts";
10
-
11
- /**
12
- * Merge an operation-level paginated trait over service-level defaults
13
- * (Smithy semantics: operations may specify partial pagination and inherit
14
- * the rest from the service).
15
- */
16
- export const mergePaginated = (
17
- op: Partial<PaginatedTrait> | undefined,
18
- service: Partial<PaginatedTrait> | undefined,
19
- ): PaginatedTrait | undefined => {
20
- if (!op) return undefined;
21
- const merged = {
22
- mode: op.mode ?? service?.mode,
23
- inputToken: op.inputToken ?? service?.inputToken,
24
- outputToken: op.outputToken ?? service?.outputToken,
25
- items: op.items ?? service?.items,
26
- pageSize: op.pageSize ?? service?.pageSize,
27
- };
28
- return Object.fromEntries(
29
- Object.entries(merged).filter(([, v]) => v !== undefined),
30
- ) as PaginatedTrait;
31
- };
32
-
33
- export interface ValidatePaginatedOptions {
34
- readonly trait: Partial<PaginatedTrait>;
35
- /** TS-facing member names of the operation input shape. */
36
- readonly inputNames: ReadonlySet<string>;
37
- /** TS-facing member names of the operation output shape. */
38
- readonly outputNames: ReadonlySet<string>;
39
- /** Items path fallback when the trait omits `items` (e.g. `"result"`). */
40
- readonly itemsFallback?: string;
41
- /** Output names accepted even when not modeled (e.g. `"resultInfo"`). */
42
- readonly syntheticOutputs?: ReadonlySet<string>;
43
- }
44
-
45
- export interface ValidatedPagination {
46
- readonly ok: boolean;
47
- /** Root member of the items path (`"result.items"` → `"result"`). */
48
- readonly itemsRoot: string;
49
- }
50
-
51
- /**
52
- * A paginated op must actually carry its page/cursor token on the input
53
- * and its items member on the output — otherwise `.pages()` would loop or
54
- * yield nothing. Returns the items-path root for emitters that promote it
55
- * to required.
56
- */
57
- export const validatePaginated = (o: ValidatePaginatedOptions): ValidatedPagination => {
58
- const itemsRoot = String(o.trait.items ?? o.itemsFallback ?? "").split(".")[0];
59
- const tokenOk =
60
- o.trait.mode === "single" ||
61
- (typeof o.trait.inputToken === "string" && o.inputNames.has(o.trait.inputToken));
62
- const itemsOk = o.outputNames.has(itemsRoot) || (o.syntheticOutputs?.has(itemsRoot) ?? false);
63
- return { ok: tokenOk && itemsOk, itemsRoot };
64
- };
@@ -1,480 +0,0 @@
1
- /**
2
- * Patch audit (dev-time only): does each RFC-6902 patch still change the
3
- * model? A patch earns its keep by changing the patched model. The audit
4
- * builds the model once with every patch (the baseline), then once per
5
- * patch file with that file left out, and diffs:
6
- *
7
- * unused the model is identical without it — delete the file
8
- * needed the model differs; the diff lists the JSON pointers
9
- * depended the build fails without it — a later patch targets what it
10
- * adds, so the two go together
11
- *
12
- * The model is built by running the package's `convert` on a scratch copy
13
- * of the package (`packages/.audit-<pkg>-<n>`), so the spec mirror must be
14
- * fetched. A file whose ops all target the Smithy model is judged in
15
- * memory by `finalizeConvert` ({@link PATCH_AUDIT_ENV}): one convert, then
16
- * only the finalize steps re-run per file. A file finalizeConvert does not
17
- * apply (Railway's GraphQL patches) costs one convert per file
18
- * ({@link SKIP_PATCHES_ENV}). Up to `jobs` copies run at once.
19
- *
20
- * The package itself is never written: its `.generated-*` dirs stay as
21
- * committed.
22
- *
23
- * Every verdict is one-at-a-time: two patches that add the same thing each
24
- * look unused alone, and only the second deletion changes the model.
25
- */
26
- import { spawn } from "node:child_process";
27
- import {
28
- cpSync,
29
- existsSync,
30
- mkdirSync,
31
- readdirSync,
32
- readFileSync,
33
- rmSync,
34
- statSync,
35
- symlinkSync,
36
- writeFileSync,
37
- } from "node:fs";
38
- import { availableParallelism, freemem } from "node:os";
39
- import { basename, dirname, join, relative, sep } from "node:path";
40
- import { diffModels, type Models } from "./model-diff.ts";
41
- import {
42
- isSmithyPatchPath,
43
- PATCH_AUDIT_ENV,
44
- PATCH_AUDIT_MARKER,
45
- RENAME_MAP_ENV,
46
- SKIP_PATCHES_ENV,
47
- type InMemoryVerdict,
48
- } from "./patches.ts";
49
-
50
- export { diffModels, type Models };
51
-
52
- export type Run =
53
- | { readonly ok: true; readonly models: Models }
54
- | { readonly ok: false; readonly error: string };
55
-
56
- /** Builds the patched model, optionally with a skip-list entry left out. */
57
- export interface ModelBuilder {
58
- readonly build: (skip?: string) => Run;
59
- readonly restore: (baseline: Models) => void;
60
- }
61
-
62
- export interface PatchFileInfo {
63
- /** Path relative to the package's `patches/` — the skip-list entry. */
64
- readonly key: string;
65
- readonly ops: number;
66
- /** Whether every op targets the Smithy model (`/shapes`, `/metadata`, …). */
67
- readonly smithyOnly: boolean;
68
- }
69
-
70
- export type Verdict =
71
- | { readonly kind: "unused" }
72
- | { readonly kind: "needed"; readonly diff: readonly string[] }
73
- | { readonly kind: "depended"; readonly error: string };
74
-
75
- export interface FileVerdict {
76
- readonly file: PatchFileInfo;
77
- readonly verdict: Verdict;
78
- /** With `ops`: indices of ops inside a needed file that change nothing alone. */
79
- readonly deadOps: readonly number[];
80
- }
81
-
82
- export type PackageAudit =
83
- | {
84
- readonly kind: "audited";
85
- readonly files: readonly FileVerdict[];
86
- /** Files under `patches/` without a `patches` array (e.g. AWS typed configs). */
87
- readonly notAudited: readonly string[];
88
- /** How many files were judged in memory, and how many by one convert each. */
89
- readonly judged: { readonly inMemory: number; readonly perFile: number };
90
- }
91
- | { readonly kind: "skipped"; readonly reason: string };
92
-
93
- // ---------------------------------------------------------------------------
94
- // files
95
-
96
- const walkJson = (dir: string): string[] => {
97
- if (!existsSync(dir)) return [];
98
- const out: string[] = [];
99
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
100
- a.name.localeCompare(b.name),
101
- )) {
102
- const p = join(dir, entry.name);
103
- if (entry.isDirectory()) out.push(...walkJson(p));
104
- else if (entry.name.endsWith(".json")) out.push(p);
105
- }
106
- return out;
107
- };
108
-
109
- /** RFC-6902 files under `patchesDir`; anything without a `patches` array is returned separately. */
110
- export const listPatchFiles = (patchesDir: string): { files: PatchFileInfo[]; other: string[] } => {
111
- const files: PatchFileInfo[] = [];
112
- const other: string[] = [];
113
- for (const file of walkJson(patchesDir)) {
114
- const key = relative(patchesDir, file).split(sep).join("/");
115
- let parsed: unknown;
116
- try {
117
- parsed = JSON.parse(readFileSync(file, "utf8"));
118
- } catch {
119
- other.push(key);
120
- continue;
121
- }
122
- const ops = (parsed as { patches?: unknown })?.patches;
123
- if (!Array.isArray(ops)) {
124
- other.push(key);
125
- continue;
126
- }
127
- const smithyOnly = ops.every(
128
- (op) => typeof op?.path === "string" && isSmithyPatchPath(op.path),
129
- );
130
- files.push({ key, ops: ops.length, smithyOnly });
131
- }
132
- return { files, other };
133
- };
134
-
135
- // ---------------------------------------------------------------------------
136
- // scratch copies
137
-
138
- /**
139
- * A scratch copy of the package next to it (same depth, so relative imports
140
- * and `node_modules` resolve the same; the dot keeps it out of the pnpm
141
- * workspace). `scripts/` and `package.json` are copied — Node resolves a
142
- * symlinked script to its real path, which would make the copy's convert
143
- * write to the real package — `.generated-*` dirs start empty, and
144
- * everything else is a symlink.
145
- */
146
- const scratchCopy = (pkgDir: string, index: number): string => {
147
- const dir = join(dirname(pkgDir), `.audit-${basename(pkgDir)}-${index}`);
148
- rmSync(dir, { recursive: true, force: true });
149
- mkdirSync(dir);
150
- for (const entry of readdirSync(pkgDir, { withFileTypes: true })) {
151
- const from = join(pkgDir, entry.name);
152
- const to = join(dir, entry.name);
153
- // Every convert output dir (`.generated-specs`, Railway's
154
- // `.generated-graphql`) starts empty, so convert never writes through a
155
- // symlink into the package.
156
- if (entry.name.startsWith(".generated")) mkdirSync(to);
157
- else if (entry.name === "scripts" || entry.name === "package.json") {
158
- cpSync(from, to, { recursive: true });
159
- } else symlinkSync(from, to);
160
- }
161
- return dir;
162
- };
163
-
164
- /** Every model convert wrote in a copy, keyed `<.generated-* dir>/<path>`. */
165
- const outputs = (copy: string): Models => {
166
- const out: Models = new Map();
167
- for (const entry of readdirSync(copy, { withFileTypes: true })) {
168
- if (!entry.isDirectory() || !entry.name.startsWith(".generated")) continue;
169
- const dir = join(copy, entry.name);
170
- for (const f of walkJson(dir))
171
- out.set(`${entry.name}/${relative(dir, f)}`, readFileSync(f, "utf8"));
172
- }
173
- return out;
174
- };
175
-
176
- interface ConvertResult {
177
- readonly ok: boolean;
178
- /** convert's own report when it failed: the `❌` lines, or its last lines. */
179
- readonly error: string;
180
- }
181
-
182
- /**
183
- * Run the package's convert command in `cwd`. Marker lines from an
184
- * in-memory audit go to `onVerdict`; everything else is only kept for the
185
- * error report.
186
- */
187
- const runConvert = (
188
- command: string,
189
- cwd: string,
190
- env: NodeJS.ProcessEnv,
191
- onVerdict: (v: InMemoryVerdict) => void = () => {},
192
- ): Promise<ConvertResult> =>
193
- new Promise((resolve) => {
194
- const child = spawn(command, { cwd, env, shell: true, stdio: ["ignore", "pipe", "pipe"] });
195
- const reported: string[] = [];
196
- const tail: string[] = [];
197
- const keep = (line: string) => {
198
- const l = line.trim();
199
- if (l === "" || l.startsWith(`⚠ ${SKIP_PATCHES_ENV}`)) return;
200
- if (l.startsWith("❌")) reported.push(l);
201
- tail.push(l);
202
- if (tail.length > 20) tail.shift();
203
- };
204
- const lines = (stream: NodeJS.ReadableStream, onLine: (line: string) => void) => {
205
- let buffer = "";
206
- stream.setEncoding("utf8");
207
- stream.on("data", (chunk: string) => {
208
- buffer += chunk;
209
- let nl: number;
210
- while ((nl = buffer.indexOf("\n")) !== -1) {
211
- onLine(buffer.slice(0, nl));
212
- buffer = buffer.slice(nl + 1);
213
- }
214
- });
215
- stream.on("end", () => buffer && onLine(buffer));
216
- };
217
- lines(child.stdout!, (line) => {
218
- if (line.startsWith(PATCH_AUDIT_MARKER)) {
219
- onVerdict(JSON.parse(line.slice(PATCH_AUDIT_MARKER.length)) as InMemoryVerdict);
220
- } else keep(line);
221
- });
222
- lines(child.stderr!, keep);
223
- child.on("error", (e) => keep(String(e)));
224
- child.on("close", (code) => {
225
- // convert reports each bad patch on its own `❌` line before throwing;
226
- // those name the pointer, the stack trace below them does not.
227
- const shown = reported.length > 0 ? reported : tail.slice(-2);
228
- resolve({ ok: code === 0, error: shown.slice(0, 3).join("\n ") });
229
- });
230
- });
231
-
232
- /** Copies to run at once: one core and ~1.5 GB of free memory each. */
233
- const defaultJobs = (): number =>
234
- Math.max(1, Math.min(availableParallelism() - 1, Math.floor(freemem() / 1.5e9)));
235
-
236
- /**
237
- * Split keys into at most `n` shards of about equal cost. A key costs about
238
- * the size of the model its patch dir applies to (every judgement re-runs
239
- * finalize over that model), so a dir is kept whole when it fits in one
240
- * shard's share and cut into chunks when it does not — each chunk pays one
241
- * more convert, which is cheap next to hundreds of re-finalized copies of a
242
- * large model.
243
- */
244
- const shard = (keys: readonly string[], n: number, cost: (dir: string) => number): string[][] => {
245
- const groups = new Map<string, string[]>();
246
- for (const key of keys) {
247
- const dir = key.includes("/") ? key.slice(0, key.lastIndexOf("/")) : "";
248
- groups.set(dir, [...(groups.get(dir) ?? []), key]);
249
- }
250
- const weighted = [...groups].map(([dir, ks]) => ({ keys: ks, each: cost(dir) }));
251
- const total = weighted.reduce((sum, g) => sum + g.keys.length * g.each, 0);
252
- const share = total / n;
253
- const pieces: { keys: string[]; cost: number }[] = [];
254
- for (const g of weighted) {
255
- const chunks = Math.min(
256
- g.keys.length,
257
- Math.max(1, Math.ceil((g.keys.length * g.each) / share)),
258
- );
259
- const size = Math.ceil(g.keys.length / chunks);
260
- for (let i = 0; i < g.keys.length; i += size) {
261
- const ks = g.keys.slice(i, i + size);
262
- pieces.push({ keys: ks, cost: ks.length * g.each });
263
- }
264
- }
265
- const shards = Array.from({ length: Math.min(n, pieces.length) }, () => ({
266
- keys: [] as string[],
267
- cost: 0,
268
- }));
269
- for (const piece of pieces.sort((a, b) => b.cost - a.cost)) {
270
- const min = shards.reduce((a, b) => (b.cost < a.cost ? b : a));
271
- min.keys.push(...piece.keys);
272
- min.cost += piece.cost;
273
- }
274
- return shards.map((s) => s.keys).filter((ks) => ks.length > 0);
275
- };
276
-
277
- /** Merge one file's verdicts from every model its patch dir applies to. */
278
- const mergeVerdicts = (vs: readonly InMemoryVerdict[]): Omit<FileVerdict, "file"> => {
279
- const failed = vs.find((v) => v.verdict.kind === "depended" || v.verdict.kind === "baseline");
280
- if (failed && "error" in failed.verdict) {
281
- return { verdict: { kind: "depended", error: failed.verdict.error }, deadOps: [] };
282
- }
283
- const needed = vs.filter((v) => v.verdict.kind === "needed");
284
- if (needed.length === 0) return { verdict: { kind: "unused" }, deadOps: [] };
285
- const diff = needed.flatMap((v) =>
286
- v.verdict.kind === "needed"
287
- ? v.verdict.diff.map((line) => (needed.length > 1 ? `${v.model}: ${line}` : line))
288
- : [],
289
- );
290
- // An op is dead only if it changes nothing in any of the models.
291
- const deadOps = needed.map((v) => v.deadOps).reduce((a, b) => a.filter((i) => b.includes(i)));
292
- return { verdict: { kind: "needed", diff }, deadOps };
293
- };
294
-
295
- /** Bounded-concurrency map over a pool of scratch copies. */
296
- const withCopies = async <A>(
297
- copies: readonly string[],
298
- tasks: readonly A[],
299
- run: (task: A, copy: string) => Promise<void>,
300
- ): Promise<void> => {
301
- let next = 0;
302
- await Promise.all(
303
- copies.map(async (copy) => {
304
- while (next < tasks.length) await run(tasks[next++]!, copy);
305
- }),
306
- );
307
- };
308
-
309
- const auditConvertStage = async (
310
- pkgDir: string,
311
- command: string,
312
- files: readonly PatchFileInfo[],
313
- options: AuditOptions,
314
- report: (v: FileVerdict) => void,
315
- ): Promise<{ inMemory: number; perFile: number } | { error: string }> => {
316
- const jobs = Math.max(1, options.jobs ?? defaultJobs());
317
- const inMemoryKeys =
318
- options.inMemory === false ? [] : files.filter((f) => f.smithyOnly).map((f) => f.key);
319
- // A dir's cost: the size of the committed model it patches (1 MB when
320
- // there is none to go by, e.g. a root-level file patching every model).
321
- const specsDir = join(pkgDir, ".generated-specs");
322
- const cost = (dir: string): number => {
323
- const model = join(specsDir, `${dir}.json`);
324
- return dir !== "" && existsSync(model) ? Math.max(1, statSync(model).size / 1e6) : 1;
325
- };
326
- const shards = shard(inMemoryKeys, jobs, cost);
327
- // Even with nothing to judge in memory, one convert builds the baseline.
328
- if (shards.length === 0) shards.push([]);
329
- const copies = Array.from({ length: Math.max(1, Math.min(jobs, files.length)) }, (_, i) =>
330
- scratchCopy(pkgDir, i),
331
- );
332
- const cleanup = () => {
333
- for (const c of copies) rmSync(c, { recursive: true, force: true });
334
- };
335
- const onSignal = () => {
336
- cleanup();
337
- process.exit(130);
338
- };
339
- process.once("SIGINT", onSignal);
340
- process.once("SIGTERM", onSignal);
341
- const byKey = new Map(files.map((f) => [f.key, f]));
342
- try {
343
- // 1. In memory: one convert per shard, each on its own copy.
344
- const verdicts = new Map<string, InMemoryVerdict[]>();
345
- let baselineError: string | undefined;
346
- await withCopies(copies, shards, async (keys, copy) => {
347
- const request = join(copy, ".audit-request.json");
348
- writeFileSync(request, JSON.stringify({ keys, ops: options.ops === true }));
349
- const result = await runConvert(
350
- command,
351
- copy,
352
- { ...process.env, [PATCH_AUDIT_ENV]: request, [SKIP_PATCHES_ENV]: "" },
353
- (v) => {
354
- verdicts.set(v.key, [...(verdicts.get(v.key) ?? []), v]);
355
- options.onProgress?.();
356
- },
357
- );
358
- if (!result.ok) baselineError ??= result.error;
359
- // A key is complete once its convert has exited: GCP judges one
360
- // patch dir against both its stable and unstable model.
361
- for (const key of keys) {
362
- const vs = verdicts.get(key);
363
- if (vs) report({ file: byKey.get(key)!, ...mergeVerdicts(vs) });
364
- }
365
- });
366
- if (baselineError !== undefined) return { error: baselineError };
367
-
368
- // 2. Everything else: one convert per file, diffed against the baseline
369
- // a copy just wrote.
370
- const perFile = files.filter((f) => !verdicts.has(f.key));
371
- if (perFile.length > 0) {
372
- const baseline = outputs(copies[0]!);
373
- const judge = async (skip: string, copy: string): Promise<Verdict> => {
374
- const result = await runConvert(command, copy, {
375
- ...process.env,
376
- [SKIP_PATCHES_ENV]: skip,
377
- });
378
- if (!result.ok) return { kind: "depended", error: result.error };
379
- const diff = diffModels(baseline, outputs(copy));
380
- return diff.length === 0 ? { kind: "unused" } : { kind: "needed", diff };
381
- };
382
- await withCopies(copies, perFile, async (file, copy) => {
383
- const verdict = await judge(file.key, copy);
384
- options.onProgress?.();
385
- const deadOps: number[] = [];
386
- if (options.ops && verdict.kind === "needed" && file.ops > 1) {
387
- for (let index = 0; index < file.ops; index++) {
388
- if ((await judge(`${file.key}:${index}`, copy)).kind === "unused") deadOps.push(index);
389
- }
390
- }
391
- report({ file, verdict, deadOps });
392
- });
393
- }
394
- return { inMemory: verdicts.size, perFile: perFile.length };
395
- } finally {
396
- process.off("SIGINT", onSignal);
397
- process.off("SIGTERM", onSignal);
398
- cleanup();
399
- }
400
- };
401
-
402
- // ---------------------------------------------------------------------------
403
- // audit
404
-
405
- export interface AuditOptions {
406
- /** Also judge every op inside each needed file. */
407
- readonly ops?: boolean;
408
- /** Only files whose key contains this substring. */
409
- readonly only?: string;
410
- /** Scratch copies converting at once; default from cores and free memory. */
411
- readonly jobs?: number;
412
- /** `false` judges every file by one convert each (the slow path; for comparing). */
413
- readonly inMemory?: boolean;
414
- /** Called after each file's verdict, in completion order. */
415
- readonly onFile?: (verdict: FileVerdict) => void;
416
- /** Called as each file is judged, before its verdict is final. */
417
- readonly onProgress?: () => void;
418
- }
419
-
420
- /** Audit one package directory. Never throws for a broken baseline — that is `skipped`. */
421
- export const auditPackage = async (
422
- pkgDir: string,
423
- options: AuditOptions = {},
424
- ): Promise<PackageAudit> => {
425
- const patchesDir = join(pkgDir, "patches");
426
- if (!existsSync(patchesDir)) return { kind: "skipped", reason: "no patches/ directory" };
427
- const listed = listPatchFiles(patchesDir);
428
- const files =
429
- options.only === undefined
430
- ? listed.files
431
- : listed.files.filter((f) => f.key.includes(options.only!));
432
- const order = new Map(files.map((f, i) => [f.key, i]));
433
- const verdicts: FileVerdict[] = [];
434
- const report = (v: FileVerdict) => {
435
- verdicts.push(v);
436
- options.onFile?.(v);
437
- };
438
- const done = (judged: { inMemory: number; perFile: number }): PackageAudit => ({
439
- kind: "audited",
440
- files: verdicts.sort((a, b) => order.get(a.file.key)! - order.get(b.file.key)!),
441
- notAudited: listed.other,
442
- judged,
443
- });
444
- if (files.length === 0) return done({ inMemory: 0, perFile: 0 });
445
-
446
- const command = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")).scripts?.convert;
447
- if (!command) return { kind: "skipped", reason: "no `convert` script applies patches" };
448
- const result = await auditConvertStage(pkgDir, command, files, options, report);
449
- if ("error" in result)
450
- return { kind: "skipped", reason: `baseline build fails: ${result.error}` };
451
- return done(result);
452
- };
453
-
454
- // ---------------------------------------------------------------------------
455
- // names
456
-
457
- /**
458
- * Each model's deferred rename — upstream shape id → the final id in
459
- * `.generated-specs` — from one convert on a scratch copy. Smithy patches
460
- * apply before the rename, so they use the upstream ids.
461
- */
462
- export const renameMaps = async (
463
- pkgDir: string,
464
- ): Promise<
465
- { ok: true; maps: Record<string, Record<string, string>> } | { ok: false; error: string }
466
- > => {
467
- const command = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")).scripts?.convert;
468
- if (!command) return { ok: false, error: "no `convert` script" };
469
- const copy = scratchCopy(pkgDir, 0);
470
- try {
471
- const out = join(copy, ".rename-map.json");
472
- const result = await runConvert(command, copy, { ...process.env, [RENAME_MAP_ENV]: out });
473
- // The maps are recorded before the Smithy patches apply, so a convert
474
- // that fails on a stale patch still names its shapes.
475
- if (existsSync(out)) return { ok: true, maps: JSON.parse(readFileSync(out, "utf8")) };
476
- return result.ok ? { ok: true, maps: {} } : { ok: false, error: result.error };
477
- } finally {
478
- rmSync(copy, { recursive: true, force: true });
479
- }
480
- };