contractdiff 0.0.0-stage → 0.4.0

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 +408 -0
  150. package/dist/props-judge.js +30 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +170 -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,170 @@
1
+ import { payloadRules } from './diff-classify.js';
2
+ import { compareContracts, pair } from './diff-contract.js';
3
+ import { canonical, isDict, normalise } from './diff-normalise.js';
4
+ import { drawFrom, make } from './props-generate.js';
5
+ import { draftOf, rooted, validatorJudge } from './props-judge.js';
6
+ import { mutate } from './props-mutate.js';
7
+ import { randomFrom } from './props-random.js';
8
+ import { shrink } from './props-shrink.js';
9
+ export const PROPERTIES = ['agreement', 'round-trip', 'normalise', 'soundness'];
10
+ export const SUBJECT = { validator: validatorJudge, normalise, encode: (value) => JSON.stringify(value), decode: (text) => JSON.parse(text), compare: compareContracts };
11
+ const judge = (subject, schema, document, draft) => {
12
+ try {
13
+ return subject.validator(rooted(schema, document), draft);
14
+ }
15
+ catch (error) {
16
+ return error.message;
17
+ }
18
+ };
19
+ const show = (value) => String(JSON.stringify(value));
20
+ const covers = (issue, path) => issue === path || path.startsWith(`${issue}/`);
21
+ const tally = (run, property) => run.tallies.get(property);
22
+ const fail = (run, counterexample) => {
23
+ tally(run, counterexample.property).failed += 1;
24
+ const same = (found) => found.property === counterexample.property && found.operation === counterexample.operation && found.payload === counterexample.payload;
25
+ if (!run.counterexamples.some(same))
26
+ run.counterexamples.push(counterexample);
27
+ };
28
+ const drawIn = (run, contract) => drawFrom(run.random, contract.document, draftOf(contract));
29
+ const gather = (into, from) => {
30
+ for (const [keyword, at] of from)
31
+ into.set(keyword, new Set([...(into.get(keyword) ?? []), ...at]));
32
+ };
33
+ const agreement = (run, check, draw, value) => {
34
+ const { where, own } = check;
35
+ if (!own.accepts(value)) {
36
+ if (draw.exact)
37
+ fail(run, { property: 'agreement', ...where, value, detail: `made from the schema, refused by the validator at ${own.paths(value).join(', ')}` });
38
+ const counted = tally(run, 'agreement');
39
+ if (draw.exact)
40
+ counted.checked += 1;
41
+ else
42
+ counted.discarded += 1;
43
+ return [];
44
+ }
45
+ tally(run, 'agreement').checked += 1;
46
+ const mutant = draw.exact ? mutate(draw, check.schema, value) : undefined;
47
+ if (mutant === undefined)
48
+ return [value];
49
+ const paths = own.paths(mutant.value);
50
+ const at = mutant.path || '/';
51
+ if (paths.length === 0)
52
+ fail(run, { property: 'agreement', ...where, value: mutant.value, detail: `\`${mutant.keyword}\` broken at ${at}, and the validator accepted it` });
53
+ else if (!paths.some((path) => covers(path, mutant.path)))
54
+ fail(run, { property: 'agreement', ...where, value: mutant.value, detail: `\`${mutant.keyword}\` broken at ${at}, refused at ${paths.join(', ')} instead` });
55
+ return [value, mutant.value];
56
+ };
57
+ const roundTrip = (run, check, value) => {
58
+ const { subject } = run;
59
+ const { own } = check;
60
+ tally(run, 'round-trip').checked += 1;
61
+ const broken = (candidate) => {
62
+ const back = subject.decode(subject.encode(candidate));
63
+ return canonical(back) !== canonical(candidate);
64
+ };
65
+ if (!broken(value))
66
+ return;
67
+ fail(run, { property: 'round-trip', ...check.where, value: shrink(value, (candidate) => own.accepts(candidate) && broken(candidate)), detail: 'changed through JSON text and back' });
68
+ };
69
+ const sameMeaning = (run, check, values) => {
70
+ const { own, normal } = check;
71
+ if (typeof normal === 'string')
72
+ return;
73
+ tally(run, 'normalise').checked += 1;
74
+ const differs = (candidate) => own.accepts(candidate) !== normal.accepts(candidate);
75
+ const found = values.find(differs);
76
+ if (found === undefined)
77
+ return;
78
+ fail(run, { property: 'normalise', ...check.where, value: shrink(found, differs), detail: `the schema ${own.accepts(found) ? 'accepts' : 'refuses'} it and its normalised form does not: ${show(check.once)}` });
79
+ };
80
+ const onPayload = (run, contract, operation, payload) => {
81
+ const draft = draftOf(contract);
82
+ const where = { operation, payload: payload.name };
83
+ const { subject } = run;
84
+ const own = judge(subject, payload.schema, contract.document, draft);
85
+ if (typeof own === 'string') {
86
+ run.skipped.push({ ...where, reason: own });
87
+ return;
88
+ }
89
+ const once = subject.normalise(payload.schema);
90
+ const twice = subject.normalise(once);
91
+ if (canonical(twice) !== canonical(once))
92
+ fail(run, { property: 'normalise', ...where, value: payload.schema, detail: `normalising twice gives ${show(twice)}, once gives ${show(once)}` });
93
+ const check = { where, schema: payload.schema, own, normal: judge(subject, once, contract.document, draft), once };
94
+ let made = false;
95
+ for (let index = 0; index < run.runs; index += 1) {
96
+ const draw = drawIn(run, contract);
97
+ const drawn = make(draw, payload.schema);
98
+ gather(run.reported, draw.reported);
99
+ if (drawn === undefined)
100
+ continue;
101
+ made = true;
102
+ const values = agreement(run, check, draw, drawn.value);
103
+ if (values.length === 0)
104
+ continue;
105
+ roundTrip(run, check, drawn.value);
106
+ sameMeaning(run, check, values);
107
+ }
108
+ if (!made)
109
+ run.skipped.push({ ...where, reason: 'no value could be made from the schema: it accepts nothing, or only values behind a reported keyword' });
110
+ };
111
+ const compatible = (run, contracts, question) => {
112
+ const { old, nu } = contracts;
113
+ const comparison = run.subject.compare(old, nu, question);
114
+ const flagged = (operation, payload) => comparison.findings.some((finding) => finding.operation === operation && (finding.payload === undefined || finding.payload === payload) && finding.verdict !== 'non-breaking');
115
+ return pair(old.operations, nu.operations).flatMap(([before, after]) => {
116
+ if (before === undefined || after === undefined)
117
+ return [];
118
+ return after.payloads.flatMap((payload) => {
119
+ const previous = before.payloads.find((candidate) => candidate.name === payload.name);
120
+ if (previous === undefined || flagged(after.id, payload.name))
121
+ return [];
122
+ return payloadRules(payload.direction, question.mode, question.side).map((rule) => {
123
+ const sides = { old: { contract: old, payload: previous }, nu: { contract: nu, payload } };
124
+ return { operation: after.id, payload: payload.name, rule, from: rule === 'backward' ? sides.old : sides.nu, to: rule === 'backward' ? sides.nu : sides.old };
125
+ });
126
+ });
127
+ });
128
+ };
129
+ const soundness = (run, sound) => {
130
+ const { from, to, rule } = sound;
131
+ const source = judge(run.subject, from.payload.schema, from.contract.document, draftOf(from.contract));
132
+ const sink = judge(run.subject, to.payload.schema, to.contract.document, draftOf(to.contract));
133
+ if (typeof source === 'string' || typeof sink === 'string')
134
+ return;
135
+ const fails = (candidate) => source.accepts(candidate) && !sink.accepts(candidate);
136
+ for (let index = 0; index < run.runs; index += 1) {
137
+ const drawn = make(drawIn(run, from.contract), from.payload.schema);
138
+ if (drawn === undefined || !source.accepts(drawn.value))
139
+ continue;
140
+ tally(run, 'soundness').checked += 1;
141
+ if (!fails(drawn.value))
142
+ continue;
143
+ const value = shrink(drawn.value, fails);
144
+ const [sender, receiver] = rule === 'backward' ? ['old', 'new'] : ['new', 'old'];
145
+ fail(run, { property: 'soundness', operation: sound.operation, payload: sound.payload, value, detail: `called compatible (${rule}), but the ${sender} contract sends this and the ${receiver} one refuses it at ${sink.paths(value).join(', ')}` });
146
+ return;
147
+ }
148
+ };
149
+ export const runProps = (contract, options) => {
150
+ const run = {
151
+ subject: { ...SUBJECT, ...options.subject },
152
+ random: randomFrom(options.seed),
153
+ runs: options.runs,
154
+ tallies: new Map(PROPERTIES.map((property) => [property, { checked: 0, discarded: 0, failed: 0 }])),
155
+ counterexamples: [],
156
+ reported: new Map(),
157
+ skipped: [],
158
+ };
159
+ for (const operation of contract.operations) {
160
+ for (const payload of operation.payloads)
161
+ if (payload.schema !== false)
162
+ onPayload(run, contract, operation.id, payload);
163
+ }
164
+ if (options.against !== undefined) {
165
+ for (const sound of compatible(run, { old: options.against, nu: contract }, { mode: options.mode ?? 'backward', side: options.side ?? 'caller' }))
166
+ soundness(run, sound);
167
+ }
168
+ const reported = [...run.reported].map(([keyword, at]) => ({ keyword, at: [...at].sort() })).sort((a, b) => a.keyword.localeCompare(b.keyword, 'en'));
169
+ return { seed: run.random.seed, runs: run.runs, tallies: Object.fromEntries(run.tallies), counterexamples: run.counterexamples, reported, skipped: run.skipped };
170
+ };
@@ -0,0 +1,75 @@
1
+ import { isDict } from './diff-normalise.js';
2
+ function* smallerArray(value) {
3
+ if (value.length > 1)
4
+ yield [];
5
+ for (let index = 0; index < value.length; index += 1)
6
+ yield value.filter((_, at) => at !== index);
7
+ for (const [index, old] of value.entries()) {
8
+ for (const item of smaller(old))
9
+ yield value.map((each, at) => (at === index ? item : each));
10
+ }
11
+ }
12
+ function* smallerObject(value) {
13
+ const entries = Object.entries(value);
14
+ for (const [key] of entries)
15
+ yield Object.fromEntries(entries.filter(([name]) => name !== key));
16
+ for (const [key, old] of entries) {
17
+ for (const item of smaller(old))
18
+ yield Object.fromEntries(entries.map(([name, each]) => [name, name === key ? item : each]));
19
+ }
20
+ }
21
+ function* smallerString(value) {
22
+ const points = [...value];
23
+ if (points.length === 0)
24
+ return;
25
+ yield '';
26
+ if (points.length === 1)
27
+ return;
28
+ yield points.slice(0, Math.floor(points.length / 2)).join('');
29
+ yield points.slice(0, -1).join('');
30
+ }
31
+ function* smallerNumber(value) {
32
+ if (value === 0)
33
+ return;
34
+ const candidates = [0];
35
+ if (!Number.isInteger(value))
36
+ candidates.push(Math.trunc(value));
37
+ candidates.push(Math.trunc(value / 2));
38
+ if (Number.isInteger(value))
39
+ candidates.push(value - Math.sign(value));
40
+ if (value < 0)
41
+ candidates.push(-value);
42
+ yield* new Set(candidates);
43
+ }
44
+ export function* smaller(value) {
45
+ if (Array.isArray(value))
46
+ yield* smallerArray(value);
47
+ else if (isDict(value))
48
+ yield* smallerObject(value);
49
+ else if (typeof value === 'string')
50
+ yield* smallerString(value);
51
+ else if (typeof value === 'number')
52
+ yield* smallerNumber(value);
53
+ else if (value === true)
54
+ yield false;
55
+ }
56
+ export const BUDGET = 500;
57
+ export const shrink = (value, fails, budget = BUDGET) => {
58
+ let current = value;
59
+ let tries = 0;
60
+ let improved = true;
61
+ while (improved && tries < budget) {
62
+ improved = false;
63
+ for (const candidate of smaller(current)) {
64
+ tries += 1;
65
+ if (fails(candidate)) {
66
+ current = candidate;
67
+ improved = true;
68
+ break;
69
+ }
70
+ if (tries >= budget)
71
+ break;
72
+ }
73
+ }
74
+ return current;
75
+ };
@@ -0,0 +1,25 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ export const readDisk = (root, paths) => {
4
+ const disk = new Map();
5
+ for (const path of paths) {
6
+ const file = join(root, path);
7
+ if (existsSync(file))
8
+ disk.set(path, readFileSync(file, 'utf8'));
9
+ }
10
+ return disk;
11
+ };
12
+ export const writeAtomic = (file, content) => {
13
+ mkdirSync(dirname(file), { recursive: true });
14
+ const temporary = `${file}.${String(process.pid)}.contractdiff-tmp`;
15
+ writeFileSync(temporary, content);
16
+ renameSync(temporary, file);
17
+ };
18
+ export const applyPlan = (root, planned) => {
19
+ for (const entry of planned) {
20
+ if (entry.action === 'delete')
21
+ rmSync(join(root, entry.path));
22
+ else if (entry.action === 'write')
23
+ writeAtomic(join(root, entry.path), entry.after);
24
+ }
25
+ };
@@ -0,0 +1,31 @@
1
+ import { defineCommand } from 'burgee';
2
+ import { extract } from './run-extract.js';
3
+ import { gen } from './run-gen.js';
4
+ const writing = {
5
+ check: { type: 'boolean', description: 'write nothing; exit 1 and list the files that are stale' },
6
+ dryRun: { type: 'boolean', description: 'write nothing; print the diff a run would write' },
7
+ force: { type: 'boolean', description: 'overwrite a generated file that was edited by hand' },
8
+ config: { type: 'string', description: 'the config file (default: contractdiff.config.json, .mjs or .ts in this folder)', placeholder: 'path' },
9
+ };
10
+ const HERE = '.';
11
+ export const genCommand = defineCommand({
12
+ name: 'gen',
13
+ description: 'Code from a spec, one plugin per target: TypeScript types, validators, NestJS modules',
14
+ effects: 'idempotent',
15
+ options: {
16
+ ...writing,
17
+ target: { type: 'string', multiple: true, description: 'run only this target (repeatable)', placeholder: 'name' },
18
+ },
19
+ run: async ({ options }) => gen({ cwd: HERE, config: options.config, targets: options.target, check: options.check, dryRun: options.dryRun, force: options.force }),
20
+ });
21
+ export const extractCommand = defineCommand({
22
+ name: 'extract',
23
+ description: 'A spec from your code, one plugin per source: validator schemas, NestJS, Hono',
24
+ effects: 'idempotent',
25
+ options: {
26
+ ...writing,
27
+ from: { type: 'string', description: 'the extractor to run (default: `extract.from` in the config)', placeholder: 'extractor' },
28
+ out: { type: 'string', description: 'the spec file to write (default: spec.json)', placeholder: 'file' },
29
+ },
30
+ run: async ({ options }) => extract({ cwd: HERE, config: options.config, from: options.from, out: options.out, check: options.check, dryRun: options.dryRun, force: options.force }),
31
+ });
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The tail every writing command shares (`gen`, `extract`): plan what the produced files do to the
3
+ * disk, refuse a hand edit, then print the diff (`--dry-run`), report what is stale (`--check`), or
4
+ * write the files and `contractdiff.map.json`. One place, so the safety rules hold for every target.
5
+ */
6
+ import { type ContractFinding } from './core/model.js';
7
+ import { type Owner } from './host.js';
8
+ import { type Produced } from './run-map.js';
9
+ import { type Action } from './run-plan.js';
10
+ export interface FileReport {
11
+ readonly path: string;
12
+ readonly owner: Owner;
13
+ readonly action: Action;
14
+ /** The target that produced it; absent for the map itself. */
15
+ readonly target?: string;
16
+ }
17
+ export interface Report {
18
+ readonly files: readonly FileReport[];
19
+ /** Whether a file was written or deleted, or would be under `--check` and `--dry-run`: what burgee asks of an idempotent command (N7). */
20
+ readonly changed: boolean;
21
+ /** How many files were written or deleted, or would be. */
22
+ readonly changes: number;
23
+ readonly unchanged: number;
24
+ /** User files left as they are. */
25
+ readonly skipped: number;
26
+ readonly findings: readonly (ContractFinding & {
27
+ readonly target: string;
28
+ })[];
29
+ /** `--dry-run`: the unified diff of every change. */
30
+ readonly diff?: string;
31
+ /** `--check`: the files that are not what a run would write. */
32
+ readonly stale?: readonly string[];
33
+ readonly exitCode?: 1;
34
+ readonly fix?: string;
35
+ }
36
+ export interface CommitOptions {
37
+ readonly root: string;
38
+ /** The command the generated headers name. */
39
+ readonly command: string;
40
+ readonly produced: readonly Produced[];
41
+ readonly findings: readonly (ContractFinding & {
42
+ readonly target: string;
43
+ })[];
44
+ readonly check?: boolean | undefined;
45
+ readonly dryRun?: boolean | undefined;
46
+ readonly force?: boolean | undefined;
47
+ }
48
+ /** Plan, refuse, and write (or only report). Throws on a hand edit in a generated file. */
49
+ export declare const commit: (options: CommitOptions) => Report;
50
+ /** Where a target's file lands: its `out` folder joined to the path the generator returned. */
51
+ export declare const under: (out: string, path: string) => string;
@@ -0,0 +1,48 @@
1
+ import { applyPlan, readDisk } from './run-apply.js';
2
+ import { unifiedDiff } from './run-diff.js';
3
+ import { MAP_FILE, parseMap, recordedFor, serializeMap, updateMap } from './run-map.js';
4
+ import { changes, plan } from './run-plan.js';
5
+ const count = (entries, action) => entries.filter((entry) => entry.action === action).length;
6
+ export const commit = (options) => {
7
+ const { root, command, produced } = options;
8
+ const all = produced.flatMap((entry) => entry.files);
9
+ const seen = new Map();
10
+ for (const { target, files } of produced) {
11
+ for (const file of files) {
12
+ const other = seen.get(file.path);
13
+ if (other !== undefined)
14
+ throw new Error(`targets "${other}" and "${target}" both write "${file.path}". fix: give them different \`out\` folders`);
15
+ seen.set(file.path, target);
16
+ }
17
+ }
18
+ const map = parseMap(readDisk(root, [MAP_FILE]).get(MAP_FILE));
19
+ const recorded = recordedFor(map, produced.map((entry) => entry.target));
20
+ const disk = readDisk(root, [...seen.keys(), ...recorded.keys(), MAP_FILE]);
21
+ const planned = plan(all, disk, { command, recorded, force: options.force });
22
+ const conflicts = planned.filter((entry) => entry.action === 'conflict').map((entry) => entry.path);
23
+ if (conflicts.length > 0) {
24
+ throw new Error(`generated files were edited by hand: ${conflicts.join(', ')}. fix: move the change to a user file, or pass --force`);
25
+ }
26
+ const before = disk.get(MAP_FILE);
27
+ const after = serializeMap(updateMap(map, produced));
28
+ const entries = [...planned, { path: MAP_FILE, owner: 'generated', action: before === after ? 'unchanged' : 'write', before, after }];
29
+ const targetOf = (path) => seen.get(path) ?? map.files[path].target;
30
+ const changed = changes(entries);
31
+ const report = {
32
+ files: entries.map((entry) => ({ path: entry.path, owner: entry.owner, action: entry.action, ...(entry.path === MAP_FILE ? {} : { target: targetOf(entry.path) }) })),
33
+ changed: changed.length > 0,
34
+ changes: changed.length,
35
+ unchanged: count(entries, 'unchanged'),
36
+ skipped: count(entries, 'skip'),
37
+ findings: options.findings,
38
+ };
39
+ if (options.check === true) {
40
+ const stale = changed.map((entry) => entry.path);
41
+ return stale.length === 0 ? { ...report, stale } : { ...report, stale, exitCode: 1, fix: `run \`${command}\` and commit the result` };
42
+ }
43
+ if (options.dryRun === true)
44
+ return { ...report, diff: changed.map((entry) => unifiedDiff(entry.path, entry.before, entry.after)).join('') };
45
+ applyPlan(root, entries);
46
+ return report;
47
+ };
48
+ export const under = (out, path) => (out === '.' ? path : `${out}/${path}`);
@@ -0,0 +1,193 @@
1
+ import { type Options } from './host.js';
2
+ export declare const CONFIG_FILES: readonly ["contractdiff.config.json", "contractdiff.config.mjs", "contractdiff.config.ts"];
3
+ export interface Target {
4
+ /** The generator's name, as a plugin registers it. */
5
+ readonly generator: string;
6
+ /** The output folder, relative to the project root, with `/` separators. */
7
+ readonly out: string;
8
+ readonly options: Options;
9
+ }
10
+ export interface ExtractConfig {
11
+ readonly from?: string;
12
+ readonly out?: string;
13
+ readonly options: Options;
14
+ }
15
+ /** `diff --decisions`: how a change is held to the decision written in the contract. */
16
+ export declare const DECISION_SETTINGS: readonly ["warn", "error", "off"];
17
+ export type DecisionSetting = (typeof DECISION_SETTINGS)[number];
18
+ export interface DiffConfig {
19
+ readonly decisions?: DecisionSetting;
20
+ }
21
+ export interface Config {
22
+ /** The folder the config file is in: every path in it is relative to this. */
23
+ readonly root: string;
24
+ readonly file: string;
25
+ readonly input?: string;
26
+ readonly overlays: readonly string[];
27
+ readonly plugins: readonly string[];
28
+ readonly targets: Readonly<Record<string, Target>>;
29
+ readonly extract: ExtractConfig;
30
+ /** Absent when the config has no `diff` section. */
31
+ readonly diff?: DiffConfig;
32
+ /** `contractdiff lint`'s rulesets and per-rule levels; absent when the config has no `lint` section. */
33
+ readonly lint?: LintConfig;
34
+ }
35
+ /** `lint`: the rulesets a run starts from, then each rule's level over them (apicontract-lint R8). */
36
+ export interface LintConfig {
37
+ readonly extends?: readonly string[];
38
+ readonly rules?: Readonly<Record<string, 'error' | 'warn' | 'off'>>;
39
+ /** How long a rule new at `error` warns first, e.g. `"14d"`; `"0d"` turns it off (R10). */
40
+ readonly warnFor?: string;
41
+ /** The ref `--since` defaults to: only operations changed since it are linted in full (R12). */
42
+ readonly since?: string;
43
+ /** The rules that still run on operations `--since` leaves untouched; none when absent (R12). */
44
+ readonly legacy?: readonly string[];
45
+ }
46
+ /** The JSON Schema `contractdiff.config.json` validates against. */
47
+ export declare const configSchema: {
48
+ readonly $schema: "https://json-schema.org/draft/2020-12/schema";
49
+ readonly title: "contractdiff.config.json";
50
+ readonly type: "object";
51
+ readonly additionalProperties: false;
52
+ readonly properties: {
53
+ readonly $schema: {
54
+ readonly type: "string";
55
+ };
56
+ readonly input: {
57
+ readonly type: "string";
58
+ readonly minLength: 1;
59
+ readonly description: "The spec, relative to this file: JSON or YAML";
60
+ };
61
+ readonly overlays: {
62
+ readonly type: "array";
63
+ readonly items: {
64
+ readonly type: "string";
65
+ readonly minLength: 1;
66
+ };
67
+ readonly description: "OpenAPI Overlays applied to the input, in order";
68
+ };
69
+ readonly plugins: {
70
+ readonly type: "array";
71
+ readonly items: {
72
+ readonly type: "string";
73
+ readonly minLength: 1;
74
+ };
75
+ readonly description: "Package names or relative paths; nothing else is loaded";
76
+ };
77
+ readonly targets: {
78
+ readonly type: "object";
79
+ readonly additionalProperties: {
80
+ readonly type: "object";
81
+ readonly additionalProperties: false;
82
+ readonly required: readonly ["generator", "out"];
83
+ readonly properties: {
84
+ readonly generator: {
85
+ readonly type: "string";
86
+ readonly minLength: 1;
87
+ };
88
+ readonly out: {
89
+ readonly type: "string";
90
+ readonly minLength: 1;
91
+ };
92
+ readonly options: {
93
+ readonly type: "object";
94
+ };
95
+ };
96
+ };
97
+ };
98
+ readonly extract: {
99
+ readonly type: "object";
100
+ readonly additionalProperties: false;
101
+ readonly properties: {
102
+ readonly from: {
103
+ readonly type: "string";
104
+ readonly minLength: 1;
105
+ };
106
+ readonly out: {
107
+ readonly type: "string";
108
+ readonly minLength: 1;
109
+ };
110
+ readonly options: {
111
+ readonly type: "object";
112
+ };
113
+ };
114
+ };
115
+ readonly diff: {
116
+ readonly type: "object";
117
+ readonly additionalProperties: false;
118
+ readonly properties: {
119
+ readonly decisions: {
120
+ readonly enum: readonly ["warn", "error", "off"];
121
+ readonly description: "How `contractdiff diff` holds a change to the decision written in the contract. The base ref's value wins over the working tree's; `--decisions` wins over both";
122
+ };
123
+ };
124
+ };
125
+ readonly lint: {
126
+ readonly type: "object";
127
+ readonly additionalProperties: false;
128
+ readonly properties: {
129
+ readonly extends: {
130
+ readonly type: "array";
131
+ readonly items: {
132
+ readonly type: "string";
133
+ readonly minLength: 1;
134
+ };
135
+ readonly description: "Rulesets, in order: `recommended`, `agent-ready`";
136
+ };
137
+ readonly rules: {
138
+ readonly type: "object";
139
+ readonly additionalProperties: {
140
+ readonly enum: readonly ["error", "warn", "off"];
141
+ };
142
+ readonly description: "A level per rule id, over the rulesets";
143
+ };
144
+ readonly warnFor: {
145
+ readonly type: "string";
146
+ readonly pattern: "^\\d+d$";
147
+ readonly description: "How long a rule new at error warns first, by the date it entered the ruleset: `\"14d\"` (the default); `\"0d\"` turns it off";
148
+ };
149
+ readonly since: {
150
+ readonly type: "string";
151
+ readonly minLength: 1;
152
+ readonly description: "The git ref `--since` defaults to: only operations added or changed since it run every rule; `merge-base` is the base with origin/main";
153
+ };
154
+ readonly legacy: {
155
+ readonly type: "array";
156
+ readonly items: {
157
+ readonly type: "string";
158
+ readonly minLength: 1;
159
+ };
160
+ readonly description: "Rule ids that still run on operations `since` leaves untouched; none by default";
161
+ };
162
+ };
163
+ };
164
+ };
165
+ };
166
+ /** The refusal for a config or a spec that cannot be used: exit 3 (R-A2), every problem on its own line with its fix. */
167
+ export declare class ConfigError extends Error {
168
+ readonly code = "CONFIG";
169
+ constructor(file: string, problems: readonly string[]);
170
+ }
171
+ /** The refusal for a command line to rewrite: exit 2 (R-A2). The message carries its `fix:`. */
172
+ export declare class UsageError extends Error {
173
+ readonly code = "USAGE";
174
+ constructor(message: string);
175
+ }
176
+ /** A path that stays inside the project: relative, `/` separators, no `..`. `./` and a trailing `/` are allowed. */
177
+ export declare const relativePath: (path: string) => string | undefined;
178
+ /** Check a config value read from `file`; every problem is reported, each with its fix. */
179
+ export declare const validateConfig: (value: unknown, file: string) => Config;
180
+ /** The first config file in `cwd`, in the order {@link CONFIG_FILES} lists them. */
181
+ export declare const findConfig: (cwd: string) => string | undefined;
182
+ /**
183
+ * The config for a run: the file `--config` names (relative to `cwd`), or the first one found in
184
+ * `cwd`. `undefined` when none is named and none is found; the caller decides whether that is an
185
+ * error.
186
+ */
187
+ export declare const loadConfig: (cwd: string, explicit?: string) => Promise<Config | undefined>;
188
+ /**
189
+ * `diff.decisions` from the text of an `contractdiff.config.json`, and nothing else in it: `diff`
190
+ * reads this from the base ref too (R12), where the rest of the file may be a version this build
191
+ * does not know. `undefined` when the file does not set it.
192
+ */
193
+ export declare const decisionSettingOf: (text: string, file: string) => DecisionSetting | undefined;