@distilled.cloud/core 1.0.0-rc.13 → 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 (235) 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.map +1 -1
  9. package/lib/codegen/boolean-string-enums.js +2 -6
  10. package/lib/codegen/boolean-string-enums.js.map +1 -1
  11. package/lib/codegen/boolean-string-enums.test.js +3 -5
  12. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  13. package/lib/codegen/cli.d.ts +5 -4
  14. package/lib/codegen/cli.d.ts.map +1 -1
  15. package/lib/codegen/cli.js +12 -9
  16. package/lib/codegen/cli.js.map +1 -1
  17. package/lib/codegen/defer-naming.test.d.ts +2 -0
  18. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  19. package/lib/codegen/defer-naming.test.js +105 -0
  20. package/lib/codegen/defer-naming.test.js.map +1 -0
  21. package/lib/codegen/emit.d.ts.map +1 -1
  22. package/lib/codegen/emit.js +1 -3
  23. package/lib/codegen/emit.js.map +1 -1
  24. package/lib/codegen/format.d.ts +0 -12
  25. package/lib/codegen/format.d.ts.map +1 -1
  26. package/lib/codegen/format.js +10 -6
  27. package/lib/codegen/format.js.map +1 -1
  28. package/lib/codegen/generated-at.d.ts +29 -0
  29. package/lib/codegen/generated-at.d.ts.map +1 -0
  30. package/lib/codegen/generated-at.js +78 -0
  31. package/lib/codegen/generated-at.js.map +1 -0
  32. package/lib/codegen/generated-at.test.d.ts +2 -0
  33. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  34. package/lib/codegen/generated-at.test.js +81 -0
  35. package/lib/codegen/generated-at.test.js.map +1 -0
  36. package/lib/codegen/generator.d.ts +4 -2
  37. package/lib/codegen/generator.d.ts.map +1 -1
  38. package/lib/codegen/generator.js +37 -75
  39. package/lib/codegen/generator.js.map +1 -1
  40. package/lib/codegen/generator.test.js +4 -9
  41. package/lib/codegen/generator.test.js.map +1 -1
  42. package/lib/codegen/graphql-client.d.ts.map +1 -1
  43. package/lib/codegen/graphql-client.js +12 -33
  44. package/lib/codegen/graphql-client.js.map +1 -1
  45. package/lib/codegen/graphql-client.test.js +4 -12
  46. package/lib/codegen/graphql-client.test.js.map +1 -1
  47. package/lib/codegen/graphql.d.ts.map +1 -1
  48. package/lib/codegen/graphql.js +7 -20
  49. package/lib/codegen/graphql.js.map +1 -1
  50. package/lib/codegen/model-diff.d.ts +10 -0
  51. package/lib/codegen/model-diff.d.ts.map +1 -0
  52. package/lib/codegen/model-diff.js +67 -0
  53. package/lib/codegen/model-diff.js.map +1 -0
  54. package/lib/codegen/naming.d.ts.map +1 -1
  55. package/lib/codegen/naming.js.map +1 -1
  56. package/lib/codegen/openapi-binary.test.js +1 -1
  57. package/lib/codegen/openapi-binary.test.js.map +1 -1
  58. package/lib/codegen/openapi-cli.d.ts +11 -11
  59. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  60. package/lib/codegen/openapi-cli.js +26 -51
  61. package/lib/codegen/openapi-cli.js.map +1 -1
  62. package/lib/codegen/openapi.d.ts +9 -1
  63. package/lib/codegen/openapi.d.ts.map +1 -1
  64. package/lib/codegen/openapi.js +48 -42
  65. package/lib/codegen/openapi.js.map +1 -1
  66. package/lib/codegen/operations.d.ts.map +1 -1
  67. package/lib/codegen/operations.js.map +1 -1
  68. package/lib/codegen/pagination.d.ts.map +1 -1
  69. package/lib/codegen/pagination.js +2 -4
  70. package/lib/codegen/pagination.js.map +1 -1
  71. package/lib/codegen/patch-audit.d.ts +84 -0
  72. package/lib/codegen/patch-audit.d.ts.map +1 -0
  73. package/lib/codegen/patch-audit.js +366 -0
  74. package/lib/codegen/patch-audit.js.map +1 -0
  75. package/lib/codegen/patch-audit.test.d.ts +2 -0
  76. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  77. package/lib/codegen/patch-audit.test.js +141 -0
  78. package/lib/codegen/patch-audit.test.js.map +1 -0
  79. package/lib/codegen/patches.d.ts +59 -10
  80. package/lib/codegen/patches.d.ts.map +1 -1
  81. package/lib/codegen/patches.js +233 -63
  82. package/lib/codegen/patches.js.map +1 -1
  83. package/lib/codegen/patches.test.js +8 -4
  84. package/lib/codegen/patches.test.js.map +1 -1
  85. package/lib/codegen/prelude.js +1 -1
  86. package/lib/codegen/prelude.js.map +1 -1
  87. package/lib/codegen/proto.d.ts.map +1 -1
  88. package/lib/codegen/proto.js +2 -4
  89. package/lib/codegen/proto.js.map +1 -1
  90. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  91. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  92. package/lib/codegen/protocol-imports.test.js +36 -0
  93. package/lib/codegen/protocol-imports.test.js.map +1 -0
  94. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  95. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  96. package/lib/codegen/rewrite-operation-ids.js +97 -59
  97. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  98. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  99. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  100. package/lib/codegen/spec-path.d.ts +1 -1
  101. package/lib/codegen/spec-path.d.ts.map +1 -1
  102. package/lib/codegen/spec-path.js +1 -1
  103. package/lib/codegen/spec-path.js.map +1 -1
  104. package/lib/codegen/untagged-unions.test.js +1 -1
  105. package/lib/codegen/untagged-unions.test.js.map +1 -1
  106. package/lib/error-category.d.ts.map +1 -1
  107. package/lib/error-category.js.map +1 -1
  108. package/lib/errors.d.ts.map +1 -1
  109. package/lib/errors.js +7 -5
  110. package/lib/errors.js.map +1 -1
  111. package/lib/graphql.d.ts +4 -8
  112. package/lib/graphql.d.ts.map +1 -1
  113. package/lib/graphql.js +20 -48
  114. package/lib/graphql.js.map +1 -1
  115. package/lib/graphql.test.js +6 -6
  116. package/lib/graphql.test.js.map +1 -1
  117. package/lib/graphql.types.d.ts.map +1 -1
  118. package/lib/graphql.types.js.map +1 -1
  119. package/lib/json-patch.d.ts +13 -6
  120. package/lib/json-patch.d.ts.map +1 -1
  121. package/lib/json-patch.js +34 -19
  122. package/lib/json-patch.js.map +1 -1
  123. package/lib/json-patch.test.d.ts +2 -0
  124. package/lib/json-patch.test.d.ts.map +1 -0
  125. package/lib/json-patch.test.js +65 -0
  126. package/lib/json-patch.test.js.map +1 -0
  127. package/lib/pagination.d.ts.map +1 -1
  128. package/lib/pagination.js +6 -16
  129. package/lib/pagination.js.map +1 -1
  130. package/lib/pagination.test.js +3 -6
  131. package/lib/pagination.test.js.map +1 -1
  132. package/lib/protocol-http.d.ts +20 -1
  133. package/lib/protocol-http.d.ts.map +1 -1
  134. package/lib/protocol-http.js +41 -47
  135. package/lib/protocol-http.js.map +1 -1
  136. package/lib/protocol-http.test.js +20 -10
  137. package/lib/protocol-http.test.js.map +1 -1
  138. package/lib/protocol-rest.d.ts.map +1 -1
  139. package/lib/protocol-rest.js +9 -18
  140. package/lib/protocol-rest.js.map +1 -1
  141. package/lib/protocol-rest.test.d.ts +2 -0
  142. package/lib/protocol-rest.test.d.ts.map +1 -0
  143. package/lib/protocol-rest.test.js +498 -0
  144. package/lib/protocol-rest.test.js.map +1 -0
  145. package/lib/response-validation.d.ts.map +1 -1
  146. package/lib/response-validation.js.map +1 -1
  147. package/lib/response-validation.test.js +10 -5
  148. package/lib/response-validation.test.js.map +1 -1
  149. package/lib/retry-after.d.ts.map +1 -1
  150. package/lib/retry-after.js +1 -1
  151. package/lib/retry-after.js.map +1 -1
  152. package/lib/retry-after.test.d.ts +2 -0
  153. package/lib/retry-after.test.d.ts.map +1 -0
  154. package/lib/retry-after.test.js +204 -0
  155. package/lib/retry-after.test.js.map +1 -0
  156. package/lib/retry.d.ts.map +1 -1
  157. package/lib/retry.js +1 -2
  158. package/lib/retry.js.map +1 -1
  159. package/lib/retry.test.d.ts +2 -0
  160. package/lib/retry.test.d.ts.map +1 -0
  161. package/lib/retry.test.js +407 -0
  162. package/lib/retry.test.js.map +1 -0
  163. package/lib/sdks.test.d.ts +2 -0
  164. package/lib/sdks.test.d.ts.map +1 -0
  165. package/lib/sdks.test.js +76 -0
  166. package/lib/sdks.test.js.map +1 -0
  167. package/lib/testing.d.ts +2 -2
  168. package/lib/testing.d.ts.map +1 -1
  169. package/lib/testing.js +1 -1
  170. package/lib/testing.js.map +1 -1
  171. package/lib/trait.d.ts.map +1 -1
  172. package/lib/trait.js.map +1 -1
  173. package/lib/xml.d.ts.map +1 -1
  174. package/lib/xml.js +3 -7
  175. package/lib/xml.js.map +1 -1
  176. package/lib/xml.test.js +11 -12
  177. package/lib/xml.test.js.map +1 -1
  178. package/package.json +7 -10
  179. package/src/api.ts +38 -55
  180. package/src/category.ts +21 -50
  181. package/src/codegen/boolean-string-enums.test.ts +12 -28
  182. package/src/codegen/boolean-string-enums.ts +2 -10
  183. package/src/codegen/cli.ts +29 -47
  184. package/src/codegen/defer-naming.test.ts +113 -0
  185. package/src/codegen/emit.ts +2 -5
  186. package/src/codegen/format.ts +12 -10
  187. package/src/codegen/generated-at.test.ts +89 -0
  188. package/src/codegen/generated-at.ts +88 -0
  189. package/src/codegen/generator.test.ts +8 -22
  190. package/src/codegen/generator.ts +72 -191
  191. package/src/codegen/graphql-client.test.ts +12 -42
  192. package/src/codegen/graphql-client.ts +30 -95
  193. package/src/codegen/graphql.ts +22 -94
  194. package/src/codegen/model-diff.ts +67 -0
  195. package/src/codegen/naming.ts +1 -2
  196. package/src/codegen/openapi-binary.test.ts +5 -12
  197. package/src/codegen/openapi-cli.ts +38 -79
  198. package/src/codegen/openapi.ts +79 -136
  199. package/src/codegen/operations.ts +2 -5
  200. package/src/codegen/pagination.ts +4 -11
  201. package/src/codegen/patch-audit.test.ts +160 -0
  202. package/src/codegen/patch-audit.ts +480 -0
  203. package/src/codegen/patches.test.ts +14 -21
  204. package/src/codegen/patches.ts +313 -103
  205. package/src/codegen/prelude.ts +1 -1
  206. package/src/codegen/proto.ts +18 -54
  207. package/src/codegen/protocol-imports.test.ts +39 -0
  208. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  209. package/src/codegen/rewrite-operation-ids.ts +111 -98
  210. package/src/codegen/spec-path.ts +3 -6
  211. package/src/codegen/untagged-unions.test.ts +3 -7
  212. package/src/error-category.ts +5 -17
  213. package/src/errors.ts +16 -31
  214. package/src/graphql.test.ts +6 -8
  215. package/src/graphql.ts +76 -219
  216. package/src/graphql.types.ts +10 -25
  217. package/src/json-patch.test.ts +77 -0
  218. package/src/json-patch.ts +54 -60
  219. package/src/pagination.test.ts +13 -35
  220. package/src/pagination.ts +44 -111
  221. package/src/protocol-http.test.ts +36 -30
  222. package/src/protocol-http.ts +73 -138
  223. package/src/protocol-rest.test.ts +703 -0
  224. package/src/protocol-rest.ts +24 -62
  225. package/src/response-validation.test.ts +12 -18
  226. package/src/response-validation.ts +3 -12
  227. package/src/retry-after.test.ts +267 -0
  228. package/src/retry-after.ts +4 -10
  229. package/src/retry.test.ts +566 -0
  230. package/src/retry.ts +6 -21
  231. package/src/sdks.test.ts +87 -0
  232. package/src/testing.ts +4 -10
  233. package/src/trait.ts +21 -67
  234. package/src/xml.test.ts +15 -33
  235. package/src/xml.ts +9 -25
