contractdiff 0.0.0-stage → 0.4.2

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +228 -2
  3. package/dist/bin.js +4 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.js +24 -0
  6. package/dist/command-diff.js +310 -0
  7. package/dist/command-explain-cap.js +36 -0
  8. package/dist/command-explain-inline.js +17 -0
  9. package/dist/command-explain-name.js +31 -0
  10. package/dist/command-explain-operation.js +85 -0
  11. package/dist/command-explain-text.js +21 -0
  12. package/dist/command-explain.js +54 -0
  13. package/dist/command-lint.js +280 -0
  14. package/dist/command-migrate.js +70 -0
  15. package/dist/command-plugin.js +32 -0
  16. package/dist/command-props.js +116 -0
  17. package/dist/commands.js +7 -0
  18. package/dist/core/index.d.ts +2 -0
  19. package/dist/core/index.js +2 -0
  20. package/dist/core/model.d.ts +46 -0
  21. package/dist/core/model.js +1 -0
  22. package/dist/core/resolve.d.ts +22 -0
  23. package/dist/core/resolve.js +71 -0
  24. package/dist/diff-classify.js +30 -0
  25. package/dist/diff-contract.js +176 -0
  26. package/dist/diff-decisions.js +446 -0
  27. package/dist/diff-normalise.js +143 -0
  28. package/dist/diff-rules.js +109 -0
  29. package/dist/diff-schema.js +335 -0
  30. package/dist/diff-security.js +33 -0
  31. package/dist/diff-transitive.js +26 -0
  32. package/dist/diff-usage.js +59 -0
  33. package/dist/extract-normalise.js +85 -0
  34. package/dist/extract-roundtrip.js +28 -0
  35. package/dist/extract-standard.js +79 -0
  36. package/dist/gen-ts-ast.d.ts +135 -0
  37. package/dist/gen-ts-ast.js +52 -0
  38. package/dist/gen-ts-bundle.js +233 -0
  39. package/dist/gen-ts-comment.js +48 -0
  40. package/dist/gen-ts-context.d.ts +83 -0
  41. package/dist/gen-ts-context.js +45 -0
  42. package/dist/gen-ts-dict.d.ts +14 -0
  43. package/dist/gen-ts-dict.js +14 -0
  44. package/dist/gen-ts-discriminators.d.ts +7 -0
  45. package/dist/gen-ts-discriminators.js +117 -0
  46. package/dist/gen-ts-document.d.ts +12 -0
  47. package/dist/gen-ts-document.js +82 -0
  48. package/dist/gen-ts-enums.js +139 -0
  49. package/dist/gen-ts-helpers.js +30 -0
  50. package/dist/gen-ts-index.d.ts +49 -0
  51. package/dist/gen-ts-index.js +110 -0
  52. package/dist/gen-ts-operations.js +277 -0
  53. package/dist/gen-ts-print.js +113 -0
  54. package/dist/gen-ts-ref.d.ts +30 -0
  55. package/dist/gen-ts-ref.js +75 -0
  56. package/dist/gen-ts-schema.js +283 -0
  57. package/dist/gen-ts-text.d.ts +24 -0
  58. package/dist/gen-ts-text.js +98 -0
  59. package/dist/host.d.ts +145 -0
  60. package/dist/host.js +273 -0
  61. package/dist/index.d.ts +6 -0
  62. package/dist/index.js +5 -0
  63. package/dist/input-asyncapi.js +167 -0
  64. package/dist/input-buf.js +58 -0
  65. package/dist/input-jsonschema.js +165 -0
  66. package/dist/input-mcp.js +111 -0
  67. package/dist/input-overlay-jsonpath.js +265 -0
  68. package/dist/input-overlay.js +138 -0
  69. package/dist/input-protobuf.js +212 -0
  70. package/dist/input-swagger2.js +331 -0
  71. package/dist/inputs.js +8 -0
  72. package/dist/lint-code-read.js +129 -0
  73. package/dist/lint-code.d.ts +56 -0
  74. package/dist/lint-code.js +64 -0
  75. package/dist/lint-engine.d.ts +93 -0
  76. package/dist/lint-engine.js +87 -0
  77. package/dist/lint-functions.js +95 -0
  78. package/dist/lint-history.js +133 -0
  79. package/dist/lint-jsonpath.js +92 -0
  80. package/dist/lint-names.d.ts +11 -0
  81. package/dist/lint-names.js +2 -0
  82. package/dist/lint-redocly.js +141 -0
  83. package/dist/lint-rules.js +189 -0
  84. package/dist/lint-select.d.ts +33 -0
  85. package/dist/lint-select.js +129 -0
  86. package/dist/lint-since.js +20 -0
  87. package/dist/lint-spectral.js +167 -0
  88. package/dist/lint-stats.js +58 -0
  89. package/dist/migrate-hey-api.js +144 -0
  90. package/dist/migrate-literal.js +139 -0
  91. package/dist/migrate-openapi-fetch.js +62 -0
  92. package/dist/migrate-openapi-typescript.js +159 -0
  93. package/dist/migrate-orval.js +119 -0
  94. package/dist/migrate-shared.js +31 -0
  95. package/dist/openapi-typescript.d.ts +9 -0
  96. package/dist/openapi-typescript.js +36 -0
  97. package/dist/openapi.d.ts +20 -0
  98. package/dist/openapi.js +94 -0
  99. package/dist/plugin-express.js +66 -0
  100. package/dist/plugin-extract-hono.js +1 -0
  101. package/dist/plugin-extract-nest.js +1 -0
  102. package/dist/plugin-extract-openapi.js +246 -0
  103. package/dist/plugin-extract-standard-schema.js +42 -0
  104. package/dist/plugin-extract-trpc.js +1 -0
  105. package/dist/plugin-extract-ts-rest.js +77 -0
  106. package/dist/plugin-fastify.js +68 -0
  107. package/dist/plugin-fetch-client.js +172 -0
  108. package/dist/plugin-fetch-routes.js +110 -0
  109. package/dist/plugin-fetch-sample.js +155 -0
  110. package/dist/plugin-fetch-text.js +5 -0
  111. package/dist/plugin-fetch.js +19 -0
  112. package/dist/plugin-hono.js +42 -0
  113. package/dist/plugin-json-schema-build.js +289 -0
  114. package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
  115. package/dist/plugin-json-schema-dialect-gemini.js +29 -0
  116. package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
  117. package/dist/plugin-json-schema-dialect-mcp.js +13 -0
  118. package/dist/plugin-json-schema-dialect-openai.js +37 -0
  119. package/dist/plugin-json-schema-dialect.js +180 -0
  120. package/dist/plugin-json-schema.js +125 -0
  121. package/dist/plugin-markdown.js +114 -0
  122. package/dist/plugin-mcp-code.js +28 -0
  123. package/dist/plugin-mcp-tools.js +152 -0
  124. package/dist/plugin-mcp.js +107 -0
  125. package/dist/plugin-msw-files.js +50 -0
  126. package/dist/plugin-msw-sample.js +45 -0
  127. package/dist/plugin-msw-synth.js +116 -0
  128. package/dist/plugin-msw.js +30 -0
  129. package/dist/plugin-nest-code.js +68 -0
  130. package/dist/plugin-nest-contract.js +23 -0
  131. package/dist/plugin-nest.js +44 -0
  132. package/dist/plugin-server-code.js +61 -0
  133. package/dist/plugin-server-contract.js +48 -0
  134. package/dist/plugin-server-example.js +62 -0
  135. package/dist/plugin-server-router.js +77 -0
  136. package/dist/plugin-server-routes.js +155 -0
  137. package/dist/plugin-server-runtime.js +3 -0
  138. package/dist/plugin-server-sample.js +40 -0
  139. package/dist/plugin-swr-sample.js +21 -0
  140. package/dist/plugin-swr.js +40 -0
  141. package/dist/plugin-tanstack-query-sample.js +21 -0
  142. package/dist/plugin-tanstack-query.js +59 -0
  143. package/dist/plugin-types.js +80 -0
  144. package/dist/plugin-validator-code.js +41 -0
  145. package/dist/plugin-validator-names.js +27 -0
  146. package/dist/plugin-validator.js +103 -0
  147. package/dist/plugins.js +21 -0
  148. package/dist/props-emit.js +194 -0
  149. package/dist/props-generate.js +409 -0
  150. package/dist/props-judge.js +61 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +176 -0
  154. package/dist/props-shrink.js +75 -0
  155. package/dist/run-apply.js +25 -0
  156. package/dist/run-command.js +31 -0
  157. package/dist/run-commit.d.ts +51 -0
  158. package/dist/run-commit.js +48 -0
  159. package/dist/run-config.d.ts +193 -0
  160. package/dist/run-config.js +256 -0
  161. package/dist/run-diff.js +24 -0
  162. package/dist/run-extract.d.ts +13 -0
  163. package/dist/run-extract.js +21 -0
  164. package/dist/run-gen.d.ts +15 -0
  165. package/dist/run-gen.js +43 -0
  166. package/dist/run-header.js +37 -0
  167. package/dist/run-input.js +31 -0
  168. package/dist/run-load.js +32 -0
  169. package/dist/run-map.d.ts +41 -0
  170. package/dist/run-map.js +52 -0
  171. package/dist/run-plan.d.ts +31 -0
  172. package/dist/run-plan.js +35 -0
  173. package/dist/scaffold-seed.js +43 -0
  174. package/dist/scaffold-write.js +17 -0
  175. package/dist/scaffold.js +196 -0
  176. package/dist/testing-lint.js +43 -0
  177. package/dist/testing-owner.js +17 -0
  178. package/dist/testing-probe.js +25 -0
  179. package/dist/testing-rules.d.ts +65 -0
  180. package/dist/testing-rules.js +115 -0
  181. package/dist/testing.d.ts +32 -0
  182. package/dist/testing.js +79 -0
  183. package/package.json +108 -4
