@distilled.cloud/core 1.0.0-rc.12 → 1.0.0-rc.14

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 (276) hide show
  1. package/lib/api.d.ts +4 -4
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +3 -5
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +3 -5
  7. package/lib/category.js.map +1 -1
  8. package/lib/codegen/boolean-string-enums.d.ts +8 -8
  9. package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
  10. package/lib/codegen/boolean-string-enums.js +83 -30
  11. package/lib/codegen/boolean-string-enums.js.map +1 -1
  12. package/lib/codegen/boolean-string-enums.test.js +130 -2
  13. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  14. package/lib/codegen/cli.d.ts +5 -4
  15. package/lib/codegen/cli.d.ts.map +1 -1
  16. package/lib/codegen/cli.js +12 -9
  17. package/lib/codegen/cli.js.map +1 -1
  18. package/lib/codegen/defer-naming.test.d.ts +2 -0
  19. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  20. package/lib/codegen/defer-naming.test.js +105 -0
  21. package/lib/codegen/defer-naming.test.js.map +1 -0
  22. package/lib/codegen/emit.d.ts.map +1 -1
  23. package/lib/codegen/emit.js +1 -3
  24. package/lib/codegen/emit.js.map +1 -1
  25. package/lib/codegen/format.d.ts +0 -12
  26. package/lib/codegen/format.d.ts.map +1 -1
  27. package/lib/codegen/format.js +10 -6
  28. package/lib/codegen/format.js.map +1 -1
  29. package/lib/codegen/generated-at.d.ts +29 -0
  30. package/lib/codegen/generated-at.d.ts.map +1 -0
  31. package/lib/codegen/generated-at.js +78 -0
  32. package/lib/codegen/generated-at.js.map +1 -0
  33. package/lib/codegen/generated-at.test.d.ts +2 -0
  34. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  35. package/lib/codegen/generated-at.test.js +81 -0
  36. package/lib/codegen/generated-at.test.js.map +1 -0
  37. package/lib/codegen/generator.d.ts +24 -5
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +69 -80
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/generator.test.d.ts +2 -0
  42. package/lib/codegen/generator.test.d.ts.map +1 -0
  43. package/lib/codegen/generator.test.js +121 -0
  44. package/lib/codegen/generator.test.js.map +1 -0
  45. package/lib/codegen/graphql-client.d.ts +7 -1
  46. package/lib/codegen/graphql-client.d.ts.map +1 -1
  47. package/lib/codegen/graphql-client.js +264 -148
  48. package/lib/codegen/graphql-client.js.map +1 -1
  49. package/lib/codegen/graphql-client.test.js +98 -238
  50. package/lib/codegen/graphql-client.test.js.map +1 -1
  51. package/lib/codegen/graphql.d.ts.map +1 -1
  52. package/lib/codegen/graphql.js +7 -20
  53. package/lib/codegen/graphql.js.map +1 -1
  54. package/lib/codegen/model-diff.d.ts +10 -0
  55. package/lib/codegen/model-diff.d.ts.map +1 -0
  56. package/lib/codegen/model-diff.js +67 -0
  57. package/lib/codegen/model-diff.js.map +1 -0
  58. package/lib/codegen/naming.d.ts.map +1 -1
  59. package/lib/codegen/naming.js.map +1 -1
  60. package/lib/codegen/openapi-binary.test.d.ts +2 -0
  61. package/lib/codegen/openapi-binary.test.d.ts.map +1 -0
  62. package/lib/codegen/openapi-binary.test.js +67 -0
  63. package/lib/codegen/openapi-binary.test.js.map +1 -0
  64. package/lib/codegen/openapi-cli.d.ts +11 -11
  65. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  66. package/lib/codegen/openapi-cli.js +26 -51
  67. package/lib/codegen/openapi-cli.js.map +1 -1
  68. package/lib/codegen/openapi.d.ts +16 -2
  69. package/lib/codegen/openapi.d.ts.map +1 -1
  70. package/lib/codegen/openapi.js +56 -39
  71. package/lib/codegen/openapi.js.map +1 -1
  72. package/lib/codegen/operations.d.ts.map +1 -1
  73. package/lib/codegen/operations.js.map +1 -1
  74. package/lib/codegen/pagination.d.ts.map +1 -1
  75. package/lib/codegen/pagination.js +2 -4
  76. package/lib/codegen/pagination.js.map +1 -1
  77. package/lib/codegen/patch-audit.d.ts +84 -0
  78. package/lib/codegen/patch-audit.d.ts.map +1 -0
  79. package/lib/codegen/patch-audit.js +366 -0
  80. package/lib/codegen/patch-audit.js.map +1 -0
  81. package/lib/codegen/patch-audit.test.d.ts +2 -0
  82. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  83. package/lib/codegen/patch-audit.test.js +141 -0
  84. package/lib/codegen/patch-audit.test.js.map +1 -0
  85. package/lib/codegen/patches.d.ts +75 -11
  86. package/lib/codegen/patches.d.ts.map +1 -1
  87. package/lib/codegen/patches.js +301 -65
  88. package/lib/codegen/patches.js.map +1 -1
  89. package/lib/codegen/patches.test.js +55 -5
  90. package/lib/codegen/patches.test.js.map +1 -1
  91. package/lib/codegen/prelude.js +1 -1
  92. package/lib/codegen/prelude.js.map +1 -1
  93. package/lib/codegen/proto.d.ts.map +1 -1
  94. package/lib/codegen/proto.js +2 -4
  95. package/lib/codegen/proto.js.map +1 -1
  96. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  97. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  98. package/lib/codegen/protocol-imports.test.js +36 -0
  99. package/lib/codegen/protocol-imports.test.js.map +1 -0
  100. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  101. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  102. package/lib/codegen/rewrite-operation-ids.js +97 -59
  103. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  104. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  105. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  106. package/lib/codegen/spec-path.d.ts +1 -1
  107. package/lib/codegen/spec-path.d.ts.map +1 -1
  108. package/lib/codegen/spec-path.js +1 -1
  109. package/lib/codegen/spec-path.js.map +1 -1
  110. package/lib/codegen/untagged-unions.test.d.ts +2 -0
  111. package/lib/codegen/untagged-unions.test.d.ts.map +1 -0
  112. package/lib/codegen/untagged-unions.test.js +80 -0
  113. package/lib/codegen/untagged-unions.test.js.map +1 -0
  114. package/lib/error-category.d.ts.map +1 -1
  115. package/lib/error-category.js.map +1 -1
  116. package/lib/errors.d.ts +2 -1
  117. package/lib/errors.d.ts.map +1 -1
  118. package/lib/errors.js +9 -4
  119. package/lib/errors.js.map +1 -1
  120. package/lib/fixtures/xml/upstream-validator.json +397 -0
  121. package/lib/graphql.d.ts +292 -205
  122. package/lib/graphql.d.ts.map +1 -1
  123. package/lib/graphql.js +945 -636
  124. package/lib/graphql.js.map +1 -1
  125. package/lib/graphql.test.js +135 -764
  126. package/lib/graphql.test.js.map +1 -1
  127. package/lib/graphql.types.d.ts +10 -0
  128. package/lib/graphql.types.d.ts.map +1 -1
  129. package/lib/graphql.types.js +4 -44
  130. package/lib/graphql.types.js.map +1 -1
  131. package/lib/index.d.ts +27 -0
  132. package/lib/index.d.ts.map +1 -0
  133. package/lib/index.js +27 -0
  134. package/lib/index.js.map +1 -0
  135. package/lib/json-patch.d.ts +13 -6
  136. package/lib/json-patch.d.ts.map +1 -1
  137. package/lib/json-patch.js +34 -19
  138. package/lib/json-patch.js.map +1 -1
  139. package/lib/json-patch.test.d.ts +2 -0
  140. package/lib/json-patch.test.d.ts.map +1 -0
  141. package/lib/json-patch.test.js +65 -0
  142. package/lib/json-patch.test.js.map +1 -0
  143. package/lib/pagination.d.ts +2 -1
  144. package/lib/pagination.d.ts.map +1 -1
  145. package/lib/pagination.js +28 -30
  146. package/lib/pagination.js.map +1 -1
  147. package/lib/pagination.test.d.ts +2 -0
  148. package/lib/pagination.test.d.ts.map +1 -0
  149. package/lib/pagination.test.js +131 -0
  150. package/lib/pagination.test.js.map +1 -0
  151. package/lib/protocol-http.d.ts +30 -16
  152. package/lib/protocol-http.d.ts.map +1 -1
  153. package/lib/protocol-http.js +133 -84
  154. package/lib/protocol-http.js.map +1 -1
  155. package/lib/protocol-http.test.js +141 -1
  156. package/lib/protocol-http.test.js.map +1 -1
  157. package/lib/protocol-rest.d.ts +18 -1
  158. package/lib/protocol-rest.d.ts.map +1 -1
  159. package/lib/protocol-rest.js +32 -21
  160. package/lib/protocol-rest.js.map +1 -1
  161. package/lib/protocol-rest.test.d.ts +2 -0
  162. package/lib/protocol-rest.test.d.ts.map +1 -0
  163. package/lib/protocol-rest.test.js +498 -0
  164. package/lib/protocol-rest.test.js.map +1 -0
  165. package/lib/query.d.ts +29 -0
  166. package/lib/query.d.ts.map +1 -0
  167. package/lib/query.js +27 -0
  168. package/lib/query.js.map +1 -0
  169. package/lib/response-validation.d.ts +67 -0
  170. package/lib/response-validation.d.ts.map +1 -0
  171. package/lib/response-validation.js +76 -0
  172. package/lib/response-validation.js.map +1 -0
  173. package/lib/response-validation.test.d.ts +2 -0
  174. package/lib/response-validation.test.d.ts.map +1 -0
  175. package/lib/response-validation.test.js +72 -0
  176. package/lib/response-validation.test.js.map +1 -0
  177. package/lib/retry-after.d.ts.map +1 -1
  178. package/lib/retry-after.js +1 -1
  179. package/lib/retry-after.js.map +1 -1
  180. package/lib/retry-after.test.d.ts +2 -0
  181. package/lib/retry-after.test.d.ts.map +1 -0
  182. package/lib/retry-after.test.js +204 -0
  183. package/lib/retry-after.test.js.map +1 -0
  184. package/lib/retry.d.ts.map +1 -1
  185. package/lib/retry.js +1 -2
  186. package/lib/retry.js.map +1 -1
  187. package/lib/retry.test.d.ts +2 -0
  188. package/lib/retry.test.d.ts.map +1 -0
  189. package/lib/retry.test.js +407 -0
  190. package/lib/retry.test.js.map +1 -0
  191. package/lib/sdks.test.d.ts +2 -0
  192. package/lib/sdks.test.d.ts.map +1 -0
  193. package/lib/sdks.test.js +76 -0
  194. package/lib/sdks.test.js.map +1 -0
  195. package/lib/testing.d.ts +39 -0
  196. package/lib/testing.d.ts.map +1 -0
  197. package/lib/testing.js +41 -0
  198. package/lib/testing.js.map +1 -0
  199. package/lib/trait.d.ts +29 -9
  200. package/lib/trait.d.ts.map +1 -1
  201. package/lib/trait.js +8 -0
  202. package/lib/trait.js.map +1 -1
  203. package/lib/xml.d.ts +44 -0
  204. package/lib/xml.d.ts.map +1 -0
  205. package/lib/xml.js +311 -0
  206. package/lib/xml.js.map +1 -0
  207. package/lib/xml.test.d.ts +2 -0
  208. package/lib/xml.test.d.ts.map +1 -0
  209. package/lib/xml.test.js +210 -0
  210. package/lib/xml.test.js.map +1 -0
  211. package/package.json +8 -11
  212. package/src/api.ts +38 -55
  213. package/src/category.ts +21 -50
  214. package/src/codegen/boolean-string-enums.test.ts +148 -17
  215. package/src/codegen/boolean-string-enums.ts +81 -32
  216. package/src/codegen/cli.ts +29 -47
  217. package/src/codegen/defer-naming.test.ts +113 -0
  218. package/src/codegen/emit.ts +2 -5
  219. package/src/codegen/format.ts +12 -10
  220. package/src/codegen/generated-at.test.ts +89 -0
  221. package/src/codegen/generated-at.ts +88 -0
  222. package/src/codegen/generator.test.ts +137 -0
  223. package/src/codegen/generator.ts +132 -193
  224. package/src/codegen/graphql-client.test.ts +100 -297
  225. package/src/codegen/graphql-client.ts +302 -210
  226. package/src/codegen/graphql.ts +22 -94
  227. package/src/codegen/model-diff.ts +67 -0
  228. package/src/codegen/naming.ts +1 -2
  229. package/src/codegen/openapi-binary.test.ts +91 -0
  230. package/src/codegen/openapi-cli.ts +38 -79
  231. package/src/codegen/openapi.ts +98 -133
  232. package/src/codegen/operations.ts +2 -5
  233. package/src/codegen/pagination.ts +4 -11
  234. package/src/codegen/patch-audit.test.ts +160 -0
  235. package/src/codegen/patch-audit.ts +480 -0
  236. package/src/codegen/patches.test.ts +73 -15
  237. package/src/codegen/patches.ts +389 -99
  238. package/src/codegen/prelude.ts +1 -1
  239. package/src/codegen/proto.ts +18 -54
  240. package/src/codegen/protocol-imports.test.ts +39 -0
  241. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  242. package/src/codegen/rewrite-operation-ids.ts +111 -98
  243. package/src/codegen/spec-path.ts +3 -6
  244. package/src/codegen/untagged-unions.test.ts +85 -0
  245. package/src/error-category.ts +5 -17
  246. package/src/errors.ts +18 -30
  247. package/src/fixtures/xml/upstream-validator.json +397 -0
  248. package/src/graphql.test.ts +173 -949
  249. package/src/graphql.ts +1468 -1186
  250. package/src/graphql.types.ts +78 -164
  251. package/src/index.ts +26 -0
  252. package/src/json-patch.test.ts +77 -0
  253. package/src/json-patch.ts +54 -60
  254. package/src/pagination.test.ts +169 -0
  255. package/src/pagination.ts +46 -103
  256. package/src/protocol-http.test.ts +178 -9
  257. package/src/protocol-http.ts +174 -163
  258. package/src/protocol-rest.test.ts +703 -0
  259. package/src/protocol-rest.ts +76 -65
  260. package/src/query.ts +39 -0
  261. package/src/response-validation.test.ts +89 -0
  262. package/src/response-validation.ts +107 -0
  263. package/src/retry-after.test.ts +267 -0
  264. package/src/retry-after.ts +4 -10
  265. package/src/retry.test.ts +566 -0
  266. package/src/retry.ts +6 -21
  267. package/src/sdks.test.ts +87 -0
  268. package/src/testing.ts +72 -0
  269. package/src/trait.ts +48 -63
  270. package/src/xml.test.ts +251 -0
  271. package/src/xml.ts +323 -0
  272. package/lib/graphql.fixture.d.ts +0 -249
  273. package/lib/graphql.fixture.d.ts.map +0 -1
  274. package/lib/graphql.fixture.js +0 -240
  275. package/lib/graphql.fixture.js.map +0 -1
  276. package/src/graphql.fixture.ts +0 -371