@@ -1,7 +1,7 @@
1
- import { afterEach, describe, expect, test } from "bun:test";
2
1
  import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
2
  import { tmpdir } from "node:os";
4
3
  import { join } from "node:path";
4
+ import { afterEach, describe, expect, test } from "vitest";
5
5
  import {
6
6
  FINALIZED_KEY,
7
7
  SKIP_PATCHES_ENV,
@@ -36,16 +36,10 @@ const model = () => ({
36
36
  const scaffold = (patches?: Record<string, unknown>) => {
37
37
  const root = mkdtempSync(join(tmpdir(), "finalize-"));
38
38
  mkdirSync(join(root, ".generated-specs"));
39
- writeFileSync(
40
- join(root, ".generated-specs", "svc.json"),
41
- JSON.stringify(model()),
42
- );
39
+ writeFileSync(join(root, ".generated-specs", "svc.json"), JSON.stringify(model()));
43
40
  if (patches) {
44
41
  mkdirSync(join(root, "patches", "svc"), { recursive: true });
45
- writeFileSync(
46
- join(root, "patches", "svc", "a.json"),
47
- JSON.stringify(patches),
48
- );
42
+ writeFileSync(join(root, "patches", "svc", "a.json"), JSON.stringify(patches));
49
43
  }
50
44
  return root;
51
45
  };
@@ -71,16 +65,12 @@ describe("finalizeConvert", () => {
71
65
  test("refuses a second pass", async () => {
72
66
  const root = scaffold();
73
67
  await finalizeConvert({ root });
74
- await expect(finalizeConvert({ root })).rejects.toThrow(
75
- /already finalized/,
76
- );
68
+ await expect(finalizeConvert({ root })).rejects.toThrow(/already finalized/);
77
69
  });
78
70
 
79
71
  test("applies Smithy patches and repairs the service list after a move", async () => {
80
72
  const root = scaffold({
81
- patches: [
82
- { op: "move", from: "/shapes/ns#AppsGet", path: "/shapes/ns#FetchApp" },
83
- ],
73
+ patches: [{ op: "move", from: "/shapes/ns#AppsGet", path: "/shapes/ns#FetchApp" }],
84
74
  });
85
75
  await finalizeConvert({ root });
86
76
  const m = read(root);
@@ -91,6 +81,13 @@ describe("finalizeConvert", () => {
91
81
  ]);
92
82
  });
93
83
 
84
+ test("rejects a patch that edits the spec", async () => {
85
+ const root = scaffold({
86
+ patches: [{ op: "add", path: "/paths/~1apps/get/responses/404", value: {} }],
87
+ });
88
+ await expect(finalizeConvert({ root })).rejects.toThrow(/target the Smithy model/);
89
+ });
90
+
94
91
  test("fails on a stale patch pointer by default", async () => {
95
92
  const root = scaffold({
96
93
  patches: [{ op: "remove", path: "/shapes/ns#Missing" }],
@@ -172,13 +169,9 @@ describe(SKIP_PATCHES_ENV, () => {
172
169
  test("a basename or a path suffix drops that file", async () => {
173
170
  const dir = patchDir();
174
171
  process.env[SKIP_PATCHES_ENV] = "a.json";
175
- expect(
176
- (await listRfc6902PatchFiles(dir)).map((f) => f.split("/").pop()),
177
- ).toEqual(["b.json"]);
172
+ expect((await listRfc6902PatchFiles(dir)).map((f) => f.split("/").pop())).toEqual(["b.json"]);
178
173
  process.env[SKIP_PATCHES_ENV] = "svc/b.json";
179
- expect(
180
- (await listRfc6902PatchFiles(dir)).map((f) => f.split("/").pop()),
181
- ).toEqual(["a.json"]);
174
+ expect((await listRfc6902PatchFiles(dir)).map((f) => f.split("/").pop())).toEqual(["a.json"]);
182
175
  process.env[SKIP_PATCHES_ENV] = "other/b.json";
183
176
  expect((await listRfc6902PatchFiles(dir)).length).toBe(2);
184
177
  });
@@ -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 {
@@ -100,14 +103,9 @@ const skipList = (): SkipList | undefined => {
100
103
  };
101
104
 
102
105
  const skipsFile = (list: SkipList | undefined, file: string): boolean =>
103
- list !== undefined &&
104
- (list.all || list.files.some((entry) => skipMatches(file, entry)));
105
-
106
- const skipsOp = (
107
- list: SkipList | undefined,
108
- file: string,
109
- index: number,
110
- ): 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 => {
111
109
  if (list === undefined) return false;
112
110
  for (const [entry, indices] of list.ops) {
113
111
  if (indices.has(index) && skipMatches(file, entry)) return true;
@@ -127,8 +125,8 @@ export const listRfc6902PatchFiles = async (dir: string): Promise<string[]> => {
127
125
  .filter((f) => f.endsWith(".json"))
128
126
  .sort(
129
127
  (a, b) =>
130
- Number(a.endsWith(".manual.json")) -
131
- Number(b.endsWith(".manual.json")) || a.localeCompare(b),
128
+ Number(a.endsWith(".manual.json")) - Number(b.endsWith(".manual.json")) ||
129
+ a.localeCompare(b),
132
130
  )
133
131
  .map((f) => path.join(dir, f))
134
132
  .filter((f) => !skipsFile(skip, f));
@@ -187,23 +185,16 @@ export const applyRfc6902Files = async (
187
185
  * longer exists and append operation shapes the list is missing, keeping
188
186
  * the existing order. Returns the number of services whose list changed.
189
187
  */
190
- export const syncServiceOperations = (model: {
191
- shapes?: Record<string, any>;
192
- }): number => {
188
+ export const syncServiceOperations = (model: { shapes?: Record<string, any> }): number => {
193
189
  const shapes = model.shapes ?? {};
194
- const opIds = Object.keys(shapes).filter(
195
- (id) => shapes[id]?.type === "operation",
196
- );
190
+ const opIds = Object.keys(shapes).filter((id) => shapes[id]?.type === "operation");
197
191
  let changed = 0;
198
192
  for (const def of Object.values(shapes)) {
199
193
  if (def?.type !== "service") continue;
200
194
  const current: Array<{ target: string }> = def.operations ?? [];
201
195
  const kept = current.filter((o) => shapes[o.target]?.type === "operation");
202
196
  const listed = new Set(kept.map((o) => o.target));
203
- const after = [
204
- ...kept,
205
- ...opIds.filter((id) => !listed.has(id)).map((target) => ({ target })),
206
- ];
197
+ const after = [...kept, ...opIds.filter((id) => !listed.has(id)).map((target) => ({ target }))];
207
198
  if (JSON.stringify(current) !== JSON.stringify(after)) {
208
199
  def.operations = after;
209
200
  changed++;
@@ -218,9 +209,7 @@ export const syncServiceOperations = (model: {
218
209
  * A convert that produces any is broken — generate would emit references
219
210
  * to types that do not exist.
220
211
  */
221
- export const danglingTargets = (model: {
222
- shapes?: Record<string, any>;
223
- }): string[] => {
212
+ export const danglingTargets = (model: { shapes?: Record<string, any> }): string[] => {
224
213
  const shapes = model.shapes ?? {};
225
214
  const ids = new Set(Object.keys(shapes));
226
215
  const out: string[] = [];
@@ -230,9 +219,7 @@ export const danglingTargets = (model: {
230
219
  return;
231
220
  }
232
221
  if (node === null || typeof node !== "object") return;
233
- for (const [key, value] of Object.entries(
234
- node as Record<string, unknown>,
235
- )) {
222
+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
236
223
  if (key === "target" && typeof value === "string") {
237
224
  if (!value.startsWith("smithy.") && !ids.has(value)) {
238
225
  out.push(`${owner} → ${value}`);
@@ -246,6 +233,159 @@ export const danglingTargets = (model: {
246
233
  return out;
247
234
  };
248
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
+
249
389
  /**
250
390
  * Last step of every convert: Smithy RFC-6902 patches, then verbNoun
251
391
  * operation names, then an optional model transform, then a reference
@@ -256,24 +396,17 @@ export const danglingTargets = (model: {
256
396
  * ops that are not idempotent, and a `transform` may not be either, so
257
397
  * running this over a model that already went through it is an error —
258
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`).
259
402
  */
260
- export const finalizeConvert = async (o: {
261
- readonly root: string;
262
- readonly outDir?: string;
263
- readonly patchesDir?: string | false;
264
- readonly exclude?: (file: string) => boolean;
265
- readonly include?: (resource: string) => boolean;
266
- readonly transform?: (model: any, resource: string) => string | void;
267
- readonly operationNaming?: "as-is" | "verbNoun";
268
- readonly onStalePatch?: OnStalePatch;
269
- }): Promise<void> => {
403
+ export const finalizeConvert = async (o: FinalizeOptions): Promise<void> => {
404
+ const specsRoot = path.resolve(o.root, ".generated-specs");
270
405
  const specsDir = path.resolve(o.root, o.outDir ?? ".generated-specs");
271
406
  if (!(await exists(specsDir))) return;
272
407
  const patchesDir =
273
- o.patchesDir === false
274
- ? undefined
275
- : path.resolve(o.root, o.patchesDir ?? "patches");
276
- const naming = o.operationNaming ?? "verbNoun";
408
+ o.patchesDir === false ? undefined : path.resolve(o.root, o.patchesDir ?? "patches");
409
+ const audit = patchesDir ? await readAuditRequest() : undefined;
277
410
 
278
411
  const walk = async (dir: string): Promise<string[]> => {
279
412
  const out: string[] = [];
@@ -281,10 +414,7 @@ export const finalizeConvert = async (o: {
281
414
  const p = path.join(dir, ent.name);
282
415
  if (ent.isDirectory()) {
283
416
  out.push(...(await walk(p)));
284
- } else if (
285
- ent.name.endsWith(".json") &&
286
- !(o.exclude?.(ent.name) ?? false)
287
- ) {
417
+ } else if (ent.name.endsWith(".json") && !(o.exclude?.(ent.name) ?? false)) {
288
418
  out.push(p);
289
419
  }
290
420
  }
@@ -296,66 +426,34 @@ export const finalizeConvert = async (o: {
296
426
  for (const modelPath of files) {
297
427
  const resource = path.basename(modelPath, ".json");
298
428
  if (o.include && !o.include(resource)) continue;
299
- const model = JSON.parse(await fs.readFile(modelPath, "utf8"));
429
+ const text = await fs.readFile(modelPath, "utf8");
430
+ const model = JSON.parse(text);
300
431
  if (model.metadata?.[FINALIZED_KEY]) {
301
432
  throw new Error(
302
433
  `${path.relative(o.root, modelPath)} was already finalized — finalizeConvert is not idempotent; re-run this package's convert from the spec instead`,
303
434
  );
304
435
  }
305
- if (patchesDir) {
306
- const patchFiles = await listRfc6902PatchFiles(
307
- path.join(patchesDir, resource),
308
- );
309
- const applied = await applyRfc6902Files(model, patchFiles, {
310
- onStalePatch: o.onStalePatch,
311
- include: (op) => isSmithyPatchPath(op.path),
312
- label: (f) => `${resource}/${path.basename(f)}`,
313
- });
314
- if (applied.errors.length) {
315
- for (const err of applied.errors) console.error(`❌ bad patch: ${err}`);
316
- throw new Error(
317
- `${applied.errors.length} patch operation(s) failed for ${resource} — fix the pointers or delete the patch`,
318
- );
319
- }
320
- if (applied.applied > 0) {
321
- console.log(
322
- ` patched ${resource}: ${applied.files} file(s), ${applied.applied} op(s)` +
323
- (applied.stale ? `, ${applied.stale} stale` : ""),
324
- );
325
- }
326
- }
327
-
328
- if (naming === "verbNoun") {
329
- const { renamed, collisions } = verbNounSmithyModel(model);
330
- if (renamed > 0) {
331
- console.log(` verbNoun ${resource}: renamed ${renamed} operation(s)`);
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`);
332
445
  }
333
- for (const c of collisions) {
334
- console.warn(
335
- ` ⚠️ verbNoun collision ${resource}: ${c} (kept original)`,
336
- );
337
- }
338
- }
339
-
340
- const note = o.transform?.(model, resource);
341
- if (note) console.log(` ${note}`);
342
-
343
- syncServiceOperations(model);
344
-
345
- const dangling = danglingTargets(model);
346
- if (dangling.length) {
347
- broken.push(`${resource}: ${dangling.length} dangling target(s)`);
348
- for (const d of dangling.slice(0, 5)) console.error(` ❌ ${d}`);
349
- if (dangling.length > 5) {
350
- 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`);
351
448
  }
449
+ broken.push(run.error.split(", e.g.")[0]!);
352
450
  // Leave the unfinalized model on disk for inspection; never stamp
353
451
  // a model that generate cannot compile.
354
452
  continue;
355
453
  }
356
-
357
- model.metadata = { ...model.metadata, [FINALIZED_KEY]: true };
358
- 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 });
359
457
  }
360
458
  if (broken.length) {
361
459
  throw new Error(
@@ -364,6 +462,118 @@ export const finalizeConvert = async (o: {
364
462
  }
365
463
  };
366
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
+
367
577
  /**
368
578
  * Metadata marker stamped by {@link finalizeConvert}. Guards against a
369
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> = {