package/dist/host.js ADDED
@@ -0,0 +1,273 @@
1
+ import { builtinAdapters } from './inputs.js';
2
+ import { parse } from './lint-jsonpath.js';
3
+ import { CODE_FUNCTIONS, FUNCTIONS } from './lint-names.js';
4
+ import { SELECTS } from './lint-select.js';
5
+ export const CONTRACT = 1;
6
+ export class PluginError extends Error {
7
+ code;
8
+ fix;
9
+ constructor(code, message, fix) {
10
+ super(`${message}. fix: ${fix}`);
11
+ this.name = 'PluginError';
12
+ this.code = code;
13
+ this.fix = fix;
14
+ }
15
+ }
16
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
17
+ function refuse(message, fix, code = 'E_PLUGIN_SCHEMA') {
18
+ throw new PluginError(code, message, fix);
19
+ }
20
+ const text = (value) => typeof value === 'string' && value !== '';
21
+ export const resultOf = (value) => {
22
+ if (!isRecord(value) || !('files' in value))
23
+ return { files: value, findings: [] };
24
+ return { files: value.files, findings: Array.isArray(value.findings) ? value.findings : [] };
25
+ };
26
+ export const documentOf = (value) => {
27
+ if (!isRecord(value) || !('document' in value) || !('findings' in value))
28
+ return { document: value, findings: [] };
29
+ return { document: value.document, findings: Array.isArray(value.findings) ? value.findings : [] };
30
+ };
31
+ const inside = (path) => !path.includes('\\') && !path.includes(':') && !path.split('/').some((part) => part === '..' || part === '.' || part === '');
32
+ const symbolsOk = (symbols) => symbols === undefined || (Array.isArray(symbols) && symbols.every((entry) => isRecord(entry) && text(entry.operation) && text(entry.symbol)));
33
+ export const validateFiles = (files, where) => {
34
+ if (!Array.isArray(files))
35
+ refuse(`${where} did not return a list of files`, 'return `{ path, content, owner }[]`');
36
+ const seen = new Set();
37
+ for (const file of files) {
38
+ if (!isRecord(file) || typeof file.path !== 'string' || typeof file.content !== 'string') {
39
+ refuse(`${where} returned a file without a path and content`, 'each file is `{ path, content, owner }`, both strings');
40
+ }
41
+ if (!inside(file.path)) {
42
+ refuse(`${where} returned the path "${file.path}", which leaves the output folder`, 'use a relative path with `/` separators and no `..`');
43
+ }
44
+ if (file.owner !== 'generated' && file.owner !== 'user') {
45
+ refuse(`${where} returned "${file.path}" without an owner`, 'say `owner: "generated"` (rewritten every run) or `owner: "user"` (written once)');
46
+ }
47
+ if (!symbolsOk(file.symbols)) {
48
+ refuse(`${where} returned "${file.path}" with malformed symbols`, 'each symbol is `{ operation, symbol }`, both non-empty strings');
49
+ }
50
+ if (seen.has(file.path))
51
+ refuse(`${where} returned "${file.path}" twice`, 'return each path once');
52
+ seen.add(file.path);
53
+ }
54
+ return files;
55
+ };
56
+ const validateAdapter = (adapter, where) => {
57
+ if (!isRecord(adapter) || !text(adapter.description) || typeof adapter.detect !== 'function' || typeof adapter.read !== 'function') {
58
+ refuse(`${where} is not an adapter`, 'an adapter is `{ description, detect(document), read(document) }`');
59
+ }
60
+ };
61
+ const validateGenerator = (generator, where) => {
62
+ if (!isRecord(generator) || !text(generator.description) || typeof generator.run !== 'function') {
63
+ refuse(`${where} is not a generator`, 'a generator is `{ description, inputs, sample, run(contract, options) }`');
64
+ }
65
+ const { inputs, options, sample } = generator;
66
+ if (!Array.isArray(inputs) || inputs.length === 0 || !inputs.every((input) => text(input))) {
67
+ refuse(`${where} does not say which input formats it accepts`, 'add `inputs: ["openapi"]`');
68
+ }
69
+ if (options !== undefined && !isRecord(options))
70
+ refuse(`${where}: options must be an object`, 'map an option name to its burgee declaration');
71
+ if (!isRecord(sample) || !('document' in sample)) {
72
+ refuse(`${where} has no sample`, 'add `sample: { document, files }`: a small document and exactly the files it produces', 'E_NO_STATIC_PROJECTION');
73
+ }
74
+ if (sample.options !== undefined && !isRecord(sample.options))
75
+ refuse(`${where}: sample.options must be an object`, 'pass the options the sample was generated with');
76
+ validateFiles(sample.files, `${where}: sample`);
77
+ };
78
+ const validateExtractor = (extractor, where) => {
79
+ if (!isRecord(extractor) || !text(extractor.description) || typeof extractor.run !== 'function') {
80
+ refuse(`${where} is not an extractor`, 'an extractor is `{ description, sample, run(options) }`');
81
+ }
82
+ const { sample } = extractor;
83
+ if (!isRecord(sample) || !isRecord(sample.options) || !('document' in sample)) {
84
+ refuse(`${where} has no sample`, 'add `sample: { options, document }`: the options it runs with and the document it returns', 'E_NO_STATIC_PROJECTION');
85
+ }
86
+ };
87
+ const isThen = (then) => isRecord(then) &&
88
+ [...FUNCTIONS, ...CODE_FUNCTIONS].includes(then.function) &&
89
+ (then.field === undefined || text(then.field)) &&
90
+ (then.functionOptions === undefined || isRecord(then.functionOptions));
91
+ const validateCode = (rule, given, thens, where) => {
92
+ const code = thens.some((then) => CODE_FUNCTIONS.includes(then.function));
93
+ if (given.implementation === true && given.select !== 'operation')
94
+ refuse(`${where} reads code but selects ${String(given.select)}`, 'a rule with `given.implementation` selects `operation`: it reads each operation\'s handler');
95
+ if (code && given.implementation !== true)
96
+ refuse(`${where} names a function on code without \`given.implementation\``, `add \`implementation: true\` to \`given\` to judge each operation's handler with ${CODE_FUNCTIONS.join(', ')}`);
97
+ if (given.implementation === true && rule.check !== undefined)
98
+ refuse(`${where} reads code with a \`check\``, 'a rule on code says what must hold with `then`, so the handler is read once, statically');
99
+ };
100
+ const pathsOf = (path, where) => {
101
+ const paths = [path].flat();
102
+ if (paths.length === 0 || !paths.every((each) => text(each)))
103
+ refuse(`${where} selects \`path\` and names none`, "add `given.path`: a JSONPath into the document, e.g. `$.info`");
104
+ for (const each of paths) {
105
+ try {
106
+ parse(each);
107
+ }
108
+ catch (error) {
109
+ refuse(`${where} selects a path outside the subset`, `${error.message}; write it with \`.key\`, \`['key']\`, \`*\`, \`..\` and \`?(@.x == 'y')\``);
110
+ }
111
+ }
112
+ };
113
+ const validateRule = (rule, where) => {
114
+ if (!isRecord(rule) || !text(rule.description) || !text(rule.fix) || !isRecord(rule.given) || !SELECTS.includes(rule.given.select)) {
115
+ refuse(`${where} is not a rule`, `a rule is \`{ description, given: { select }, then or check, fix, sample }\`, \`select\` one of ${SELECTS.join(', ')}`);
116
+ }
117
+ if (rule.given.select === 'path')
118
+ pathsOf(rule.given.path, where);
119
+ const thens = rule.then === undefined ? [] : [rule.then].flat();
120
+ if (!thens.every((then) => isThen(then)) || (rule.check !== undefined && typeof rule.check !== 'function') || (thens.length === 0 && rule.check === undefined)) {
121
+ refuse(`${where} says nothing that must hold`, `give it \`then: { function }\`, \`function\` one of ${FUNCTIONS.join(', ')}, or a \`check(node, context)\` function`);
122
+ }
123
+ validateCode(rule, rule.given, thens, where);
124
+ const { sample } = rule;
125
+ if (!isRecord(sample) || !('document' in sample) || !Array.isArray(sample.findings) || !sample.findings.every((finding) => isRecord(finding) && typeof finding.pointer === 'string' && text(finding.message))) {
126
+ refuse(`${where} has no sample`, 'add `sample: { document, findings: [{ pointer, message }] }`: a small document and exactly what the rule finds on it', 'E_NO_STATIC_PROJECTION');
127
+ }
128
+ };
129
+ const each = (group, plugin, key, validateOne) => {
130
+ if (group === undefined)
131
+ return;
132
+ if (!isRecord(group))
133
+ refuse(`plugin "${plugin}": ${key} must be an object`, `map a name to each of the ${key}`);
134
+ for (const [name, value] of Object.entries(group))
135
+ validateOne(value, `plugin "${plugin}": ${key}.${name}`);
136
+ };
137
+ export function validate(plugin) {
138
+ if (!isRecord(plugin))
139
+ refuse('a plugin is a plain object', 'export an object, not a function or an array');
140
+ const { name, contract } = plugin;
141
+ if (!text(name))
142
+ refuse('a plugin needs a name', 'add `name: "…"`: it is how a refused plugin is reported');
143
+ if (contract !== undefined && (!Number.isInteger(contract) || contract < 1 || contract > CONTRACT)) {
144
+ refuse(`plugin "${name}" declares contract ${String(contract)}; this contractdiff knows ${String(CONTRACT)}`, "upgrade contractdiff, or lower the plugin's `contract`", 'E_PLUGIN_CONTRACT');
145
+ }
146
+ each(plugin.adapters, name, 'adapters', validateAdapter);
147
+ each(plugin.generators, name, 'generators', validateGenerator);
148
+ each(plugin.extractors, name, 'extractors', validateExtractor);
149
+ each(plugin.rules, name, 'rules', validateRule);
150
+ }
151
+ export const createHost = () => {
152
+ const order = [];
153
+ const latest = (pick) => {
154
+ for (const plugin of order.toReversed()) {
155
+ const found = pick(plugin);
156
+ if (found !== undefined)
157
+ return found;
158
+ }
159
+ return undefined;
160
+ };
161
+ const names = (key) => {
162
+ const all = [...new Set(order.flatMap((plugin) => Object.keys(plugin[key] ?? {})))].toSorted();
163
+ return all.length === 0 ? 'none' : all.join(', ');
164
+ };
165
+ const read = (document, accepted) => {
166
+ const adapter = latest((plugin) => Object.entries(plugin.adapters ?? {}).find(([name, candidate]) => (accepted?.includes(name) ?? true) && candidate.detect(document))?.[1]);
167
+ if (adapter === undefined) {
168
+ const wanted = accepted === undefined ? names('adapters') : accepted.join(', ');
169
+ return refuse('no input format recognises this document', `pass one of: ${wanted}; or install the plugin that reads it`, 'E_NO_CONTRIBUTION');
170
+ }
171
+ return adapter.read(document);
172
+ };
173
+ const named = (key, name, kind) => {
174
+ const found = latest((plugin) => {
175
+ const group = plugin[key];
176
+ return group !== undefined && Object.hasOwn(group, name) ? group[name] : undefined;
177
+ });
178
+ if (found === undefined) {
179
+ return refuse(`no ${kind} is named "${name}"`, `use one of: ${names(key)}; or install the plugin that provides it and add it to \`plugins\``, 'E_NO_CONTRIBUTION');
180
+ }
181
+ return found;
182
+ };
183
+ const generator = (target) => named('generators', target, 'generator');
184
+ const extractor = (name) => named('extractors', name, 'extractor');
185
+ const run = async (target, document, options = {}) => {
186
+ const chosen = generator(target);
187
+ const contract = read(document, chosen.inputs);
188
+ const result = resultOf(await chosen.run(contract, options));
189
+ return { files: validateFiles(result.files, `generator "${target}"`), findings: [...(contract.findings ?? []), ...result.findings] };
190
+ };
191
+ return {
192
+ register: (plugin) => {
193
+ validate(plugin);
194
+ order.push(plugin);
195
+ },
196
+ plugins: () => order,
197
+ reset: () => {
198
+ order.length = 0;
199
+ },
200
+ read: (document) => read(document),
201
+ generator,
202
+ extractor,
203
+ rules: () => Object.fromEntries(order.flatMap((plugin) => Object.entries(plugin.rules ?? {}))),
204
+ generate: async (target, document, options) => (await run(target, document, options)).files,
205
+ run,
206
+ };
207
+ };
208
+ const FIXES = {
209
+ 'not deterministic': 'remove whatever changes between runs: time, random values, iteration order',
210
+ unexpected: 'add the file to `sample.files`, or stop generating it',
211
+ different: 'update `sample.files` to what `run` returns, or fix `run`',
212
+ missing: 'generate the file, or remove it from `sample.files`',
213
+ };
214
+ const problemWith = (content, again, declared) => {
215
+ if (again !== content)
216
+ return 'not deterministic';
217
+ if (declared === undefined)
218
+ return 'unexpected';
219
+ return declared === content ? undefined : 'different';
220
+ };
221
+ const canonical = (value) => JSON.stringify(value, (_key, inner) => isRecord(inner) ? Object.fromEntries(Object.entries(inner).toSorted(([a], [b]) => a.localeCompare(b))) : inner);
222
+ const compare = (generator, first, second, declared) => {
223
+ const findings = [];
224
+ for (const [path, content] of first) {
225
+ const problem = problemWith(content, second.get(path), declared.get(path));
226
+ if (problem !== undefined)
227
+ findings.push({ generator, path, problem, fix: FIXES[problem] });
228
+ }
229
+ for (const path of second.keys()) {
230
+ if (!first.has(path))
231
+ findings.push({ generator, path, problem: 'not deterministic', fix: 'return the same files on every run' });
232
+ }
233
+ for (const path of declared.keys()) {
234
+ if (!first.has(path))
235
+ findings.push({ generator, path, problem: 'missing', fix: FIXES.missing });
236
+ }
237
+ return findings;
238
+ };
239
+ const render = (files) => new Map(files.map((file) => [file.path, `${file.owner}\n${file.content}`]));
240
+ const checkExtractor = async ([name, extractor]) => {
241
+ const first = canonical(documentOf(await extractor.run(extractor.sample.options)).document);
242
+ const second = canonical(documentOf(await extractor.run(extractor.sample.options)).document);
243
+ if (second !== first)
244
+ return [{ generator: name, path: 'sample.document', problem: 'not deterministic', fix: FIXES['not deterministic'] }];
245
+ if (first === canonical(extractor.sample.document))
246
+ return [];
247
+ return [{ generator: name, path: 'sample.document', problem: 'different', fix: 'update `sample.document` to what `run(sample.options)` returns, or fix `run`' }];
248
+ };
249
+ export const checkPlugin = async (plugin) => {
250
+ const host = createHost();
251
+ host.register({ name: 'contractdiff', adapters: builtinAdapters });
252
+ host.register(plugin);
253
+ const [, registered] = host.plugins();
254
+ const checkOne = async ([name, generator]) => {
255
+ const contract = host.read(generator.sample.document);
256
+ const run = async () => render(validateFiles(resultOf(await generator.run(contract, generator.sample.options ?? {})).files, `generator "${name}"`));
257
+ const first = await run();
258
+ return compare(name, first, await run(), render(generator.sample.files));
259
+ };
260
+ const findings = await Promise.all([
261
+ ...Object.entries(registered.generators ?? {}).map(async (entry) => checkOne(entry)),
262
+ ...Object.entries(registered.extractors ?? {}).map(async (entry) => checkExtractor(entry)),
263
+ ]);
264
+ return findings.flat();
265
+ };
266
+ const program = createHost();
267
+ export const register = (plugin) => {
268
+ program.register(plugin);
269
+ };
270
+ export const registered = () => program.plugins();
271
+ export const reset = () => {
272
+ program.reset();
273
+ };
@@ -0,0 +1,6 @@
1
+ export { program, VERSION } from './cli.js';
2
+ export { type Config, configSchema, type Target } from './run-config.js';
3
+ export { type FileReport, type Report } from './run-commit.js';
4
+ export { extract, type ExtractOptions } from './run-extract.js';
5
+ export { gen, type GenOptions } from './run-gen.js';
6
+ export { type ContractMap, MAP_FILE, type MapEntry } from './run-map.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { program, VERSION } from './cli.js';
2
+ export { configSchema } from './run-config.js';
3
+ export { extract } from './run-extract.js';
4
+ export { gen } from './run-gen.js';
5
+ export { MAP_FILE } from './run-map.js';
@@ -0,0 +1,167 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ const dict = (value) => (isDict(value) ? value : {});
4
+ const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
5
+ const lastKey = (ref) => ref.slice(ref.lastIndexOf('/') + 1).replaceAll('~1', '/').replaceAll('~0', '~');
6
+ const JSON_SCHEMA_FORMAT = /^application\/(?:vnd\.aai\.asyncapi(?:\+json|\+yaml)?|schema\+json|schema\+yaml)(?:;|$)/;
7
+ export class AsyncApiError extends Error {
8
+ constructor(reason, fix) {
9
+ super(`not an AsyncAPI document: ${reason}. fix: ${fix}`);
10
+ this.name = 'AsyncApiError';
11
+ }
12
+ }
13
+ export const detect = (document) => isDict(document) && typeof document.asyncapi === 'string' && /^[23]\./.test(document.asyncapi);
14
+ const membersOf = (map, at) => Object.entries(dict(map)).map(([key, value], index) => ({ value, at: `${at}/${token(key)}`, key, index }));
15
+ const itemsOf = (list, at) => list.map((value, index) => ({ value, at: `${at}/${String(index)}`, key: undefined, index }));
16
+ const opposite = (direction) => (direction === 'publish' ? 'subscribe' : 'publish');
17
+ const schemaOf = (holder, format) => isDict(holder) && 'schemaFormat' in holder && 'schema' in holder ? { schema: holder.schema, format: holder.schemaFormat } : { schema: holder, format };
18
+ const anyIfMissing = (schema) => (schema === undefined ? true : schema);
19
+ const createReader = (root, report) => {
20
+ const follow = (value, at) => {
21
+ let node = value;
22
+ let where = at;
23
+ let ref;
24
+ const seen = new Set();
25
+ while (isDict(node) && typeof node.$ref === 'string' && !seen.has(node.$ref)) {
26
+ const next = node.$ref;
27
+ seen.add(next);
28
+ ref ??= next;
29
+ if (!next.startsWith('#')) {
30
+ report('ref-external', `${where}/$ref`, `\`${next}\` is in another file and is not read`, 'bundle the document into one file first');
31
+ return undefined;
32
+ }
33
+ try {
34
+ node = pointerGet(root, next);
35
+ }
36
+ catch (error) {
37
+ report('ref-broken', `${where}/$ref`, error.message.replace(/\. fix: .*/, ''), 'point the reference at a value the document defines');
38
+ return undefined;
39
+ }
40
+ where = next;
41
+ }
42
+ return { node: dict(node), where, ref };
43
+ };
44
+ const notApplied = (node, where) => {
45
+ if (node.traits !== undefined) {
46
+ report('traits-not-applied', `${where}/traits`, 'traits are not merged into what they apply to, so what they add is not read', 'write what the traits add on the operation or message itself');
47
+ }
48
+ };
49
+ const partsOf = (node, where, name, direction) => {
50
+ const payloads = [];
51
+ for (const [part, suffix] of [
52
+ ['payload', ''],
53
+ ['headers', ':headers'],
54
+ ]) {
55
+ if (part === 'headers' && node.headers === undefined)
56
+ continue;
57
+ const { schema, format } = schemaOf(node[part], node.schemaFormat);
58
+ if (typeof format === 'string' && !JSON_SCHEMA_FORMAT.test(format)) {
59
+ report('schema-format-unsupported', `${where}/${part}`, `the ${part} is written in \`${format}\`, not JSON Schema, so it is not read`, "convert the schema to JSON Schema, or generate from the format's own tools");
60
+ continue;
61
+ }
62
+ payloads.push({ name: `${name}${suffix}`, direction, schema: anyIfMissing(schema), required: true });
63
+ }
64
+ return payloads;
65
+ };
66
+ const messagePayloads = (entry, direction, prefix) => {
67
+ const followed = follow(entry.value, entry.at);
68
+ if (followed === undefined)
69
+ return [];
70
+ const { node, where, ref } = followed;
71
+ if (Array.isArray(node.oneOf))
72
+ return itemsOf(node.oneOf, `${where}/oneOf`).flatMap((item) => messagePayloads(item, direction, prefix));
73
+ notApplied(node, where);
74
+ if (node.bindings !== undefined) {
75
+ report('bindings-not-read', `${where}/bindings`, 'message bindings (a Kafka key schema, say) are not read', 'describe what the binding carries in the message headers or payload, if a generator needs it');
76
+ }
77
+ const named = [entry.key, ref === undefined ? undefined : lastKey(ref), node.messageId, node.name].find((name) => typeof name === 'string');
78
+ return partsOf(node, where, `${prefix}:${named ?? String(entry.index)}`, direction);
79
+ };
80
+ return { follow, notApplied, messagePayloads };
81
+ };
82
+ const readV2 = (root, reader, report) => {
83
+ report('asyncapi2-directions', '#/asyncapi', "AsyncAPI 2.x names operations from the client's side: `publish` is what this application receives and `subscribe` what it sends. They are read from the application's side, as 3.0's `send` and `receive` are, so a 2.x document and its 3.0 migration read the same", 'nothing to do; the operation ids keep their 2.x verbs, and each payload carries the direction it travels from this application');
84
+ const operations = [];
85
+ for (const channel of membersOf(root.channels, '#/channels')) {
86
+ const item = reader.follow(channel.value, channel.at);
87
+ if (item === undefined)
88
+ continue;
89
+ for (const verb of ['publish', 'subscribe']) {
90
+ const declared = item.node[verb];
91
+ if (!isDict(declared))
92
+ continue;
93
+ const source = `${item.where}/${verb}`;
94
+ const owned = opposite(verb);
95
+ reader.notApplied(declared, source);
96
+ const parameters = membersOf(item.node.parameters, `${item.where}/parameters`).flatMap((entry) => {
97
+ const parameter = reader.follow(entry.value, entry.at);
98
+ return parameter === undefined ? [] : [{ name: `param:${entry.key}`, direction: owned, schema: anyIfMissing(parameter.node.schema), required: true }];
99
+ });
100
+ const message = { value: declared.message, at: `${source}/message`, key: undefined, index: 0 };
101
+ const payloads = declared.message === undefined ? [] : reader.messagePayloads(message, owned, 'message');
102
+ const id = typeof declared.operationId === 'string' ? declared.operationId : `${verb} ${channel.key}`;
103
+ operations.push({ id, source, payloads: [...parameters, ...payloads] });
104
+ }
105
+ }
106
+ return operations;
107
+ };
108
+ const ACTIONS = new Map([
109
+ ['send', 'publish'],
110
+ ['receive', 'subscribe'],
111
+ ]);
112
+ const parametersV3 = (channel, direction, reader, report) => membersOf(channel.node.parameters, `${channel.where}/parameters`).flatMap((entry) => {
113
+ const parameter = reader.follow(entry.value, entry.at);
114
+ if (parameter === undefined)
115
+ return [];
116
+ report('parameter-synthesised', parameter.where, `parameter \`${entry.key}\` has no schema; it is read as a string with its \`enum\`, \`default\`, \`description\` and \`examples\``, 'nothing to do: AsyncAPI 3 parameters are strings');
117
+ const keywords = Object.entries(parameter.node).filter(([key]) => ['enum', 'default', 'description', 'examples'].includes(key));
118
+ return [{ name: `param:${entry.key}`, direction, schema: { type: 'string', ...Object.fromEntries(keywords) }, required: true }];
119
+ });
120
+ const channelOf = (holder, where, reader) => reader.follow(holder.channel, `${where}/channel`);
121
+ const messagesOf = (holder, where, channel) => Array.isArray(holder.messages) ? itemsOf(holder.messages, `${where}/messages`) : membersOf(channel?.node.messages, `${channel?.where ?? where}/messages`);
122
+ const readV3 = (root, reader, report) => {
123
+ const operations = [];
124
+ for (const entry of membersOf(root.operations, '#/operations')) {
125
+ const followed = reader.follow(entry.value, entry.at);
126
+ if (followed === undefined)
127
+ continue;
128
+ const { node: declared, where } = followed;
129
+ const direction = ACTIONS.get(declared.action);
130
+ if (direction === undefined) {
131
+ report('action-unknown', `${where}/action`, `operation \`${entry.key}\` has no \`action: send\` or \`action: receive\`, so it is not read`, 'say whether the application sends or receives it');
132
+ continue;
133
+ }
134
+ reader.notApplied(declared, where);
135
+ const channel = channelOf(declared, where, reader);
136
+ const payloads = [
137
+ ...(channel === undefined ? [] : parametersV3(channel, direction, reader, report)),
138
+ ...messagesOf(declared, where, channel).flatMap((message) => reader.messagePayloads(message, direction, 'message')),
139
+ ];
140
+ const reply = reader.follow(declared.reply, `${where}/reply`);
141
+ if (reply !== undefined) {
142
+ const answered = messagesOf(reply.node, reply.where, channelOf(reply.node, reply.where, reader));
143
+ payloads.push(...answered.flatMap((message) => reader.messagePayloads(message, opposite(direction), 'reply')));
144
+ }
145
+ operations.push({ id: entry.key, source: where, payloads });
146
+ }
147
+ return operations;
148
+ };
149
+ export const read = (document) => {
150
+ if (!detect(document)) {
151
+ throw new AsyncApiError('it has no `asyncapi: 2.x` or `asyncapi: 3.x` member', 'pass an AsyncAPI 2.6 or 3.0 document');
152
+ }
153
+ const root = document;
154
+ const findings = new Map();
155
+ const report = (code, pointer, message, fix) => {
156
+ findings.set(`${code} ${pointer}`, { code, pointer, message, fix });
157
+ };
158
+ const reader = createReader(root, report);
159
+ const operations = root.asyncapi.startsWith('2.') ? readV2(root, reader, report) : readV3(root, reader, report);
160
+ return { format: 'asyncapi', document, operations, findings: [...findings.values()] };
161
+ };
162
+ export const adapter = Object.freeze({
163
+ name: 'asyncapi',
164
+ description: 'AsyncAPI 2.x and 3.x documents: channels, operations and messages',
165
+ detect,
166
+ read,
167
+ });
@@ -0,0 +1,58 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { ambientRuntime, NotFoundError, run } from 'bellpull';
4
+ import { UsageError } from './run-config.js';
5
+ const BUF_INSTALL = 'install buf (https://buf.build/docs/installation), or hand over the image `buf build -o image.json` writes';
6
+ export const isBufSource = (path, cwd) => path.endsWith('.proto') || ['buf.yaml', 'buf.work.yaml'].some((file) => existsSync(join(resolve(cwd, path), file)));
7
+ export const bufIn = (runtime = ambientRuntime()) => async (path, cwd) => {
8
+ const result = await run('buf', ['build', path, '-o', '-#format=json'], { cwd, runtime }).catch(async (error) => (error instanceof NotFoundError ? undefined : Promise.reject(error)));
9
+ if (result === undefined)
10
+ throw new UsageError(`cannot build ${path}: buf is not on the PATH. fix: ${BUF_INSTALL}`);
11
+ if (!result.ok)
12
+ throw new UsageError(`buf could not build ${path}: ${result.stderr.trim()}. fix: correct what buf reports, then run again`);
13
+ return result.stdout;
14
+ };
15
+ const AT_REF = /^git:([^:]+):/;
16
+ const passOld = (command) => `fix: \`${command}\` and pass old.json`;
17
+ export const refFix = (spec) => {
18
+ const match = AT_REF.exec(spec);
19
+ const ref = match[1];
20
+ const path = spec.slice(match[0].length);
21
+ if (path.endsWith('.proto'))
22
+ return passOld(`buf build '.git#ref=${ref}' -o old.json`);
23
+ return passOld(/\.[a-z]+$/i.test(path) ? `git show ${ref}:${path} > old.json` : `buf build '.git#ref=${ref},subdir=${path}' -o old.json`);
24
+ };
25
+ export const builtImages = async (specs, cwd, build) => {
26
+ const sources = specs.filter((spec) => spec !== undefined && isBufSource(spec.replace(AT_REF, ''), cwd));
27
+ const atRef = sources.find((spec) => AT_REF.test(spec));
28
+ if (atRef !== undefined)
29
+ throw new UsageError(`cannot build ${atRef}: buf builds a ref itself. ${refFix(atRef)}`);
30
+ const images = await Promise.all(sources.map(async (spec) => [spec, await build(spec, cwd)]));
31
+ return new Map(images);
32
+ };
33
+ export const LEVELS = ['file', 'package', 'wire-json', 'wire'];
34
+ const FOUND = 100;
35
+ const jsonOf = (line) => {
36
+ try {
37
+ return JSON.parse(line);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ };
43
+ const annotationOf = (line) => {
44
+ const parsed = jsonOf(line);
45
+ const { path, start_line: start, type, message } = (typeof parsed === 'object' && parsed !== null ? parsed : {});
46
+ if (typeof type !== 'string' || typeof message !== 'string')
47
+ throw new UsageError(`buf breaking printed what is not an annotation: ${line}. fix: run a buf that has --error-format json, then run again`);
48
+ return { path: typeof path === 'string' ? path : '', line: typeof start === 'number' ? start : 0, type, message };
49
+ };
50
+ export const breakingIn = (runtime = ambientRuntime()) => async (nu, old, level, cwd) => {
51
+ const config = JSON.stringify({ version: 'v2', breaking: { use: [level.replaceAll('-', '_').toUpperCase()] } });
52
+ const result = await run('buf', ['breaking', nu, '--against', old, '--error-format', 'json', '--config', config], { cwd, runtime }).catch(async (error) => (error instanceof NotFoundError ? undefined : Promise.reject(error)));
53
+ if (result === undefined)
54
+ throw new UsageError(`cannot judge ${nu} at --level ${level}: buf is not on the PATH. fix: install buf (https://buf.build/docs/installation), or drop --level`);
55
+ if (!result.ok && result.code !== FOUND)
56
+ throw new UsageError(`buf breaking could not compare ${nu} with ${old}: ${result.stderr.trim()}. fix: correct what buf reports, then run again`);
57
+ return result.stdout.split('\n').filter((line) => line.trim() !== '').map(annotationOf);
58
+ };