@@ -1,11 +1,11 @@
1
1
  /**
2
- * RFC-6902 patch application for convert (dev-time only).
3
- *
4
- * OpenAPI ops (`/paths`, `/components`, …) apply to the spec before
5
- * conversion; Smithy ops (`/shapes`, `/metadata`, `/smithy`) apply to the
6
- * model after conversion. `.generated-specs` is the patched model.
7
- * `scripts/generate.ts` does not apply patches.
2
+ * RFC-6902 patch application (dev-time only). Every package's convert ends
3
+ * in {@link finalizeConvert}, which applies the Smithy ops (`/shapes`,
4
+ * `/metadata`, `/smithy`) of `patches/<model>/` to the freshly converted
5
+ * model, under the names the spec gives, then the deferred names; so
6
+ * `.generated-specs` is the patched model and generate never patches.
8
7
  */
8
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
9
9
  import * as fs from "node:fs/promises";
10
10
  import * as path from "node:path";
11
11
  import {
@@ -14,7 +14,12 @@ import {
14
14
  type JsonPatchOperation,
15
15
  type PatchFile,
16
16
  } from "../json-patch.ts";
17
- import { verbNounSmithyModel } from "./rewrite-operation-ids.ts";
17
+ import { diffModels } from "./model-diff.ts";
18
+ import {
19
+ applyDeferredRename,
20
+ RENAME_METADATA_KEY,
21
+ verbNounSmithyModel,
22
+ } from "./rewrite-operation-ids.ts";
18
23
 
19
24
  export type OnStalePatch = "fail" | "warn";
20
25
 
@@ -27,9 +32,7 @@ export interface ApplyPatchesResult {
27
32
 
28
33
  /** Smithy-model JSON pointers — OpenAPI has no `/shapes` tree. */
29
34
  export const isSmithyPatchPath = (pointer: string): boolean =>
30
- pointer.startsWith("/shapes") ||
31
- pointer.startsWith("/metadata") ||
32
- pointer.startsWith("/smithy");
35
+ pointer.startsWith("/shapes") || pointer.startsWith("/metadata") || pointer.startsWith("/smithy");
33
36
 
34
37
  const exists = async (p: string): Promise<boolean> => {
35
38
  try {
@@ -40,20 +43,93 @@ const exists = async (p: string): Promise<boolean> => {
40
43
  }
41
44
  };
42
45
 
46
+ /**
47
+ * Leave patches out of one convert run (dev-time only; the seam
48
+ * `scripts/patches.ts audit` uses to find patches the spec no longer
49
+ * needs). Comma-separated entries:
50
+ *
51
+ * all skip every patch file
52
+ * <file> skip a file — its basename, or a path suffix
53
+ * (`svc/a.json`) when basenames repeat
54
+ * <file>:<index> skip one op of a file, by its index in `patches`
55
+ *
56
+ * Like `DISTILLED_SPECS_LOCAL`, it lives in one command's environment: a
57
+ * model written under it is announced on stderr and must not be committed.
58
+ */
59
+ export const SKIP_PATCHES_ENV = "DISTILLED_SKIP_PATCHES";
60
+
61
+ interface SkipList {
62
+ readonly all: boolean;
63
+ readonly files: readonly string[];
64
+ readonly ops: ReadonlyMap<string, ReadonlySet<number>>;
65
+ }
66
+
67
+ const parseSkipList = (): SkipList | undefined => {
68
+ const raw = (process.env[SKIP_PATCHES_ENV] ?? "").trim();
69
+ if (raw === "") return undefined;
70
+ const files: string[] = [];
71
+ const ops = new Map<string, Set<number>>();
72
+ for (const entry of raw.split(",")) {
73
+ const item = entry.trim();
74
+ if (item === "") continue;
75
+ if (item === "all") return { all: true, files: [], ops: new Map() };
76
+ const at = item.lastIndexOf(":");
77
+ const index = at === -1 ? NaN : Number(item.slice(at + 1));
78
+ if (Number.isInteger(index) && index >= 0) {
79
+ const file = item.slice(0, at);
80
+ ops.set(file, (ops.get(file) ?? new Set()).add(index));
81
+ } else {
82
+ files.push(item);
83
+ }
84
+ }
85
+ return { all: false, files, ops };
86
+ };
87
+
88
+ const skipMatches = (file: string, entry: string): boolean =>
89
+ path.basename(file) === entry || file.endsWith(path.sep + entry);
90
+
91
+ let skipAnnounced = false;
92
+
93
+ const skipList = (): SkipList | undefined => {
94
+ const list = parseSkipList();
95
+ if (list && !skipAnnounced) {
96
+ skipAnnounced = true;
97
+ // stderr for the same reason as the DISTILLED_SPECS_LOCAL notice.
98
+ console.error(
99
+ `⚠ ${SKIP_PATCHES_ENV}=${process.env[SKIP_PATCHES_ENV]} — this model is missing patches; do not commit it.`,
100
+ );
101
+ }
102
+ return list;
103
+ };
104
+
105
+ const skipsFile = (list: SkipList | undefined, file: string): boolean =>
106
+ list !== undefined && (list.all || list.files.some((entry) => skipMatches(file, entry)));
107
+
108
+ const skipsOp = (list: SkipList | undefined, file: string, index: number): boolean => {
109
+ if (list === undefined) return false;
110
+ for (const [entry, indices] of list.ops) {
111
+ if (indices.has(index) && skipMatches(file, entry)) return true;
112
+ }
113
+ return false;
114
+ };
115
+
43
116
  /**
44
117
  * RFC-6902 files in `dir`: every `*.json`, `*.manual.json` last (those
45
- * usually target post-rename shape names). Missing dir → `[]`.
118
+ * usually target post-rename shape names). Missing dir → `[]`. Files named
119
+ * by {@link SKIP_PATCHES_ENV} are left out.
46
120
  */
47
121
  export const listRfc6902PatchFiles = async (dir: string): Promise<string[]> => {
48
122
  if (!(await exists(dir))) return [];
123
+ const skip = skipList();
49
124
  return (await fs.readdir(dir))
50
125
  .filter((f) => f.endsWith(".json"))
51
126
  .sort(
52
127
  (a, b) =>
53
- Number(a.endsWith(".manual.json")) -
54
- Number(b.endsWith(".manual.json")) || a.localeCompare(b),
128
+ Number(a.endsWith(".manual.json")) - Number(b.endsWith(".manual.json")) ||
129
+ a.localeCompare(b),
55
130
  )
56
- .map((f) => path.join(dir, f));
131
+ .map((f) => path.join(dir, f))
132
+ .filter((f) => !skipsFile(skip, f));
57
133
  };
58
134
 
59
135
  export const applyRfc6902Files = async (
@@ -73,12 +149,14 @@ export const applyRfc6902Files = async (
73
149
  stale: 0,
74
150
  errors: [],
75
151
  };
152
+ const skip = skipList();
76
153
  for (const file of files) {
154
+ if (skipsFile(skip, file)) continue;
77
155
  const parsed = JSON.parse(await fs.readFile(file, "utf8")) as PatchFile;
78
156
  const label = opts.label?.(file) ?? path.basename(file);
79
157
  result.files++;
80
- for (const patchOp of parsed.patches ?? []) {
81
- if (!include(patchOp)) continue;
158
+ for (const [index, patchOp] of (parsed.patches ?? []).entries()) {
159
+ if (!include(patchOp) || skipsOp(skip, file, index)) continue;
82
160
  try {
83
161
  applyOperation(target, patchOp);
84
162
  result.applied++;
@@ -107,23 +185,16 @@ export const applyRfc6902Files = async (
107
185
  * longer exists and append operation shapes the list is missing, keeping
108
186
  * the existing order. Returns the number of services whose list changed.
109
187
  */
110
- export const syncServiceOperations = (model: {
111
- shapes?: Record<string, any>;
112
- }): number => {
188
+ export const syncServiceOperations = (model: { shapes?: Record<string, any> }): number => {
113
189
  const shapes = model.shapes ?? {};
114
- const opIds = Object.keys(shapes).filter(
115
- (id) => shapes[id]?.type === "operation",
116
- );
190
+ const opIds = Object.keys(shapes).filter((id) => shapes[id]?.type === "operation");
117
191
  let changed = 0;
118
192
  for (const def of Object.values(shapes)) {
119
193
  if (def?.type !== "service") continue;
120
194
  const current: Array<{ target: string }> = def.operations ?? [];
121
195
  const kept = current.filter((o) => shapes[o.target]?.type === "operation");
122
196
  const listed = new Set(kept.map((o) => o.target));
123
- const after = [
124
- ...kept,
125
- ...opIds.filter((id) => !listed.has(id)).map((target) => ({ target })),
126
- ];
197
+ const after = [...kept, ...opIds.filter((id) => !listed.has(id)).map((target) => ({ target }))];
127
198
  if (JSON.stringify(current) !== JSON.stringify(after)) {
128
199
  def.operations = after;
129
200
  changed++;
@@ -138,9 +209,7 @@ export const syncServiceOperations = (model: {
138
209
  * A convert that produces any is broken — generate would emit references
139
210
  * to types that do not exist.
140
211
  */
141
- export const danglingTargets = (model: {
142
- shapes?: Record<string, any>;
143
- }): string[] => {
212
+ export const danglingTargets = (model: { shapes?: Record<string, any> }): string[] => {
144
213
  const shapes = model.shapes ?? {};
145
214
  const ids = new Set(Object.keys(shapes));
146
215
  const out: string[] = [];
@@ -150,9 +219,7 @@ export const danglingTargets = (model: {
150
219
  return;
151
220
  }
152
221
  if (node === null || typeof node !== "object") return;
153
- for (const [key, value] of Object.entries(
154
- node as Record<string, unknown>,
155
- )) {
222
+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
156
223
  if (key === "target" && typeof value === "string") {
157
224
  if (!value.startsWith("smithy.") && !ids.has(value)) {
158
225
  out.push(`${owner} → ${value}`);
@@ -166,6 +233,159 @@ export const danglingTargets = (model: {
166
233
  return out;
167
234
  };
168
235
 
236
+ export interface FinalizeOptions {
237
+ readonly root: string;
238
+ readonly outDir?: string;
239
+ readonly patchesDir?: string | false;
240
+ /**
241
+ * The directory holding a model's patches, relative to `patchesDir`.
242
+ * Default `<resource>`; `""` for a single-model package whose patches sit
243
+ * at the root of `patchesDir`; `undefined` for none.
244
+ */
245
+ readonly patchesFor?: (resource: string) => string | undefined;
246
+ readonly exclude?: (file: string) => boolean;
247
+ readonly include?: (resource: string) => boolean;
248
+ readonly transform?: (model: any, resource: string) => string | void;
249
+ readonly operationNaming?: "as-is" | "verbNoun";
250
+ readonly onStalePatch?: OnStalePatch;
251
+ }
252
+
253
+ /** A patch file read once, with only its Smithy ops. */
254
+ interface LoadedPatchFile {
255
+ /** Path relative to the patches dir, `/`-separated — the audit's key. */
256
+ readonly key: string;
257
+ readonly file: string;
258
+ readonly ops: readonly JsonPatchOperation[];
259
+ }
260
+
261
+ const loadSmithyPatches = async (
262
+ patchesDir: string,
263
+ dir: string | undefined,
264
+ ): Promise<LoadedPatchFile[]> => {
265
+ if (dir === undefined) return [];
266
+ const out: LoadedPatchFile[] = [];
267
+ for (const file of await listRfc6902PatchFiles(path.join(patchesDir, dir))) {
268
+ const parsed = JSON.parse(await fs.readFile(file, "utf8")) as PatchFile;
269
+ const key = path.relative(patchesDir, file).split(path.sep).join("/");
270
+ const spec = (parsed.patches ?? []).find((op) => !isSmithyPatchPath(op.path));
271
+ if (spec) {
272
+ // Patches edit the converted model under upstream names, never the
273
+ // spec: one kind of patch, and one the audit can judge in memory.
274
+ throw new Error(
275
+ `patches/${key} [${spec.op} ${spec.path}]: patches target the Smithy model (/shapes, /metadata), not the spec — see the distilled-sdk-patch skill`,
276
+ );
277
+ }
278
+ out.push({ key, file, ops: parsed.patches ?? [] });
279
+ }
280
+ return out;
281
+ };
282
+
283
+ type FinalizeRun =
284
+ | { readonly ok: true; readonly model: any }
285
+ | { readonly ok: false; readonly stage: "patch" | "rename" | "dangling"; readonly error: string };
286
+
287
+ /**
288
+ * One model through the finalize steps: Smithy patches, verbNoun names,
289
+ * the package's transform, the service operation list, and the reference
290
+ * check. `skip` leaves out a patch file (`key`) or one of its ops
291
+ * (`key:index`); `quiet` silences the progress lines for audit re-runs.
292
+ */
293
+ const finalizeModel = (
294
+ model: any,
295
+ resource: string,
296
+ patches: readonly LoadedPatchFile[],
297
+ o: FinalizeOptions,
298
+ skip: { readonly key: string; readonly index?: number } | undefined,
299
+ quiet: boolean,
300
+ ): FinalizeRun => {
301
+ const log = quiet ? () => {} : console.log;
302
+ const deferred = model.metadata?.[RENAME_METADATA_KEY];
303
+ if (deferred && !quiet) recordRename(resource, deferred);
304
+ const envSkip = skipList();
305
+ let files = 0;
306
+ let applied = 0;
307
+ let stale = 0;
308
+ const errors: string[] = [];
309
+ for (const p of patches) {
310
+ if (skip && skip.key === p.key && skip.index === undefined) continue;
311
+ files++;
312
+ for (const [index, op] of p.ops.entries()) {
313
+ if (skip && skip.key === p.key && skip.index === index) continue;
314
+ if (skipsOp(envSkip, p.file, index)) continue;
315
+ try {
316
+ // A cloned op: `add`/`replace` insert the value by reference, and
317
+ // the audit applies the same parsed ops to many fresh models.
318
+ applyOperation(model, structuredClone(op));
319
+ applied++;
320
+ } catch (e) {
321
+ const line = `${p.key} [${op.op} ${op.path}]`;
322
+ const msg = e instanceof Error ? e.message : String(e);
323
+ if (isStaleTargetError(e) && o.onStalePatch === "warn") {
324
+ stale++;
325
+ if (!quiet) console.warn(` ⚠️ stale: ${line}`);
326
+ } else {
327
+ errors.push(`${line}: ${isStaleTargetError(e) ? `stale target (${msg})` : msg}`);
328
+ }
329
+ }
330
+ }
331
+ }
332
+ if (errors.length) {
333
+ if (!quiet) for (const err of errors) console.error(`❌ bad patch: ${err}`);
334
+ return {
335
+ ok: false,
336
+ stage: "patch",
337
+ error: `${errors.length} patch operation(s) failed for ${resource}: ${errors[0]}`,
338
+ };
339
+ }
340
+ if (applied > 0) {
341
+ log(
342
+ ` patched ${resource}: ${files} file(s), ${applied} op(s)` +
343
+ (stale ? `, ${stale} stale` : ""),
344
+ );
345
+ }
346
+
347
+ try {
348
+ const renamed = applyDeferredRename(model);
349
+ if (renamed > 0) log(` named ${resource}: ${renamed} shape(s)`);
350
+ } catch (e) {
351
+ const error = `${resource}: ${e instanceof Error ? e.message : String(e)}`;
352
+ if (!quiet) console.error(`❌ ${error}`);
353
+ return { ok: false, stage: "rename", error };
354
+ }
355
+
356
+ if ((o.operationNaming ?? "verbNoun") === "verbNoun") {
357
+ const { renamed, collisions } = verbNounSmithyModel(model);
358
+ if (renamed > 0) log(` verbNoun ${resource}: renamed ${renamed} operation(s)`);
359
+ if (!quiet) {
360
+ for (const c of collisions) {
361
+ console.warn(` ⚠️ verbNoun collision ${resource}: ${c} (kept original)`);
362
+ }
363
+ }
364
+ }
365
+
366
+ const note = o.transform?.(model, resource);
367
+ if (note) log(` ${note}`);
368
+
369
+ syncServiceOperations(model);
370
+
371
+ const dangling = danglingTargets(model);
372
+ if (dangling.length) {
373
+ if (!quiet) {
374
+ for (const d of dangling.slice(0, 5)) console.error(` ❌ ${d}`);
375
+ if (dangling.length > 5) console.error(` … ${dangling.length - 5} more`);
376
+ }
377
+ return {
378
+ ok: false,
379
+ stage: "dangling",
380
+ error: `${resource}: ${dangling.length} dangling target(s), e.g. ${dangling[0]}`,
381
+ };
382
+ }
383
+ model.metadata = { ...model.metadata, [FINALIZED_KEY]: true };
384
+ return { ok: true, model };
385
+ };
386
+
387
+ const modelText = (model: unknown): string => `${JSON.stringify(model, null, 2)}\n`;
388
+
169
389
  /**
170
390
  * Last step of every convert: Smithy RFC-6902 patches, then verbNoun
171
391
  * operation names, then an optional model transform, then a reference
@@ -176,24 +396,17 @@ export const danglingTargets = (model: {
176
396
  * ops that are not idempotent, and a `transform` may not be either, so
177
397
  * running this over a model that already went through it is an error —
178
398
  * re-run the package's `convert` instead.
399
+ *
400
+ * Under {@link PATCH_AUDIT_ENV} it also judges the requested patch files
401
+ * in memory (see `./patch-audit.ts`).
179
402
  */
180
- export const finalizeConvert = async (o: {
181
- readonly root: string;
182
- readonly outDir?: string;
183
- readonly patchesDir?: string | false;
184
- readonly exclude?: (file: string) => boolean;
185
- readonly include?: (resource: string) => boolean;
186
- readonly transform?: (model: any, resource: string) => string | void;
187
- readonly operationNaming?: "as-is" | "verbNoun";
188
- readonly onStalePatch?: OnStalePatch;
189
- }): Promise<void> => {
403
+ export const finalizeConvert = async (o: FinalizeOptions): Promise<void> => {
404
+ const specsRoot = path.resolve(o.root, ".generated-specs");
190
405
  const specsDir = path.resolve(o.root, o.outDir ?? ".generated-specs");
191
406
  if (!(await exists(specsDir))) return;
192
407
  const patchesDir =
193
- o.patchesDir === false
194
- ? undefined
195
- : path.resolve(o.root, o.patchesDir ?? "patches");
196
- const naming = o.operationNaming ?? "verbNoun";
408
+ o.patchesDir === false ? undefined : path.resolve(o.root, o.patchesDir ?? "patches");
409
+ const audit = patchesDir ? await readAuditRequest() : undefined;
197
410
 
198
411
  const walk = async (dir: string): Promise<string[]> => {
199
412
  const out: string[] = [];
@@ -201,10 +414,7 @@ export const finalizeConvert = async (o: {
201
414
  const p = path.join(dir, ent.name);
202
415
  if (ent.isDirectory()) {
203
416
  out.push(...(await walk(p)));
204
- } else if (
205
- ent.name.endsWith(".json") &&
206
- !(o.exclude?.(ent.name) ?? false)
207
- ) {
417
+ } else if (ent.name.endsWith(".json") && !(o.exclude?.(ent.name) ?? false)) {
208
418
  out.push(p);
209
419
  }
210
420
  }
@@ -216,66 +426,34 @@ export const finalizeConvert = async (o: {
216
426
  for (const modelPath of files) {
217
427
  const resource = path.basename(modelPath, ".json");
218
428
  if (o.include && !o.include(resource)) continue;
219
- const model = JSON.parse(await fs.readFile(modelPath, "utf8"));
429
+ const text = await fs.readFile(modelPath, "utf8");
430
+ const model = JSON.parse(text);
220
431
  if (model.metadata?.[FINALIZED_KEY]) {
221
432
  throw new Error(
222
433
  `${path.relative(o.root, modelPath)} was already finalized — finalizeConvert is not idempotent; re-run this package's convert from the spec instead`,
223
434
  );
224
435
  }
225
- if (patchesDir) {
226
- const patchFiles = await listRfc6902PatchFiles(
227
- path.join(patchesDir, resource),
228
- );
229
- const applied = await applyRfc6902Files(model, patchFiles, {
230
- onStalePatch: o.onStalePatch,
231
- include: (op) => isSmithyPatchPath(op.path),
232
- label: (f) => `${resource}/${path.basename(f)}`,
233
- });
234
- if (applied.errors.length) {
235
- for (const err of applied.errors) console.error(`❌ bad patch: ${err}`);
236
- throw new Error(
237
- `${applied.errors.length} patch operation(s) failed for ${resource} — fix the pointers or delete the patch`,
238
- );
239
- }
240
- if (applied.applied > 0) {
241
- console.log(
242
- ` patched ${resource}: ${applied.files} file(s), ${applied.applied} op(s)` +
243
- (applied.stale ? `, ${applied.stale} stale` : ""),
244
- );
436
+ const patches = patchesDir
437
+ ? await loadSmithyPatches(patchesDir, o.patchesFor ? o.patchesFor(resource) : resource)
438
+ : [];
439
+ const run = finalizeModel(model, resource, patches, o, undefined, false);
440
+ const label = path.relative(specsRoot, modelPath).split(path.sep).join("/");
441
+ if (!run.ok) {
442
+ if (audit) auditModel(audit, label, resource, text, patches, o, run);
443
+ if (run.stage === "patch") {
444
+ throw new Error(`${run.error.split(": ")[0]} — fix the pointers or delete the patch`);
245
445
  }
246
- }
247
-
248
- if (naming === "verbNoun") {
249
- const { renamed, collisions } = verbNounSmithyModel(model);
250
- if (renamed > 0) {
251
- console.log(` verbNoun ${resource}: renamed ${renamed} operation(s)`);
252
- }
253
- for (const c of collisions) {
254
- console.warn(
255
- ` ⚠️ verbNoun collision ${resource}: ${c} (kept original)`,
256
- );
257
- }
258
- }
259
-
260
- const note = o.transform?.(model, resource);
261
- if (note) console.log(` ${note}`);
262
-
263
- syncServiceOperations(model);
264
-
265
- const dangling = danglingTargets(model);
266
- if (dangling.length) {
267
- broken.push(`${resource}: ${dangling.length} dangling target(s)`);
268
- for (const d of dangling.slice(0, 5)) console.error(` ❌ ${d}`);
269
- if (dangling.length > 5) {
270
- console.error(` … ${dangling.length - 5} more`);
446
+ if (run.stage === "rename") {
447
+ throw new Error(`${run.error} — a patch added a shape under a name the rename needs`);
271
448
  }
449
+ broken.push(run.error.split(", e.g.")[0]!);
272
450
  // Leave the unfinalized model on disk for inspection; never stamp
273
451
  // a model that generate cannot compile.
274
452
  continue;
275
453
  }
276
-
277
- model.metadata = { ...model.metadata, [FINALIZED_KEY]: true };
278
- await fs.writeFile(modelPath, `${JSON.stringify(model, null, 2)}\n`);
454
+ const finalized = modelText(run.model);
455
+ await fs.writeFile(modelPath, finalized);
456
+ if (audit) auditModel(audit, label, resource, text, patches, o, { ok: true, text: finalized });
279
457
  }
280
458
  if (broken.length) {
281
459
  throw new Error(
@@ -284,6 +462,118 @@ export const finalizeConvert = async (o: {
284
462
  }
285
463
  };
286
464
 
465
+ /**
466
+ * Path of a JSON file finalizeConvert adds each model's deferred rename to
467
+ * (`{ <model>: { <upstream id>: <final id> } }`). Set by
468
+ * `pnpm patches:names`, which tells a patch author the upstream name of a
469
+ * shape they see in `.generated-specs`.
470
+ */
471
+ export const RENAME_MAP_ENV = "DISTILLED_RENAME_MAP";
472
+
473
+ const recordRename = (resource: string, rename: Record<string, string>): void => {
474
+ const file = process.env[RENAME_MAP_ENV];
475
+ if (!file) return;
476
+ const all = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
477
+ all[resource] = { ...all[resource], ...rename };
478
+ writeFileSync(file, JSON.stringify(all));
479
+ };
480
+
481
+ // ---------------------------------------------------------------------------
482
+ // in-memory patch audit
483
+
484
+ /**
485
+ * Path of a JSON request (`{ keys: string[], ops: boolean }`) asking
486
+ * finalizeConvert to judge those patch files in memory. Set only by
487
+ * `pnpm patches:audit` on a scratch copy of the package; the models it
488
+ * writes are the normal, fully patched ones.
489
+ *
490
+ * Each verdict is printed to stdout as one line, {@link PATCH_AUDIT_MARKER}
491
+ * followed by JSON. A requested key no finalizeConvert call owns (its ops
492
+ * are applied somewhere else, e.g. before conversion) gets no line, and the
493
+ * audit judges it by re-running convert.
494
+ */
495
+ export const PATCH_AUDIT_ENV = "DISTILLED_PATCH_AUDIT";
496
+ export const PATCH_AUDIT_MARKER = "@@distilled-patch-audit ";
497
+
498
+ interface AuditRequest {
499
+ readonly keys: ReadonlySet<string>;
500
+ readonly ops: boolean;
501
+ }
502
+
503
+ /** One finalizeConvert's answer for one patch file. */
504
+ export interface InMemoryVerdict {
505
+ readonly key: string;
506
+ /** Path of the model relative to the package's `.generated-specs`. */
507
+ readonly model: string;
508
+ readonly verdict:
509
+ | { readonly kind: "unused" }
510
+ | { readonly kind: "needed"; readonly diff: readonly string[] }
511
+ | { readonly kind: "depended"; readonly error: string }
512
+ | { readonly kind: "baseline"; readonly error: string };
513
+ readonly deadOps: readonly number[];
514
+ }
515
+
516
+ const readAuditRequest = async (): Promise<AuditRequest | undefined> => {
517
+ const file = process.env[PATCH_AUDIT_ENV];
518
+ if (!file) return undefined;
519
+ const raw = JSON.parse(await fs.readFile(file, "utf8")) as { keys: string[]; ops?: boolean };
520
+ return { keys: new Set(raw.keys), ops: raw.ops === true };
521
+ };
522
+
523
+ const emitVerdict = (v: InMemoryVerdict): void => {
524
+ process.stdout.write(`${PATCH_AUDIT_MARKER}${JSON.stringify(v)}\n`);
525
+ };
526
+
527
+ const auditModel = (
528
+ audit: AuditRequest,
529
+ model: string,
530
+ resource: string,
531
+ text: string,
532
+ patches: readonly LoadedPatchFile[],
533
+ o: FinalizeOptions,
534
+ baseline:
535
+ | { readonly ok: true; readonly text: string }
536
+ | { readonly ok: false; readonly error: string },
537
+ ): void => {
538
+ const owned = patches.filter((p) => audit.keys.has(p.key) && p.ops.length > 0);
539
+ for (const p of owned) {
540
+ if (!baseline.ok) {
541
+ emitVerdict({
542
+ key: p.key,
543
+ model,
544
+ verdict: { kind: "baseline", error: baseline.error },
545
+ deadOps: [],
546
+ });
547
+ continue;
548
+ }
549
+ const judge = (index?: number): InMemoryVerdict["verdict"] => {
550
+ const run = finalizeModel(
551
+ JSON.parse(text),
552
+ resource,
553
+ patches,
554
+ o,
555
+ { key: p.key, index },
556
+ true,
557
+ );
558
+ if (!run.ok) return { kind: "depended", error: run.error };
559
+ const without = modelText(run.model);
560
+ if (without === baseline.text) return { kind: "unused" };
561
+ const diff = diffModels(new Map([[model, baseline.text]]), new Map([[model, without]]));
562
+ // The committed model is compared byte for byte, so a patch that only
563
+ // orders keys (`before`, a `move` onto itself) is needed too.
564
+ return { kind: "needed", diff: diff.length === 0 ? ["(key order only)"] : diff };
565
+ };
566
+ const verdict = judge();
567
+ const deadOps: number[] = [];
568
+ if (audit.ops && verdict.kind === "needed" && p.ops.length > 1) {
569
+ for (let index = 0; index < p.ops.length; index++) {
570
+ if (judge(index).kind === "unused") deadOps.push(index);
571
+ }
572
+ }
573
+ emitVerdict({ key: p.key, model, verdict, deadOps });
574
+ }
575
+ };
576
+
287
577
  /**
288
578
  * Metadata marker stamped by {@link finalizeConvert}. Guards against a
289
579
  * second pass over the same file (see the note on finalizeConvert).
@@ -1,3 +1,4 @@
1
+ import { isForwardRef } from "./graph.ts";
1
2
  /**
2
3
  * Smithy prelude scalar baselines + reference resolvers for the SDK
3
4
  * generators (dev-time only).
@@ -8,7 +9,6 @@
8
9
  * fall back here for untyped scalars.
9
10
  */
10
11
  import { isPrelude, local } from "./naming.ts";
11
- import { isForwardRef } from "./graph.ts";
12
12
 
13
13
  /** Prelude shape → schema expression (JSON-wire flavor). */
14
14
  export const JSON_PRELUDE: Record<string, string> = {