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
@@ -0,0 +1,43 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { readInput } from './command-lint.js';
4
+ import { findingsOn } from './lint-engine.js';
5
+ import { select, SELECTS } from './lint-select.js';
6
+ import { UsageError } from './run-config.js';
7
+ const SHAPE = 'fix: pass one finding from `contractdiff lint --json`, shaped { "file", "pointer", "message", "fix" }, or the whole output';
8
+ const isRecord = (value) => typeof value === 'object' && value !== null;
9
+ const findingOf = (text, from) => {
10
+ let value;
11
+ try {
12
+ value = JSON.parse(text);
13
+ }
14
+ catch (error) {
15
+ throw new UsageError(`${from} is not JSON: ${error.message}. ${SHAPE}`);
16
+ }
17
+ const finding = isRecord(value) && Array.isArray(value.findings) ? value.findings[0] : value;
18
+ if (!isRecord(finding) || typeof finding.file !== 'string' || typeof finding.pointer !== 'string' || typeof finding.message !== 'string') {
19
+ throw new UsageError(`${from} holds no finding with a \`file\`, a \`pointer\` and a \`message\`. ${SHAPE}`);
20
+ }
21
+ return finding;
22
+ };
23
+ export const seedOf = (from, cwd) => {
24
+ let text;
25
+ try {
26
+ text = String(readFileSync(resolve(cwd, from)));
27
+ }
28
+ catch {
29
+ throw new UsageError(`there is no finding file ${from}. fix: save one with \`contractdiff lint <spec> --json > ${from}\``);
30
+ }
31
+ const finding = findingOf(text, from);
32
+ const [file, pointer] = [finding.file, finding.pointer];
33
+ const { contract } = readInput(file, cwd);
34
+ const [found] = SELECTS.flatMap((kind) => select(contract, { select: kind }).flatMap((node) => (node.pointer === pointer ? [{ kind, node }] : [])));
35
+ if (found === undefined)
36
+ throw new UsageError(`${file} has no node at ${pointer} a rule can select. fix: lint ${file} again and pass a finding from that run`);
37
+ const { name } = found.node;
38
+ const raw = finding.message;
39
+ const message = name !== undefined && raw.startsWith(`${name}: `) ? raw.slice(name.length + 2) : raw;
40
+ const fix = typeof finding.fix === 'string' ? finding.fix : 'say what to change so the node is no longer this mistake';
41
+ const rule = { description: message, given: { select: found.kind }, check: (node) => (node.pointer === pointer ? [message] : []), fix };
42
+ return { document: contract.document, select: found.kind, pointer, message, fix, findings: findingsOn(rule, contract) };
43
+ };
@@ -0,0 +1,17 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { plan } from './testing-owner.js';
4
+ const missing = () => undefined;
5
+ const current = async (path) => readFile(path, 'utf8').catch(missing);
6
+ export const writeFiles = async (directory, files) => {
7
+ const found = await Promise.all(files.map(async (file) => [file.path, await current(join(directory, file.path))]));
8
+ const planned = plan(files, new Map(found));
9
+ const writes = planned.flatMap((entry, index) => (entry.action === 'write' ? [files[index]] : []));
10
+ await Promise.all(writes.map(async (file) => {
11
+ const target = join(directory, file.path);
12
+ await mkdir(dirname(target), { recursive: true });
13
+ await writeFile(target, file.content);
14
+ }));
15
+ const paths = (action) => planned.filter((entry) => entry.action === action).map((entry) => entry.path);
16
+ return { written: paths('write'), unchanged: paths('unchanged'), kept: paths('skip') };
17
+ };
@@ -0,0 +1,196 @@
1
+ export const KINDS = ['generator', 'extractor', 'adapter', 'rules'];
2
+ const NAME = /^[a-z][\da-z]*(?:-[\da-z]+)*$/u;
3
+ export const checkName = (name) => {
4
+ if (!NAME.test(name)) {
5
+ throw new Error(`"${name}" is not a plugin name. fix: use lowercase letters, digits and single dashes, starting with a letter, e.g. \`my-target\``);
6
+ }
7
+ };
8
+ const openapiSample = (name) => `{
9
+ openapi: '3.1.0',
10
+ info: { title: '${name} sample', version: '1.0.0' },
11
+ paths: { '/pets': { get: { operationId: 'listPets', responses: { '200': { description: 'the pets' } } } } },
12
+ }`;
13
+ const header = (name, kind, what) => `/**
14
+ * The \`${name}\` contractdiff plugin: ${what}.
15
+ *
16
+ * Scaffolded by \`contractdiff plugin new ${name} --kind ${kind}\`. ${kind === 'rules' ? 'Change `then` or `check`, then make `sample.findings`\n * say exactly what the rule finds on' : 'Change `run`, then make `sample`\n * say exactly what `run` returns for'} \`sample.document\`: \`node --test plugin-${name}.test.ts\` runs the
17
+ * conformance suite and names every rule the plugin breaks, with a \`fix:\` line for each.
18
+ */
19
+ `;
20
+ const generator = (name) => `${header(name, 'generator', 'a generator, spec to code')}import { type Contract, type GeneratedFile, type Plugin } from 'contractdiff/testing';
21
+
22
+ /** One file: the operation ids, sorted so two runs give the same bytes. */
23
+ const run = (contract: Contract): GeneratedFile[] => {
24
+ const ids = contract.operations.map((operation) => operation.id).toSorted();
25
+ return [{ path: '${name}.ts', owner: 'generated', content: \`// generated by ${name}: do not edit\\nexport const operations = \${JSON.stringify(ids)} as const;\\n\` }];
26
+ };
27
+
28
+ export const plugin: Plugin = {
29
+ name: '${name}',
30
+ generators: {
31
+ '${name}': {
32
+ description: 'The operation ids of a spec, as a TypeScript constant',
33
+ inputs: ['openapi'],
34
+ sample: {
35
+ document: ${openapiSample(name).replaceAll('\n', '\n ')},
36
+ files: [{ path: '${name}.ts', owner: 'generated', content: '// generated by ${name}: do not edit\\nexport const operations = ["listPets"] as const;\\n' }],
37
+ },
38
+ run,
39
+ },
40
+ },
41
+ };
42
+ `;
43
+ const extractor = (name) => `${header(name, 'extractor', 'an extractor, code to spec')}import { type Plugin } from 'contractdiff/testing';
44
+
45
+ /** The operations named in \`options.operations\`; a real extractor reads them from the user's code instead. */
46
+ const run = (options: Readonly<Record<string, unknown>>): unknown => {
47
+ const named = Array.isArray(options.operations) ? options.operations.filter((id): id is string => typeof id === 'string') : [];
48
+ const paths = Object.fromEntries(named.toSorted().map((id) => [\`/\${id}\`, { get: { operationId: id, responses: { '200': { description: 'ok' } } } }]));
49
+ return { openapi: '3.1.0', info: { title: '${name}', version: '0.0.0' }, paths };
50
+ };
51
+
52
+ export const plugin: Plugin = {
53
+ name: '${name}',
54
+ extractors: {
55
+ '${name}': {
56
+ description: 'An OpenAPI document from the operations it is told about',
57
+ sample: {
58
+ options: { operations: ['listPets'] },
59
+ document: { openapi: '3.1.0', info: { title: '${name}', version: '0.0.0' }, paths: { '/listPets': { get: { operationId: 'listPets', responses: { '200': { description: 'ok' } } } } } },
60
+ },
61
+ run,
62
+ },
63
+ },
64
+ };
65
+ `;
66
+ const adapter = (name) => `${header(name, 'adapter', 'an input format, and a generator that reads it')}import { type Contract, type GeneratedFile, type Plugin } from 'contractdiff/testing';
67
+
68
+ /** A document in this format: \`{ "${name}": 1, "operations": ["listPets"] }\`. */
69
+ const detect = (document: unknown): boolean => typeof document === 'object' && document !== null && (document as Record<string, unknown>)['${name}'] === 1;
70
+
71
+ const read = (document: unknown): Contract => {
72
+ const { operations } = document as { operations?: unknown };
73
+ const ids = Array.isArray(operations) ? operations.filter((id): id is string => typeof id === 'string') : [];
74
+ return { format: '${name}', document, operations: ids.map((id, index) => ({ id, source: \`#/operations/\${String(index)}\`, payloads: [] })) };
75
+ };
76
+
77
+ /** The generator that shows the format reads: the operation ids, sorted. */
78
+ const run = (contract: Contract): GeneratedFile[] => [
79
+ { path: 'operations.txt', owner: 'generated', content: contract.operations.map((operation) => \`\${operation.id}\\n\`).toSorted().join('') },
80
+ ];
81
+
82
+ export const plugin: Plugin = {
83
+ name: '${name}',
84
+ adapters: { '${name}': { description: 'The ${name} format', detect, read } },
85
+ generators: {
86
+ '${name}-operations': {
87
+ description: 'The operation ids of a ${name} document, one per line',
88
+ inputs: ['${name}'],
89
+ sample: { document: { '${name}': 1, operations: ['listPets'] }, files: [{ path: 'operations.txt', owner: 'generated', content: 'listPets\\n' }] },
90
+ run,
91
+ },
92
+ },
93
+ };
94
+
95
+ /** The sample after a spec change, for the conformance suite's regeneration rule: it can only change OpenAPI itself. */
96
+ export const mutate = (document: unknown): unknown => ({ ...(document as object), operations: ['listPets', 'createPet'] });
97
+ `;
98
+ const SAMPLE_DEPTH = 4;
99
+ const literal = (value, depth) => JSON.stringify(value, undefined, 2).replaceAll('\n', `\n${' '.repeat(depth)}`);
100
+ const rule = (name) => `${header(name, 'rules', '`lint` rules')}import { type Plugin } from 'contractdiff/testing';
101
+
102
+ export const plugin: Plugin = {
103
+ name: '${name}',
104
+ rules: {
105
+ '${name}': {
106
+ description: 'Every operation has a summary',
107
+ given: { select: 'operation' },
108
+ then: { field: 'summary', function: 'truthy' },
109
+ fix: 'add a one-line \`summary\` saying what the operation does',
110
+ sample: {
111
+ document: ${openapiSample(name).replaceAll('\n', '\n ')},
112
+ findings: [{ pointer: '#/paths/~1pets/get', message: '\`summary\` is missing' }],
113
+ },
114
+ },
115
+ },
116
+ };
117
+ `;
118
+ const seeded = (name, seed) => `${header(name, 'rules', '`lint` rules')}import { type Plugin } from 'contractdiff/testing';
119
+
120
+ // Seeded from one finding: \`check\` flags exactly the node it was found at. Widen it to say what makes
121
+ // any node this mistake, then add the documents it should and should not flag to \`sample\`.
122
+ const DOCUMENT = ${literal(seed.document, 0)};
123
+
124
+ export const plugin: Plugin = {
125
+ name: '${name}',
126
+ rules: {
127
+ '${name}': {
128
+ description: ${JSON.stringify(`Never again: ${seed.message}`)},
129
+ given: { select: '${seed.select}' },
130
+ check: (node) => (node.pointer === ${JSON.stringify(seed.pointer)} ? [${JSON.stringify(seed.message)}] : []),
131
+ fix: ${JSON.stringify(seed.fix)},
132
+ sample: {
133
+ document: DOCUMENT,
134
+ findings: ${literal(seed.findings, SAMPLE_DEPTH)},
135
+ },
136
+ },
137
+ },
138
+ };
139
+ `;
140
+ const test = (name, kind) => `import { test } from 'node:test';
141
+
142
+ import { conformance } from 'contractdiff/testing';
143
+
144
+ import { ${kind === 'adapter' ? 'mutate, plugin' : 'plugin'} } from './plugin-${name}.js';
145
+
146
+ test('the ${name} plugin passes the contractdiff conformance suite', async () => {
147
+ await conformance(plugin${kind === 'adapter' ? ', { mutate }' : ''});
148
+ });
149
+ `;
150
+ const readme = (name, kind) => `# ${name}
151
+
152
+ An [contractdiff](https://github.com/ofri-peretz/burgee/tree/main/packages/contractdiff) plugin: a
153
+ ${kind}, scaffolded by \`contractdiff plugin new ${name} --kind ${kind}\`.
154
+
155
+ ## Check it
156
+
157
+ \`\`\`sh
158
+ node --test plugin-${name}.test.ts
159
+ \`\`\`
160
+
161
+ The test runs the conformance suite from \`contractdiff/testing\`. It passes as scaffolded, and it
162
+ names every rule a change breaks, each with a \`fix:\` line:
163
+
164
+ | Rule | What it asks |
165
+ |---|---|
166
+ | \`schema\` | \`validate\` accepts the plugin, and it contributes a generator, an extractor, an adapter or a rule |
167
+ | \`sample\` | \`run\` on \`sample.document\` returns exactly \`sample.files\` (an extractor: \`sample.document\`; a rule: \`sample.findings\`) |
168
+ | \`deterministic\` | two runs give the same bytes |
169
+ | \`regeneration\` | after a spec change, every \`owner: 'user'\` file is byte for byte what it was |
170
+ | \`roundtrip\` | with \`{ extractor }\`: extracting what the generator wrote gives back the sample contract |
171
+ | \`fix-lines\` | every refusal and every finding says what to do: \`fix: …\` |
172
+ | \`paths\` | every path stays inside the output folder, even for an operation id with \`../\` in it |
173
+ | \`no-io\` | a rule reads only the node and the contract it is given: it never calls \`fetch\` |
174
+
175
+ ## Use it
176
+
177
+ The files are ES modules: keep them in a package with \`"type": "module"\`. Add the plugin to \`contractdiff.config.json\`:
178
+
179
+ \`\`\`json
180
+ { "plugins": ["./plugin-${name}.ts"] }
181
+ \`\`\`
182
+ `;
183
+ export const scaffold = (name, kind, seed) => {
184
+ checkName(name);
185
+ const templates = { generator, extractor, adapter, rules: rule };
186
+ if (!KINDS.includes(kind))
187
+ throw new Error(`"${String(kind)}" is not a plugin kind. fix: pass --kind ${KINDS.join(', --kind ')}`);
188
+ if (seed !== undefined && kind !== 'rules')
189
+ throw new Error(`a seed makes a rule, and the kind is ${kind}. fix: pass --kind rules with --from`);
190
+ const source = seed === undefined ? templates[kind](name) : seeded(name, seed);
191
+ return [
192
+ { path: `plugin-${name}.ts`, owner: 'user', content: source },
193
+ { path: `plugin-${name}.test.ts`, owner: 'user', content: test(name, kind) },
194
+ { path: 'README.md', owner: 'user', content: readme(name, kind) },
195
+ ];
196
+ };
@@ -0,0 +1,43 @@
1
+ import { findingsOn } from './lint-engine.js';
2
+ import { failureOf } from './testing-rules.js';
3
+ const NO_IO = 'a rule reads only the node and the contract it is given: no network, no files, no model';
4
+ const runOn = (host, rule, document) => {
5
+ const real = globalThis.fetch;
6
+ let fetched = false;
7
+ globalThis.fetch = (() => {
8
+ fetched = true;
9
+ throw new Error(NO_IO);
10
+ });
11
+ try {
12
+ return { findings: findingsOn(rule, host.read(document)), fetched };
13
+ }
14
+ catch (error) {
15
+ return { error, fetched };
16
+ }
17
+ finally {
18
+ globalThis.fetch = real;
19
+ }
20
+ };
21
+ const show = (findings) => JSON.stringify(findings);
22
+ const checkRule = (host, id, rule, corpus) => {
23
+ const where = `rule "${id}"`;
24
+ const sample = rule.sample;
25
+ const documents = [{ where: `${where} on its sample`, document: sample.document }, ...corpus.map((document, index) => ({ where: `${where} on corpus document ${String(index)}`, document }))];
26
+ return documents.flatMap(({ where: at, document }, index) => {
27
+ const first = runOn(host, rule, document);
28
+ const again = runOn(host, rule, document);
29
+ if (first.fetched || again.fetched)
30
+ return [{ rule: 'no-io', where: at, message: 'it called fetch', fix: NO_IO }];
31
+ if ('error' in first)
32
+ return [failureOf('sample', at, first.error, 'make the rule run on any document an adapter reads, without throwing')];
33
+ const failures = [];
34
+ if (index === 0 && show(first.findings) !== show(sample.findings)) {
35
+ failures.push({ rule: 'sample', where: at, message: `it finds ${show(first.findings)}; the sample says ${show(sample.findings)}`, fix: 'make `sample.findings` exactly what the rule finds on `sample.document`, or fix the rule' });
36
+ }
37
+ if ('error' in again || show(again.findings) !== show(first.findings)) {
38
+ failures.push({ rule: 'deterministic', where: at, message: 'two runs found different things', fix: 'remove whatever changes between runs: time, random values, iteration order, state kept between calls' });
39
+ }
40
+ return failures;
41
+ });
42
+ };
43
+ export const ruleFailures = (host, rules, corpus) => Object.entries(rules).flatMap(([id, rule]) => checkRule(host, id, rule, corpus));
@@ -0,0 +1,17 @@
1
+ export const plan = (files, disk) => files.map((file) => {
2
+ const current = disk.get(file.path);
3
+ if (current === file.content)
4
+ return { path: file.path, action: 'unchanged' };
5
+ return { path: file.path, action: current !== undefined && file.owner === 'user' ? 'skip' : 'write' };
6
+ });
7
+ export const unsafe = (before, after) => {
8
+ const disk = new Map(before.map((file) => [file.path, file.content]));
9
+ const owners = new Map(before.map((file) => [file.path, file.owner]));
10
+ return plan(after, disk).flatMap(({ path, action }) => {
11
+ if (action === 'skip')
12
+ return [{ path, problem: 'user file changes' }];
13
+ if (action === 'write' && owners.get(path) === 'user')
14
+ return [{ path, problem: 'user file becomes generated' }];
15
+ return [];
16
+ });
17
+ };
@@ -0,0 +1,25 @@
1
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2
+ export const PROBE_ID = 'conformanceProbe';
3
+ export const PROBE_PROPERTY = 'conformanceProbe';
4
+ export const HOSTILE_ID = '../conformance-probe';
5
+ const withOperation = (document, path, id) => {
6
+ if (!isDict(document) || !isDict(document.paths))
7
+ return undefined;
8
+ const copy = structuredClone(document);
9
+ return { ...copy, paths: { ...copy.paths, [path]: { get: { operationId: id, responses: { '200': { description: 'the conformance probe' } } } } } };
10
+ };
11
+ const namedSchemas = (document) => [
12
+ ...Object.values(isDict(document.components) && isDict(document.components.schemas) ? document.components.schemas : {}),
13
+ ...Object.values(isDict(document.definitions) ? document.definitions : {}),
14
+ ];
15
+ export const changed = (document) => {
16
+ const copy = withOperation(document, '/conformance-probe', PROBE_ID);
17
+ if (copy === undefined)
18
+ return undefined;
19
+ for (const schema of namedSchemas(copy)) {
20
+ if (isDict(schema) && isDict(schema.properties))
21
+ schema.properties[PROBE_PROPERTY] = { type: 'string' };
22
+ }
23
+ return copy;
24
+ };
25
+ export const hostile = (document) => withOperation(document, '/conformance-hostile', HOSTILE_ID);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The eight rules of the conformance suite (apicontract-kit R2), one function each. A rule reads
3
+ * what the suite observed and returns its failures; it never throws, so one broken rule cannot
4
+ * hide another. The shared definition of done they check is `.sdlc/intents/contractdiff/program.md`.
5
+ */
6
+ import { type ContractFinding } from './core/model.js';
7
+ import { type Extractor, type Finding, type Generator, type Host } from './host.js';
8
+ export declare const RULES: readonly ["schema", "sample", "deterministic", "regeneration", "roundtrip", "fix-lines", "paths", "no-io"];
9
+ export type Rule = (typeof RULES)[number];
10
+ /** One rule broken in one place, and what to do about it. */
11
+ export interface Failure {
12
+ readonly rule: Rule;
13
+ readonly where: string;
14
+ readonly message: string;
15
+ readonly fix: string;
16
+ }
17
+ /** What one generator call returned, or what it threw. */
18
+ export type Outcome = {
19
+ readonly files: unknown;
20
+ readonly findings: readonly ContractFinding[];
21
+ } | {
22
+ readonly error: unknown;
23
+ };
24
+ /** One generator call the suite made, on the sample or on a document derived from it. */
25
+ export interface Run {
26
+ readonly where: string;
27
+ readonly outcome: Outcome;
28
+ /** The same call made a second time, where the rule is that it must not differ. */
29
+ readonly again?: Outcome;
30
+ }
31
+ /** What `checkPlugin` reported, or what it threw. */
32
+ export type Checked = {
33
+ readonly findings: readonly Finding[];
34
+ } | {
35
+ readonly error: unknown;
36
+ };
37
+ /** Whether a refusal says what to do about it. */
38
+ export declare const hasFix: (error: unknown) => boolean;
39
+ /** A thrown error as a failure: its own `fix:` line when it carries one, `fallback` when not. */
40
+ export declare const failureOf: (rule: Rule, where: string, error: unknown, fallback: string) => Failure;
41
+ /** Call a generator and keep what it returned or threw. */
42
+ export declare const outcome: (call: () => unknown) => Promise<Outcome>;
43
+ /** `schema`: `host.validate` accepts the plugin, and it contributes something contractdiff reads. */
44
+ export declare const schema: (plugin: unknown) => Failure[];
45
+ /** `sample`: each generator's run on its sample document returns exactly the files the sample declares. */
46
+ export declare const sample: (checked: Checked) => Failure[];
47
+ /** `deterministic`: two runs on one document return the same bytes, on the sample and on every corpus document. */
48
+ export declare const deterministic: (checked: Checked, runs: readonly Run[]) => Failure[];
49
+ /** One generator before and after a spec change. `after` is absent when the suite cannot change the sample. */
50
+ export interface Regeneration {
51
+ readonly generator: string;
52
+ readonly before: Outcome;
53
+ readonly after: Outcome | undefined;
54
+ }
55
+ /** `regeneration`: after a spec change, the writer's owner rule leaves every user file as it was. */
56
+ export declare const regeneration: (cases: readonly Regeneration[]) => Failure[];
57
+ /** `paths`: every file every run returned passes `validateFiles`, including on an operation id that tries to leave the folder. */
58
+ export declare const paths: (runs: readonly Run[]) => Failure[];
59
+ /** `fix-lines`: every refusal a run threw, and every finding it returned, says what to do about it. */
60
+ export declare const fixLines: (checked: Checked, runs: readonly Run[]) => Failure[];
61
+ /**
62
+ * `roundtrip` (R-RT): `extract(gen(spec))` reads as the same contract as `spec`. The extractor runs
63
+ * with its sample's options and `files`, the files the generator returned for its sample.
64
+ */
65
+ export declare const roundtrip: (host: Host, generators: readonly (readonly [string, Generator])[], extractor: Extractor) => Promise<Failure[]>;
@@ -0,0 +1,115 @@
1
+ import { documentOf, resultOf, validate, validateFiles } from './host.js';
2
+ import { unsafe } from './testing-owner.js';
3
+ export const RULES = ['schema', 'sample', 'deterministic', 'regeneration', 'roundtrip', 'fix-lines', 'paths', 'no-io'];
4
+ const MARK = 'fix: ';
5
+ const textOf = (error) => (error instanceof Error ? error.message : String(error));
6
+ export const hasFix = (error) => textOf(error).includes(MARK);
7
+ export const failureOf = (rule, where, error, fallback) => {
8
+ const text = textOf(error);
9
+ const at = text.indexOf(MARK);
10
+ if (at === -1)
11
+ return { rule, where, message: text, fix: fallback };
12
+ return { rule, where, message: text.slice(0, at).replace(/[.\s]+$/u, ''), fix: text.slice(at + MARK.length) };
13
+ };
14
+ export const outcome = async (call) => {
15
+ try {
16
+ const { files, findings } = resultOf(await call());
17
+ return { files, findings };
18
+ }
19
+ catch (error) {
20
+ return { error };
21
+ }
22
+ };
23
+ const isError = (value) => 'error' in value;
24
+ export const schema = (plugin) => {
25
+ try {
26
+ validate(plugin);
27
+ }
28
+ catch (error) {
29
+ return [failureOf('schema', 'plugin', error, 'export the shape `Plugin` in contractdiff describes')];
30
+ }
31
+ const { adapters = {}, generators = {}, extractors = {}, rules = {} } = plugin;
32
+ if (Object.keys({ ...adapters, ...generators, ...extractors, ...rules }).length > 0)
33
+ return [];
34
+ return [{ rule: 'schema', where: `plugin "${plugin.name}"`, message: 'it contributes no adapter, generator, extractor or rule', fix: 'add `generators`, `extractors`, `adapters` or `rules`' }];
35
+ };
36
+ export const sample = (checked) => {
37
+ if ('error' in checked)
38
+ return [failureOf('sample', 'sample', checked.error, 'make `run` succeed on its own `sample.document`')];
39
+ return checked.findings
40
+ .filter((finding) => finding.problem !== 'not deterministic')
41
+ .map((finding) => ({ rule: 'sample', where: `${finding.generator}: ${finding.path}`, message: `the file is ${finding.problem}`, fix: finding.fix }));
42
+ };
43
+ const fingerprint = (side) => (isError(side) ? textOf(side.error) : JSON.stringify([side.files, side.findings]));
44
+ const same = (first, second) => fingerprint(first) === fingerprint(second);
45
+ export const deterministic = (checked, runs) => [
46
+ ...('error' in checked ? [] : checked.findings.filter((finding) => finding.problem === 'not deterministic')).map((finding) => ({ rule: 'deterministic', where: `${finding.generator}: ${finding.path}`, message: 'two runs on the sample differ', fix: finding.fix })),
47
+ ...runs
48
+ .filter((run) => run.again !== undefined && !same(run.outcome, run.again))
49
+ .map((run) => ({ rule: 'deterministic', where: run.where, message: 'two runs on the same document differ', fix: 'remove whatever changes between runs: time, random values, iteration order' })),
50
+ ];
51
+ export const regeneration = (cases) => cases.flatMap(({ generator, before, after }) => {
52
+ const where = `generator "${generator}"`;
53
+ if (after === undefined) {
54
+ return [{ rule: 'regeneration', where, message: 'the suite cannot add an operation to this sample document', fix: 'pass `mutate` to `conformance`: a function that returns the sample document with one operation more' }];
55
+ }
56
+ for (const side of [before, after]) {
57
+ if (isError(side))
58
+ return [failureOf('regeneration', where, side.error, 'make `run` succeed on the sample document with one operation more')];
59
+ }
60
+ const files = (side) => validateFiles(side.files, where);
61
+ try {
62
+ return unsafe(files(before), files(after)).map(({ path, problem }) => ({
63
+ rule: 'regeneration',
64
+ where: `${generator}: ${path}`,
65
+ message: `the ${problem} when the spec changes`,
66
+ fix: 'keep a user file the same whatever the spec says; put what follows the spec in a generated file it imports',
67
+ }));
68
+ }
69
+ catch {
70
+ return [];
71
+ }
72
+ });
73
+ export const paths = (runs) => runs.flatMap((run) => [run.outcome, run.again].flatMap((side) => {
74
+ if (side === undefined || isError(side))
75
+ return [];
76
+ try {
77
+ validateFiles(side.files, run.where);
78
+ return [];
79
+ }
80
+ catch (error) {
81
+ return [failureOf('paths', run.where, error, 'return relative paths with `/` separators')];
82
+ }
83
+ }));
84
+ export const fixLines = (checked, runs) => {
85
+ const thrown = runs.flatMap((run) => [run.outcome, run.again].flatMap((side) => (side !== undefined && isError(side) ? [{ where: run.where, error: side.error }] : [])));
86
+ if ('error' in checked && !thrown.some(({ error }) => textOf(error) === textOf(checked.error)))
87
+ thrown.unshift({ where: 'sample', error: checked.error });
88
+ const findings = runs.flatMap((run) => (isError(run.outcome) ? [] : run.outcome.findings.map((finding) => ({ where: run.where, finding }))));
89
+ return [
90
+ ...thrown
91
+ .filter(({ error }) => !hasFix(error))
92
+ .map(({ where, error }) => ({ rule: 'fix-lines', where, message: `it refused without a fix line: ${textOf(error)}`, fix: 'end the message with `fix: <what to do>`, or throw a `PluginError`' })),
93
+ ...findings
94
+ .filter(({ finding }) => typeof finding.fix !== 'string' || finding.fix.trim() === '')
95
+ .map(({ where, finding }) => ({ rule: 'fix-lines', where, message: `its finding "${finding.code}" has no fix`, fix: 'give every finding a `fix`: what the user does about it' })),
96
+ ];
97
+ };
98
+ const canonical = (value) => JSON.stringify(value, (_key, inner) => typeof inner === 'object' && inner !== null && !Array.isArray(inner) ? Object.fromEntries(Object.entries(inner).toSorted(([a], [b]) => a.localeCompare(b))) : inner);
99
+ const shape = (host, document) => canonical(Object.fromEntries(host.read(document).operations.map((operation) => [operation.id, operation.payloads])));
100
+ export const roundtrip = async (host, generators, extractor) => {
101
+ const one = async ([name, generator]) => {
102
+ const where = `generator "${name}"`;
103
+ try {
104
+ const files = validateFiles(resultOf(await generator.run(host.read(generator.sample.document), generator.sample.options ?? {})).files, where);
105
+ const extracted = documentOf(await extractor.run({ ...extractor.sample.options, files })).document;
106
+ if (shape(host, extracted) === shape(host, generator.sample.document))
107
+ return [];
108
+ return [{ rule: 'roundtrip', where, message: 'extracting what it generated does not give back the sample contract', fix: 'make the extractor read every operation and payload the generator writes' }];
109
+ }
110
+ catch (error) {
111
+ return [failureOf('roundtrip', where, error, 'make the extractor read the files the generator writes')];
112
+ }
113
+ };
114
+ return (await Promise.all(generators.map(one))).flat();
115
+ };
@@ -0,0 +1,32 @@
1
+ import { type Extractor } from './host.js';
2
+ import { type Failure } from './testing-rules.js';
3
+ export interface ConformanceOptions {
4
+ /** More documents to run every generator on: each must give the same bytes twice, and safe paths. */
5
+ readonly corpus?: readonly unknown[];
6
+ /**
7
+ * The sample document after a spec change, for the `regeneration` rule. The suite makes this
8
+ * itself for an OpenAPI or Swagger sample (one operation and one property more); any other
9
+ * format needs it.
10
+ */
11
+ readonly mutate?: (document: unknown) => unknown;
12
+ /** The extract half, for the `roundtrip` rule: run with its sample's options plus `files`, what the generator wrote. */
13
+ readonly extractor?: Extractor;
14
+ /** The generator `extractor` pairs with. Every generator of the plugin, when absent. */
15
+ readonly generator?: string;
16
+ }
17
+ /** Every rule a plugin broke. Its message is the list, one failure and its `fix:` line per entry. */
18
+ export declare class ConformanceError extends Error {
19
+ readonly failures: readonly Failure[];
20
+ constructor(plugin: string, failures: readonly Failure[]);
21
+ }
22
+ /**
23
+ * Run the conformance suite on `plugin`. Resolves when it passes every rule; rejects with a
24
+ * `ConformanceError` naming every rule it breaks. A plugin `host.validate` refuses is reported
25
+ * under `schema` alone, since no other rule can run on it.
26
+ */
27
+ export declare const conformance: (plugin: unknown, options?: ConformanceOptions) => Promise<void>;
28
+ export { type Failure, type Rule, RULES } from './testing-rules.js';
29
+ export { type Contract, type ContractFinding, type Operation, type Payload } from './core/model.js';
30
+ export { type Rule as LintRule, type RuleSample, type SampleFinding } from './lint-engine.js';
31
+ export { type LintNode } from './lint-select.js';
32
+ export { type Adapter, type Extractor, type GeneratedFile, type Generator, type GeneratorResult, type Options, type Plugin, PluginError } from './host.js';
@@ -0,0 +1,79 @@
1
+ import { checkPlugin, createHost } from './host.js';
2
+ import { builtinAdapters } from './inputs.js';
3
+ import { ruleFailures } from './testing-lint.js';
4
+ import { changed, hostile } from './testing-probe.js';
5
+ import { deterministic, fixLines, outcome, paths, regeneration, roundtrip, sample, schema, } from './testing-rules.js';
6
+ export class ConformanceError extends Error {
7
+ failures;
8
+ constructor(plugin, failures) {
9
+ const lines = failures.map((failure) => `- ${failure.rule}: ${failure.where}: ${failure.message}\n fix: ${failure.fix}`);
10
+ const rules = new Set(failures.map((failure) => failure.rule)).size;
11
+ super(`plugin "${plugin}" breaks ${String(rules)} conformance rule(s) in ${String(failures.length)} place(s):\n${lines.join('\n')}`);
12
+ this.name = 'ConformanceError';
13
+ this.failures = failures;
14
+ }
15
+ }
16
+ const refuse = (label, failures) => {
17
+ if (failures.length > 0)
18
+ throw new ConformanceError(label, failures);
19
+ };
20
+ const generatorsOf = (plugin) => Object.entries(plugin.generators ?? {});
21
+ const checked = async (plugin) => {
22
+ try {
23
+ return { findings: await checkPlugin(plugin) };
24
+ }
25
+ catch (error) {
26
+ return { error };
27
+ }
28
+ };
29
+ const observe = async (host, [name, generator], options) => {
30
+ const settings = generator.sample.options ?? {};
31
+ const on = async (document) => outcome(async () => generator.run(host.read(document), settings));
32
+ const where = (what) => `generator "${name}" ${what}`;
33
+ const changedDocument = (options.mutate ?? changed)(generator.sample.document);
34
+ const probe = hostile(generator.sample.document);
35
+ const [before, after, escaping, empty, corpus] = await Promise.all([
36
+ on(generator.sample.document),
37
+ changedDocument === undefined ? undefined : on(changedDocument),
38
+ probe === undefined ? undefined : on(probe),
39
+ outcome(async () => {
40
+ const contract = { ...host.read(generator.sample.document), operations: [] };
41
+ return generator.run(contract, settings);
42
+ }),
43
+ Promise.all((options.corpus ?? []).map(async (document, index) => ({ where: where(`on corpus document ${String(index)}`), outcome: await on(document), again: await on(document) }))),
44
+ ]);
45
+ const runs = [
46
+ { where: where('on its sample'), outcome: before },
47
+ ...(after === undefined ? [] : [{ where: where('after a spec change'), outcome: after }]),
48
+ ...(escaping === undefined ? [] : [{ where: where('on an operation id with "../" in it'), outcome: escaping }]),
49
+ { where: where('on a contract with no operations'), outcome: empty },
50
+ ...corpus,
51
+ ];
52
+ return { runs, regeneration: { generator: name, before, after } };
53
+ };
54
+ export const conformance = async (plugin, options = {}) => {
55
+ const refused = schema(plugin);
56
+ const name = plugin?.name;
57
+ const label = typeof name === 'string' ? name : 'unnamed';
58
+ refuse(label, refused);
59
+ const valid = plugin;
60
+ const host = createHost();
61
+ host.register({ name: 'contractdiff', adapters: builtinAdapters });
62
+ host.register(valid);
63
+ const report = await checked(valid);
64
+ const observed = await Promise.all(generatorsOf(valid).map(async (entry) => observe(host, entry, options)));
65
+ const runs = observed.flatMap((one) => one.runs);
66
+ const paired = generatorsOf(valid).filter(([generatorName]) => options.generator === undefined || generatorName === options.generator);
67
+ const failures = [
68
+ ...sample(report),
69
+ ...deterministic(report, runs),
70
+ ...regeneration(observed.map((one) => one.regeneration)),
71
+ ...(options.extractor === undefined ? [] : await roundtrip(host, paired, options.extractor)),
72
+ ...fixLines(report, runs),
73
+ ...paths(runs),
74
+ ...ruleFailures(host, valid.rules ?? {}, options.corpus ?? []),
75
+ ];
76
+ refuse(label, failures);
77
+ };
78
+ export { RULES } from './testing-rules.js';
79
+ export { PluginError } from './host.js';