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,256 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ export const CONFIG_FILES = ['contractdiff.config.json', 'contractdiff.config.mjs', 'contractdiff.config.ts'];
5
+ export const DECISION_SETTINGS = ['warn', 'error', 'off'];
6
+ export const configSchema = {
7
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
8
+ title: 'contractdiff.config.json',
9
+ type: 'object',
10
+ additionalProperties: false,
11
+ properties: {
12
+ $schema: { type: 'string' },
13
+ input: { type: 'string', minLength: 1, description: 'The spec, relative to this file: JSON or YAML' },
14
+ overlays: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'OpenAPI Overlays applied to the input, in order' },
15
+ plugins: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Package names or relative paths; nothing else is loaded' },
16
+ targets: {
17
+ type: 'object',
18
+ additionalProperties: {
19
+ type: 'object',
20
+ additionalProperties: false,
21
+ required: ['generator', 'out'],
22
+ properties: { generator: { type: 'string', minLength: 1 }, out: { type: 'string', minLength: 1 }, options: { type: 'object' } },
23
+ },
24
+ },
25
+ extract: {
26
+ type: 'object',
27
+ additionalProperties: false,
28
+ properties: { from: { type: 'string', minLength: 1 }, out: { type: 'string', minLength: 1 }, options: { type: 'object' } },
29
+ },
30
+ diff: {
31
+ type: 'object',
32
+ additionalProperties: false,
33
+ properties: {
34
+ decisions: { enum: DECISION_SETTINGS, 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' },
35
+ },
36
+ },
37
+ lint: {
38
+ type: 'object',
39
+ additionalProperties: false,
40
+ properties: {
41
+ extends: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Rulesets, in order: `recommended`, `agent-ready`' },
42
+ rules: { type: 'object', additionalProperties: { enum: ['error', 'warn', 'off'] }, description: 'A level per rule id, over the rulesets' },
43
+ warnFor: { type: 'string', pattern: '^\\d+d$', description: 'How long a rule new at error warns first, by the date it entered the ruleset: `"14d"` (the default); `"0d"` turns it off' },
44
+ since: { type: 'string', minLength: 1, 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' },
45
+ legacy: { type: 'array', items: { type: 'string', minLength: 1 }, description: 'Rule ids that still run on operations `since` leaves untouched; none by default' },
46
+ },
47
+ },
48
+ },
49
+ };
50
+ export class ConfigError extends Error {
51
+ code = 'CONFIG';
52
+ constructor(file, problems) {
53
+ super(`${file} cannot be used:\n${problems.map((problem) => ` - ${problem}`).join('\n')}`);
54
+ this.name = 'ConfigError';
55
+ }
56
+ }
57
+ export class UsageError extends Error {
58
+ code = 'USAGE';
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = 'UsageError';
62
+ }
63
+ }
64
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
65
+ const text = (value) => typeof value === 'string' && value !== '';
66
+ export const relativePath = (path) => {
67
+ const parts = path.split('/').filter((part) => part !== '.');
68
+ if (path.includes('\\') || path.includes(':') || path.startsWith('/') || parts.some((part) => part === '..'))
69
+ return undefined;
70
+ const kept = parts.filter((part) => part !== '');
71
+ return kept.length === 0 ? '.' : kept.join('/');
72
+ };
73
+ const strings = (value, key, problems) => {
74
+ if (value === undefined)
75
+ return [];
76
+ if (!(Array.isArray(value) && value.every((entry) => text(entry))))
77
+ problems.push(`\`${key}\` must be a list of non-empty strings. fix: write \`"${key}": ["…"]\``);
78
+ return value;
79
+ };
80
+ const options = (value, where, problems) => {
81
+ if (value === undefined)
82
+ return {};
83
+ if (isRecord(value))
84
+ return value;
85
+ problems.push(`\`${where}.options\` must be an object. fix: map each option name to its value`);
86
+ return {};
87
+ };
88
+ const target = (name, value, problems) => {
89
+ const where = `targets.${name}`;
90
+ if (!isRecord(value)) {
91
+ problems.push(`\`${where}\` must be an object. fix: write \`{ "generator": "…", "out": "…" }\``);
92
+ return undefined;
93
+ }
94
+ for (const key of Object.keys(value)) {
95
+ if (!['generator', 'out', 'options'].includes(key))
96
+ problems.push(`\`${where}.${key}\` is not a target setting. fix: remove it; a target takes generator, out and options`);
97
+ }
98
+ if (!text(value.generator))
99
+ problems.push(`\`${where}.generator\` is missing. fix: name the generator, e.g. \`"generator": "${name}"\``);
100
+ const out = text(value.out) ? relativePath(value.out) : undefined;
101
+ if (out === undefined)
102
+ problems.push(`\`${where}.out\` must be a folder inside the project. fix: write a relative path such as \`"out": "src/generated"\``);
103
+ return { generator: String(value.generator), out: String(out), options: options(value.options, where, problems) };
104
+ };
105
+ const extractOf = (value, problems) => {
106
+ if (value !== undefined && !isRecord(value))
107
+ problems.push('`extract` must be an object. fix: write `{ "from": "…", "out": "spec.json" }`');
108
+ if (!isRecord(value))
109
+ return { options: {} };
110
+ for (const key of Object.keys(value)) {
111
+ if (!['from', 'out', 'options'].includes(key))
112
+ problems.push(`\`extract.${key}\` is not an extract setting. fix: remove it; extract takes from, out and options`);
113
+ }
114
+ if (value.from !== undefined && !text(value.from))
115
+ problems.push('`extract.from` must be an extractor name. fix: write `"from": "…"`');
116
+ if (value.out !== undefined && !(text(value.out) && relativePath(value.out) !== undefined))
117
+ problems.push('`extract.out` must be a file inside the project. fix: write `"out": "spec.json"`');
118
+ return {
119
+ ...(value.from === undefined ? {} : { from: value.from }),
120
+ ...(value.out === undefined ? {} : { out: value.out }),
121
+ options: options(value.options, 'extract', problems),
122
+ };
123
+ };
124
+ const decisionsOf = (value, problems) => {
125
+ if (value === undefined)
126
+ return undefined;
127
+ if (DECISION_SETTINGS.includes(value))
128
+ return value;
129
+ problems.push(`\`diff.decisions\` must be one of ${DECISION_SETTINGS.join(', ')}. fix: write \`"decisions": "warn"\``);
130
+ return undefined;
131
+ };
132
+ const diffOf = (value, problems) => {
133
+ if (value === undefined)
134
+ return undefined;
135
+ if (!isRecord(value)) {
136
+ problems.push('`diff` must be an object. fix: write `{ "decisions": "warn" }`');
137
+ return undefined;
138
+ }
139
+ for (const key of Object.keys(value)) {
140
+ if (key !== 'decisions')
141
+ problems.push(`\`diff.${key}\` is not a diff setting. fix: remove it; diff takes decisions`);
142
+ }
143
+ const decisions = decisionsOf(value.decisions, problems);
144
+ return decisions === undefined ? {} : { decisions };
145
+ };
146
+ const LINT_LEVELS = ['error', 'warn', 'off'];
147
+ const historyProblems = (warnFor, since) => [
148
+ ...(warnFor === undefined || (typeof warnFor === 'string' && /^\d+d$/u.test(warnFor)) ? [] : ['`lint.warnFor` must be a number of days. fix: write `"warnFor": "14d"`, or `"0d"` to turn warn-first off']),
149
+ ...(since === undefined || text(since) ? [] : ['`lint.since` must be a git ref. fix: write `"since": "merge-base"`, or a tag such as `"v1.0.0"`']),
150
+ ];
151
+ const lintOf = (value, problems) => {
152
+ if (value === undefined)
153
+ return undefined;
154
+ if (!isRecord(value)) {
155
+ problems.push('`lint` must be an object. fix: write `{ "extends": ["recommended"], "rules": { … } }`');
156
+ return undefined;
157
+ }
158
+ for (const key of Object.keys(value)) {
159
+ if (!['extends', 'rules', 'warnFor', 'since', 'legacy'].includes(key))
160
+ problems.push(`\`lint.${key}\` is not a lint setting. fix: remove it; lint takes extends, rules, warnFor, since and legacy`);
161
+ }
162
+ const rules = value.rules;
163
+ if (rules !== undefined && !(isRecord(rules) && Object.values(rules).every((level) => LINT_LEVELS.includes(level)))) {
164
+ problems.push('`lint.rules` must map rule ids to "error", "warn" or "off". fix: write `"rules": { "operation-tags": "error" }`');
165
+ }
166
+ const { warnFor, since } = value;
167
+ problems.push(...historyProblems(warnFor, since));
168
+ return {
169
+ ...(value.extends === undefined ? {} : { extends: strings(value.extends, 'lint.extends', problems) }),
170
+ ...(rules === undefined ? {} : { rules: rules }),
171
+ ...(warnFor === undefined ? {} : { warnFor: warnFor }),
172
+ ...(since === undefined ? {} : { since: since }),
173
+ ...(value.legacy === undefined ? {} : { legacy: strings(value.legacy, 'lint.legacy', problems) }),
174
+ };
175
+ };
176
+ const targetsOf = (value, problems) => {
177
+ if (value !== undefined && !isRecord(value))
178
+ problems.push('`targets` must be an object. fix: map a target name to `{ "generator": "…", "out": "…" }`');
179
+ if (!isRecord(value))
180
+ return {};
181
+ const targets = {};
182
+ for (const [name, entry] of Object.entries(value)) {
183
+ const checked = target(name, entry, problems);
184
+ if (checked !== undefined)
185
+ targets[name] = checked;
186
+ }
187
+ return targets;
188
+ };
189
+ const KEYS = new Set(Object.keys(configSchema.properties));
190
+ export const validateConfig = (value, file) => {
191
+ if (!isRecord(value))
192
+ throw new ConfigError(file, ['the config is not an object. fix: write `{ "input": "openapi.yaml", "targets": { … } }`']);
193
+ const problems = [];
194
+ for (const key of Object.keys(value)) {
195
+ if (!KEYS.has(key))
196
+ problems.push(`\`${key}\` is not a setting. fix: remove it; the settings are ${[...KEYS].join(', ')}`);
197
+ }
198
+ if (value.input !== undefined && !(text(value.input) && relativePath(value.input) !== undefined)) {
199
+ problems.push('`input` must be a file inside the project. fix: write `"input": "openapi.yaml"`');
200
+ }
201
+ const config = {
202
+ root: dirname(file),
203
+ file,
204
+ ...(value.input === undefined ? {} : { input: value.input }),
205
+ overlays: strings(value.overlays, 'overlays', problems),
206
+ plugins: strings(value.plugins, 'plugins', problems),
207
+ targets: targetsOf(value.targets, problems),
208
+ extract: extractOf(value.extract, problems),
209
+ };
210
+ const diff = diffOf(value.diff, problems);
211
+ const lint = lintOf(value.lint, problems);
212
+ if (problems.length > 0)
213
+ throw new ConfigError(file, problems);
214
+ return { ...config, ...(diff === undefined ? {} : { diff }), ...(lint === undefined ? {} : { lint }) };
215
+ };
216
+ export const findConfig = (cwd) => CONFIG_FILES.map((name) => resolve(cwd, name)).find((file) => existsSync(file));
217
+ const read = async (file) => {
218
+ if (file.endsWith('.json')) {
219
+ try {
220
+ return JSON.parse(String(readFileSync(file)));
221
+ }
222
+ catch (error) {
223
+ throw new ConfigError(file, [`it is not JSON (${error.message}). fix: correct the JSON, or validate it against \`configSchema\``]);
224
+ }
225
+ }
226
+ try {
227
+ const module = (await import(pathToFileURL(file).href));
228
+ return module.default;
229
+ }
230
+ catch (error) {
231
+ throw new ConfigError(file, [`it failed to load (${error.message}). fix: make it a module whose default export is the config object`]);
232
+ }
233
+ };
234
+ export const loadConfig = async (cwd, explicit) => {
235
+ const file = explicit === undefined ? findConfig(cwd) : resolve(cwd, explicit);
236
+ if (file === undefined)
237
+ return undefined;
238
+ if (!existsSync(file))
239
+ throw new ConfigError(file, ['it does not exist. fix: pass `--config` a file that exists, or create `contractdiff.config.json`']);
240
+ return validateConfig(await read(file), file);
241
+ };
242
+ export const decisionSettingOf = (text, file) => {
243
+ let value;
244
+ try {
245
+ value = JSON.parse(text);
246
+ }
247
+ catch (error) {
248
+ throw new ConfigError(file, [`it is not JSON (${error.message}). fix: correct the JSON, or validate it against \`configSchema\``]);
249
+ }
250
+ const section = isRecord(value) && isRecord(value.diff) ? value.diff : {};
251
+ const problems = [];
252
+ const setting = decisionsOf(section.decisions, problems);
253
+ if (problems.length > 0)
254
+ throw new ConfigError(file, problems);
255
+ return setting;
256
+ };
@@ -0,0 +1,24 @@
1
+ const linesOf = (text) => text.split('\n');
2
+ export const unifiedDiff = (path, before, after) => {
3
+ if (before === after)
4
+ return '';
5
+ const old = linesOf(before ?? '');
6
+ const now = linesOf(after ?? '');
7
+ let head = 0;
8
+ while (old[head] === now[head])
9
+ head += 1;
10
+ let tail = 0;
11
+ while (tail < old.length - head && tail < now.length - head && old.at(-1 - tail) === now.at(-1 - tail))
12
+ tail += 1;
13
+ const removed = old.slice(head, old.length - tail);
14
+ const added = now.slice(head, now.length - tail);
15
+ const range = (count) => `${String(count === 0 ? head : head + 1)},${String(count)}`;
16
+ return [
17
+ `--- ${before === undefined ? '/dev/null' : `a/${path}`}`,
18
+ `+++ ${after === undefined ? '/dev/null' : `b/${path}`}`,
19
+ `@@ -${range(removed.length)} +${range(added.length)} @@`,
20
+ ...removed.map((line) => `-${line}`),
21
+ ...added.map((line) => `+${line}`),
22
+ '',
23
+ ].join('\n');
24
+ };
@@ -0,0 +1,13 @@
1
+ import { type Report } from './run-commit.js';
2
+ export interface ExtractOptions {
3
+ readonly cwd: string;
4
+ readonly config?: string | undefined;
5
+ /** The extractor's name; the config's `extract.from` when absent. */
6
+ readonly from?: string | undefined;
7
+ /** The spec file to write; the config's `extract.out`, else `spec.json`. */
8
+ readonly out?: string | undefined;
9
+ readonly check?: boolean | undefined;
10
+ readonly dryRun?: boolean | undefined;
11
+ readonly force?: boolean | undefined;
12
+ }
13
+ export declare const extract: (options: ExtractOptions) => Promise<Report>;
@@ -0,0 +1,21 @@
1
+ import { join } from 'node:path';
2
+ import { documentOf } from './host.js';
3
+ import { commit } from './run-commit.js';
4
+ import { loadConfig, relativePath, UsageError, validateConfig } from './run-config.js';
5
+ import { loadPlugins } from './run-load.js';
6
+ export const extract = async (options) => {
7
+ const config = (await loadConfig(options.cwd, options.config)) ??
8
+ { ...validateConfig({}, join(options.cwd, 'contractdiff.config.json')), root: options.cwd };
9
+ const from = options.from ?? config.extract.from;
10
+ if (from === undefined)
11
+ throw new UsageError('extract needs an extractor. fix: pass --from <extractor>, or set `"extract": { "from": "…" }` in the config');
12
+ const out = relativePath(options.out ?? config.extract.out ?? 'spec.json');
13
+ if (out === undefined || !out.endsWith('.json'))
14
+ throw new UsageError('--out must be a .json file inside the project. fix: pass --out spec.json');
15
+ const host = await loadPlugins(config);
16
+ const { document, findings } = documentOf(await host.extractor(from).run(config.extract.options));
17
+ const content = JSON.stringify(document, undefined, 2);
18
+ if (content === undefined)
19
+ throw new Error(`the extractor "${from}" returned no document. fix: return the spec object from \`run(options)\``);
20
+ return commit({ root: config.root, command: 'contractdiff extract', produced: [{ target: 'extract', files: [{ path: out, content: `${content}\n`, owner: 'generated' }] }], findings: findings.map((finding) => ({ ...finding, target: 'extract' })), check: options.check, dryRun: options.dryRun, force: options.force });
21
+ };
@@ -0,0 +1,15 @@
1
+ import { type Report } from './run-commit.js';
2
+ import { type Config } from './run-config.js';
3
+ export interface GenOptions {
4
+ /** Where a config is looked for, and what `--config` is relative to. */
5
+ readonly cwd: string;
6
+ readonly config?: string | undefined;
7
+ /** Run only these targets; every target when absent or empty. */
8
+ readonly targets?: readonly string[] | undefined;
9
+ readonly check?: boolean | undefined;
10
+ readonly dryRun?: boolean | undefined;
11
+ readonly force?: boolean | undefined;
12
+ }
13
+ /** The config, or a refusal when there is none. */
14
+ export declare const requireConfig: (cwd: string, explicit: string | undefined) => Promise<Config>;
15
+ export declare const gen: (options: GenOptions) => Promise<Report>;
@@ -0,0 +1,43 @@
1
+ import { join } from 'node:path';
2
+ import { commit, under } from './run-commit.js';
3
+ import { ConfigError, loadConfig, UsageError } from './run-config.js';
4
+ import { readInput } from './run-input.js';
5
+ import { loadPlugins } from './run-load.js';
6
+ export const requireConfig = async (cwd, explicit) => {
7
+ const config = await loadConfig(cwd, explicit);
8
+ if (config === undefined) {
9
+ throw new ConfigError(join(cwd, 'contractdiff.config.json'), ['no config was found. fix: create contractdiff.config.json with `input` and `targets`, or pass `--config`']);
10
+ }
11
+ return config;
12
+ };
13
+ const chosen = (config, wanted) => {
14
+ const names = Object.keys(config.targets);
15
+ if (names.length === 0)
16
+ throw new ConfigError(config.file, ['it has no `targets`. fix: add `"targets": { "types": { "generator": "types", "out": "src/generated" } }`']);
17
+ if (wanted === undefined || wanted.length === 0)
18
+ return names;
19
+ const unknown = wanted.find((name) => !names.includes(name));
20
+ if (unknown !== undefined)
21
+ throw new UsageError(`no target is named "${unknown}". fix: pass --target with one of: ${names.join(', ')}`);
22
+ return names.filter((name) => wanted.includes(name));
23
+ };
24
+ export const gen = async (options) => {
25
+ const config = await requireConfig(options.cwd, options.config);
26
+ const { input } = config;
27
+ if (input === undefined)
28
+ throw new ConfigError(config.file, ['it has no `input`. fix: add `"input": "openapi.yaml"`, the spec to generate from']);
29
+ const names = chosen(config, options.targets);
30
+ const host = await loadPlugins(config);
31
+ const document = readInput({ root: config.root, file: config.file, input, overlays: config.overlays });
32
+ const results = await Promise.all(names.map(async (name) => {
33
+ const target = config.targets[name];
34
+ const result = await host.run(target.generator, document, target.options);
35
+ return {
36
+ produced: { target: name, files: result.files.map((file) => ({ ...file, path: under(target.out, file.path) })) },
37
+ findings: result.findings.map((finding) => ({ ...finding, target: name })),
38
+ };
39
+ }));
40
+ const produced = results.map((result) => result.produced);
41
+ const findings = results.flatMap((result) => result.findings);
42
+ return commit({ root: config.root, command: 'contractdiff gen', produced, findings, check: options.check, dryRun: options.dryRun, force: options.force });
43
+ };
@@ -0,0 +1,37 @@
1
+ import { createHash } from 'node:crypto';
2
+ const DIGITS = 12;
3
+ export const digest = (body) => createHash('sha256').update(body).digest('hex').slice(0, DIGITS);
4
+ const SLASHES = ['// ', ''];
5
+ const HASH = ['# ', ''];
6
+ const MARKUP = ['<!-- ', ' -->'];
7
+ const COMMENTS = new Map([
8
+ ['ts', SLASHES],
9
+ ['tsx', SLASHES],
10
+ ['mts', SLASHES],
11
+ ['cts', SLASHES],
12
+ ['js', SLASHES],
13
+ ['jsx', SLASHES],
14
+ ['mjs', SLASHES],
15
+ ['cjs', SLASHES],
16
+ ['yaml', HASH],
17
+ ['yml', HASH],
18
+ ['md', MARKUP],
19
+ ]);
20
+ const extension = (path) => path.slice(path.lastIndexOf('.') + 1);
21
+ export const headerLine = (path, body, command) => {
22
+ const comment = COMMENTS.get(extension(path));
23
+ if (comment === undefined)
24
+ return undefined;
25
+ return `${comment[0]}generated by contractdiff — do not edit; run \`${command}\` (sha256:${digest(body)})${comment[1]}`;
26
+ };
27
+ export const withHeader = (path, body, command) => {
28
+ const line = headerLine(path, body, command);
29
+ return line === undefined ? body : `${line}\n${body}`;
30
+ };
31
+ const HEADER = /^(?:\/\/|#|<!--) generated by contractdiff — do not edit; run `[^`\n]+` \(sha256:([\da-f]{12})\)(?: -->)?\n/u;
32
+ export const readHeader = (content) => {
33
+ const match = HEADER.exec(content);
34
+ if (match === null)
35
+ return undefined;
36
+ return { hash: match[1], body: content.slice(match[0].length) };
37
+ };
@@ -0,0 +1,31 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { parse as parseYaml } from 'seniority/yaml';
4
+ import { bundle } from './gen-ts-bundle.js';
5
+ import { applyOverlays } from './input-overlay.js';
6
+ import { ConfigError } from './run-config.js';
7
+ const NON_PRINTABLE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F]/gu;
8
+ const parseYamlLeniently = (text) => {
9
+ try {
10
+ return parseYaml(text);
11
+ }
12
+ catch {
13
+ return parseYaml(text.replaceAll(NON_PRINTABLE, '\uFFFD'));
14
+ }
15
+ };
16
+ export const readDocument = (path, file) => {
17
+ if (!existsSync(path))
18
+ throw new ConfigError(file, [`${path} does not exist. fix: point \`input\` at the spec, relative to the config`]);
19
+ const text = readFileSync(path, 'utf8');
20
+ try {
21
+ return path.endsWith('.json') ? JSON.parse(text) : parseYamlLeniently(text);
22
+ }
23
+ catch (error) {
24
+ throw new ConfigError(file, [`${path} is not JSON or YAML (${error.message}). fix: correct the file, or point \`input\` at another`]);
25
+ }
26
+ };
27
+ export const readInput = ({ root, file, input, overlays }, apply = applyOverlays) => {
28
+ const path = resolve(root, input);
29
+ const document = readDocument(path, file);
30
+ return bundle(overlays.length === 0 ? document : apply(document, overlays.map((overlay) => readDocument(resolve(root, overlay), file))), path);
31
+ };
@@ -0,0 +1,32 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { createHost } from './host.js';
5
+ import { builtinAdapters } from './inputs.js';
6
+ import { builtins } from './plugins.js';
7
+ import { ConfigError } from './run-config.js';
8
+ export const locate = (entry, root) => entry.startsWith('.') || entry.startsWith('/') ? pathToFileURL(resolve(root, entry)).href : pathToFileURL(createRequire(join(root, 'package.json')).resolve(entry)).href;
9
+ const pluginOf = (module) => module.default ?? module.plugin;
10
+ export const loadPlugins = async ({ root, file, plugins }) => {
11
+ const host = createHost();
12
+ for (const plugin of [{ name: 'contractdiff', adapters: builtinAdapters }, ...builtins])
13
+ host.register(plugin);
14
+ const modules = await Promise.all(plugins.map(async (entry) => {
15
+ try {
16
+ return (await import(locate(entry, root)));
17
+ }
18
+ catch (error) {
19
+ throw new ConfigError(file, [`the plugin "${entry}" did not load (${error.message}). fix: install it (\`npm i -D ${entry}\`) or correct its path in \`plugins\``]);
20
+ }
21
+ }));
22
+ for (const [index, entry] of plugins.entries()) {
23
+ const module = modules[index];
24
+ try {
25
+ host.register(pluginOf(module));
26
+ }
27
+ catch (error) {
28
+ throw new ConfigError(file, [`"${entry}" is not a plugin contractdiff can use: ${error.message}`]);
29
+ }
30
+ }
31
+ return host;
32
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * `contractdiff.map.json` (apicontract-gen-command R7, spec.md R-BL1): for each operation, the files
3
+ * and symbols generated for it. `check`, `diff` and the contract-test plugins read it.
4
+ */
5
+ import { type GeneratedFile } from './host.js';
6
+ export declare const MAP_FILE = "contractdiff.map.json";
7
+ export interface MapEntry {
8
+ readonly file: string;
9
+ readonly symbol: string;
10
+ readonly target: string;
11
+ /**
12
+ * `user` for the symbol the user owns that implements the operation (R-BL1): a method of the
13
+ * controller class or a member of the handlers object a target wrote once. Absent for a generated one.
14
+ */
15
+ readonly owner?: 'user';
16
+ }
17
+ export interface MapFile {
18
+ readonly target: string;
19
+ /** sha256 of the body, 12 hex digits. */
20
+ readonly sha: string;
21
+ }
22
+ export interface ContractMap {
23
+ readonly version: 1;
24
+ readonly operations: Readonly<Record<string, readonly MapEntry[]>>;
25
+ readonly files: Readonly<Record<string, MapFile>>;
26
+ }
27
+ /** What one target produced this run, its paths relative to the project root. */
28
+ export interface Produced {
29
+ readonly target: string;
30
+ readonly files: readonly GeneratedFile[];
31
+ }
32
+ export declare const emptyMap: () => ContractMap;
33
+ /** Read the map a previous run wrote; no file is an empty map. */
34
+ export declare const parseMap: (text: string | undefined) => ContractMap;
35
+ /** The body hashes the map recorded for files of the given targets, by path. */
36
+ export declare const recordedFor: (map: ContractMap, targets: readonly string[]) => Map<string, string>;
37
+ export declare const updateMap: (previous: ContractMap, produced: readonly Produced[]) => ContractMap;
38
+ /** The symbols the user owns that implement an operation: what a rule on code reads (apicontract-lint R14). */
39
+ export declare const handlersOf: (map: ContractMap, operation: string) => MapEntry[];
40
+ /** The bytes the map is written as. */
41
+ export declare const serializeMap: (map: ContractMap) => string;
@@ -0,0 +1,52 @@
1
+ import { ConfigError } from './run-config.js';
2
+ import { digest } from './run-header.js';
3
+ export const MAP_FILE = 'contractdiff.map.json';
4
+ export const emptyMap = () => ({ version: 1, operations: {}, files: {} });
5
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
6
+ const unreadable = (why) => {
7
+ throw new ConfigError(MAP_FILE, [`it ${why}. fix: delete ${MAP_FILE} and run \`contractdiff gen\` again; it is regenerated, never edited`]);
8
+ };
9
+ const isMap = (value) => isRecord(value) && value.version === 1 && isRecord(value.operations) && isRecord(value.files);
10
+ export const parseMap = (text) => {
11
+ if (text === undefined)
12
+ return emptyMap();
13
+ let value;
14
+ try {
15
+ value = JSON.parse(text);
16
+ }
17
+ catch {
18
+ return unreadable('is not JSON');
19
+ }
20
+ return isMap(value) ? value : unreadable('is not a version 1 contract map');
21
+ };
22
+ export const recordedFor = (map, targets) => new Map(Object.entries(map.files).filter(([, entry]) => targets.includes(entry.target)).map(([path, entry]) => [path, entry.sha]));
23
+ const sorted = (entries) => {
24
+ const all = new Map(entries);
25
+ return Object.fromEntries([...all.keys()].toSorted().map((key) => [key, all.get(key)]));
26
+ };
27
+ const byTargetFileSymbol = (a, b) => `${a.target}\0${a.file}\0${a.symbol}`.localeCompare(`${b.target}\0${b.file}\0${b.symbol}`, 'en');
28
+ export const updateMap = (previous, produced) => {
29
+ const ran = new Set(produced.map((entry) => entry.target));
30
+ const operations = new Map();
31
+ const add = (id, entries) => {
32
+ operations.set(id, [...(operations.get(id) ?? []), ...entries]);
33
+ };
34
+ for (const [id, entries] of Object.entries(previous.operations))
35
+ add(id, entries.filter((entry) => !ran.has(entry.target)));
36
+ const files = new Map(Object.entries(previous.files).filter(([, entry]) => !ran.has(entry.target)));
37
+ for (const { target, files: written } of produced) {
38
+ for (const file of written) {
39
+ if (file.owner === 'generated')
40
+ files.set(file.path, { target, sha: digest(file.content) });
41
+ const owned = file.owner === 'user' ? { owner: 'user' } : {};
42
+ for (const { operation, symbol } of file.symbols ?? [])
43
+ add(operation, [{ file: file.path, symbol, target, ...owned }]);
44
+ }
45
+ }
46
+ const kept = [...operations].filter(([, entries]) => entries.length > 0).map(([id, entries]) => [id, entries.toSorted(byTargetFileSymbol)]);
47
+ return { version: 1, operations: sorted(kept), files: sorted(files) };
48
+ };
49
+ export const handlersOf = (map, operation) => Object.entries(map.operations)
50
+ .filter(([id]) => id === operation)
51
+ .flatMap(([, entries]) => entries.filter((entry) => entry.owner === 'user'));
52
+ export const serializeMap = (map) => `${JSON.stringify(map, undefined, 2)}\n`;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * What a run would do to each file (apicontract-gen-command R4), decided without touching the
3
+ * disk: the caller reads what is there and writes what this returns. Pure, so every rule of
4
+ * regeneration safety is tested here and nowhere else.
5
+ */
6
+ import { type GeneratedFile, type Owner } from './host.js';
7
+ export type Action = 'write' | 'skip' | 'unchanged' | 'conflict' | 'delete';
8
+ export interface Planned {
9
+ /** Relative to the project root, with `/` separators. */
10
+ readonly path: string;
11
+ readonly owner: Owner;
12
+ readonly action: Action;
13
+ /** What is on disk now, if anything. */
14
+ readonly before: string | undefined;
15
+ /** What a write leaves on disk: the header and the body. `undefined` for a delete. */
16
+ readonly after: string | undefined;
17
+ }
18
+ export interface PlanOptions {
19
+ /** The command the header names. */
20
+ readonly command: string;
21
+ /** The body hashes the previous map recorded for the targets this run writes, by path. */
22
+ readonly recorded?: ReadonlyMap<string, string>;
23
+ /** Overwrite (or delete) a generated file that was edited by hand. */
24
+ readonly force?: boolean | undefined;
25
+ }
26
+ /** What is on disk at each path that has a file: its contents. */
27
+ export type Disk = ReadonlyMap<string, string>;
28
+ /** Every path this run touches or refuses, sorted by path. Paths that need nothing done are listed as `unchanged` or `skip`. */
29
+ export declare const plan: (files: readonly GeneratedFile[], disk: Disk, options: PlanOptions) => Planned[];
30
+ /** The entries that change the disk. */
31
+ export declare const changes: (planned: readonly Planned[]) => Planned[];
@@ -0,0 +1,35 @@
1
+ import { digest, readHeader, withHeader } from './run-header.js';
2
+ const intact = (path, content, recorded) => {
3
+ const header = readHeader(content);
4
+ return header === undefined ? recorded.get(path) === digest(content) : header.hash === digest(header.body);
5
+ };
6
+ const generated = (file, disk, options, recorded) => {
7
+ const before = disk.get(file.path);
8
+ const after = withHeader(file.path, file.content, options.command);
9
+ const entry = { path: file.path, owner: file.owner, before, after };
10
+ if (before === undefined)
11
+ return { ...entry, action: 'write' };
12
+ if (before === after)
13
+ return { ...entry, action: 'unchanged' };
14
+ return { ...entry, action: options.force === true || intact(file.path, before, recorded) ? 'write' : 'conflict' };
15
+ };
16
+ export const plan = (files, disk, options) => {
17
+ const recorded = options.recorded ?? new Map();
18
+ const planned = files.map((file) => {
19
+ if (file.owner === 'generated')
20
+ return generated(file, disk, options, recorded);
21
+ const before = disk.get(file.path);
22
+ return { path: file.path, owner: 'user', action: before === undefined ? 'write' : 'skip', before, after: before ?? file.content };
23
+ });
24
+ const produced = new Set(files.map((file) => file.path));
25
+ for (const path of recorded.keys()) {
26
+ const before = disk.get(path);
27
+ if (produced.has(path) || before === undefined)
28
+ continue;
29
+ const action = options.force === true || intact(path, before, recorded) ? 'delete' : 'conflict';
30
+ planned.push({ path, owner: 'generated', action, before, after: undefined });
31
+ }
32
+ const byPath = new Map(planned.map((entry) => [entry.path, entry]));
33
+ return [...byPath.keys()].toSorted().map((path) => byPath.get(path));
34
+ };
35
+ export const changes = (planned) => planned.filter((entry) => entry.action === 'write' || entry.action === 'delete');