specshield 3.4.15 → 3.4.16
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.
- package/CHANGELOG.md +29 -0
- package/README.md +83 -1
- package/package.json +3 -2
- package/src/cli.js +2 -0
- package/src/commands/fix.js +173 -0
- package/src/core/classifyChanges.js +1 -1
- package/src/core/fix/fixSpec.js +179 -0
- package/src/core/fix/locate.js +263 -0
- package/src/core/fix/ops.js +233 -0
- package/src/core/fix/shim/spring.js +532 -0
- package/src/core/fix/shim/transforms.js +231 -0
- package/src/core/fix/strategies.js +578 -0
- package/src/core/outputFormatter.js +1 -0
- package/src/core/usage/deprecations.js +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# SpecShield CLI changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased — break → fix: `specshield fix`
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **`specshield fix <base> <target>`** writes the non-breaking version of a breaking
|
|
8
|
+
change as minimal edits to the target spec (comments and layout kept): renamed fields
|
|
9
|
+
keep both names, removed things come back `deprecated` (`--sunset`), newly required
|
|
10
|
+
input becomes optional, type changes keep the old type, removed enum values return.
|
|
11
|
+
Every fix is verified by re-running the diff engine; one that leaves its break or adds
|
|
12
|
+
another is not applied. `--out`, `--write`, `--dry-run`, `--json`.
|
|
13
|
+
- **`--spring <dir> --package <pkg>`** generates a Spring Boot 3 version layer
|
|
14
|
+
(`ResponseBodyAdvice`/`RequestBodyAdvice`): old clients get the old JSON shape (renames,
|
|
15
|
+
scalar conversions, enum mappings, request defaults, list envelopes), each rewrite
|
|
16
|
+
checked on sample payloads against the old schema first. Compiled and tested in a Spring
|
|
17
|
+
Boot 3.2 and 3.5 app (`test-harness/spring-compat/verify.sh`).
|
|
18
|
+
- `compare` points at `specshield fix` when it finds breaking changes.
|
|
19
|
+
- `specshield deprecations` also honours `x-deprecated: true` (Swagger 2.0 schemas).
|
|
20
|
+
|
|
21
|
+
### Tested on real data
|
|
22
|
+
|
|
23
|
+
- Kubernetes `swagger.json` v1.37.1 → master: 552 breaking changes, all fixed and verified
|
|
24
|
+
(7 s); an independent `compare` of v1.37.1 against the fixed spec reports 0.
|
|
25
|
+
- GitHub's REST API description, April → October 2026 (13 MB): 429 breaking changes, all
|
|
26
|
+
fixed and verified (22 s), independently re-checked. This run removed two kinds of
|
|
27
|
+
guesses: "renames" between unrelated fields that happened to be the only ones of a type
|
|
28
|
+
(`budget_type` → `expires_at`; now a rename needs a shared word), and enum "renames"
|
|
29
|
+
between single-value constants of `oneOf` variants that moved. A format-only change
|
|
30
|
+
(`integer` → `int64`) no longer suggests a new field.
|
|
31
|
+
|
|
3
32
|
## Unreleased — safe removal: deprecate → watch traffic drain → remove
|
|
4
33
|
|
|
5
34
|
### Added
|
package/README.md
CHANGED
|
@@ -42,7 +42,7 @@ What the CLI does:
|
|
|
42
42
|
- [vs. Alternatives](#vs-alternatives) · [Pricing](#pricing)
|
|
43
43
|
|
|
44
44
|
**Commands — local & hosted compare**
|
|
45
|
-
- [Local Compare](#local-compare) · [**Who does a change break? (usage-aware compare)**](#who-does-a-change-break--usage-aware-compare) · [**Safe removal: deprecate → drain → remove**](#safe-removal-deprecate--watch-traffic-drain--remove) · [Remote Compare](#remote-compare) · [Comparison History](#comparison-history) · [Share a Comparison](#share-a-comparison) · [GitHub App PR Checks](#github-app--pr-checks)
|
|
45
|
+
- [Local Compare](#local-compare) · [**Who does a change break? (usage-aware compare)**](#who-does-a-change-break--usage-aware-compare) · [**Safe removal: deprecate → drain → remove**](#safe-removal-deprecate--watch-traffic-drain--remove) · [**Break → fix: `specshield fix`**](#break--fix-generate-the-non-breaking-version) · [Remote Compare](#remote-compare) · [Comparison History](#comparison-history) · [Share a Comparison](#share-a-comparison) · [GitHub App PR Checks](#github-app--pr-checks)
|
|
46
46
|
|
|
47
47
|
**Governance — lint & gate**
|
|
48
48
|
- [`specshield govern`](#governance--lint-a-spec-and-gate-the-pr)
|
|
@@ -434,6 +434,88 @@ and emails whoever uploaded. Only the report is sent — counts per client, neve
|
|
|
434
434
|
specshield deprecations api/openapi.yaml --usage usage.json --upload --org acme --api payments
|
|
435
435
|
```
|
|
436
436
|
|
|
437
|
+
## Break → fix: generate the non-breaking version
|
|
438
|
+
|
|
439
|
+
A blocked PR with no way forward is why teams switch gates off. `specshield fix` takes
|
|
440
|
+
the change that broke the gate and writes the **non-breaking version** of it — the
|
|
441
|
+
expand-and-contract edit you'd make by hand if you had the time.
|
|
442
|
+
|
|
443
|
+
```bash
|
|
444
|
+
specshield fix api/openapi.base.yaml api/openapi.yaml
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
```text
|
|
448
|
+
SpecShield™ Fix — Payments API 1.0.0 → 2.0.0
|
|
449
|
+
16 breaking changes · 14 fixed · 2 need a decision
|
|
450
|
+
Each fix was re-checked with the diff engine: it removes its breaking change and adds none.
|
|
451
|
+
|
|
452
|
+
✔ `status` was renamed to `paymentStatus`: return both, `status` deprecated
|
|
453
|
+
POST /payments, GET /payments/{id}
|
|
454
|
+
→ The server must return `status` with the same value as `paymentStatus`.
|
|
455
|
+
✔ Make `currency` optional (default "EUR")
|
|
456
|
+
→ Clients that don't send it get the default "EUR".
|
|
457
|
+
✔ Keep `amount` as integer; return the string value as `amountV2`
|
|
458
|
+
✔ Keep "ENABLED" as an allowed value of status (renamed to "ACTIVE")
|
|
459
|
+
✔ Keep GET /payments/{id}/receipt, marked deprecated
|
|
460
|
+
…
|
|
461
|
+
✖ NEEDS A DECISION (2)
|
|
462
|
+
● Type of "responses.200" changed from "array" to "object" in GET /payments
|
|
463
|
+
the list moved into `data` — one schema can't describe both shapes, so this needs a version layer (--spring)
|
|
464
|
+
|
|
465
|
+
✔ Wrote openapi.fixed.yaml (12 edits, comments and layout kept)
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
| The change | The fix |
|
|
469
|
+
|---|---|
|
|
470
|
+
| Field or parameter renamed | keep both names, the old one `deprecated` (a rename needs the same type **and** a shared word in the name) |
|
|
471
|
+
| Field, parameter, operation, response or schema removed | restore it, `deprecated` (`--sunset 2027-03-31` adds `x-sunset`) — then `specshield deprecations` tracks it draining |
|
|
472
|
+
| Request field or parameter became required | optional again; the report says the server must default it |
|
|
473
|
+
| Field type changed | request: keep the old type · response: keep the old type, new type as `<field>V2` |
|
|
474
|
+
| Format only (`integer` → `int64`) | keep the old format |
|
|
475
|
+
| Enum value removed | keep it (a value renamed while others stay is recognised) |
|
|
476
|
+
| Body changed shape (list → `{ data: [...] }`) | no spec can say both → `--spring` |
|
|
477
|
+
|
|
478
|
+
- **Nothing unverified is written.** Every fix is applied and the diff engine re-run; a fix
|
|
479
|
+
that leaves its breaking change or adds another is dropped and listed with the reason.
|
|
480
|
+
Fixes that depend on each other (restoring a field brings back an enum value it needs)
|
|
481
|
+
are applied in rounds, and the result may not contain any break the target didn't have.
|
|
482
|
+
- The fix is written to `<target>.fixed.yaml` (or `--out`, or `--write` in place) as
|
|
483
|
+
minimal edits: comments, ordering and quoting of every untouched line are kept, so
|
|
484
|
+
`git diff` shows only the fix. `--dry-run` writes nothing; `--json` for scripts.
|
|
485
|
+
- Exit code `0` when everything was fixed, `1` when something still needs a decision.
|
|
486
|
+
- Each fix tells you what the **server** must do for the spec to be true — return the old
|
|
487
|
+
field too, accept the old value, default a missing one.
|
|
488
|
+
|
|
489
|
+
### Spring Boot: old clients keep the old shape
|
|
490
|
+
|
|
491
|
+
Some changes can't be undone in the spec — a list wrapped in an envelope, a field that now
|
|
492
|
+
holds a string. `--spring` generates a Stripe-style **version layer** for a Spring Boot 3
|
|
493
|
+
service instead: the controllers speak only the new API; clients that don't send
|
|
494
|
+
`X-API-Version: 2.0.0` get the old JSON, and their old requests are upgraded on the way in.
|
|
495
|
+
|
|
496
|
+
```bash
|
|
497
|
+
specshield fix base.yaml target.yaml --spring src/main/java --package com.acme.payments.compat
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
- Generated: `ApiVersion_2_0_0.java` (this change's rewrites, as data) plus a small fixed
|
|
501
|
+
runtime — a `ResponseBodyAdvice` and a `RequestBodyAdvice` on Jackson. No changes to
|
|
502
|
+
your controllers.
|
|
503
|
+
- Rewrites: rename a field, convert a scalar's type (`"1250"` ↔ `1250`, only when the value
|
|
504
|
+
converts exactly), map an enum value, default a missing request field, unwrap a list from
|
|
505
|
+
its envelope — at any depth, inside arrays and maps.
|
|
506
|
+
- **Checked before it is generated**: for every operation, a sample payload of the new
|
|
507
|
+
shape is rewritten and validated against the *old* schema (and old requests against the
|
|
508
|
+
new one). A rewrite that can't produce the old shape is not generated — e.g. a required
|
|
509
|
+
field the new code no longer returns at all — and the report says why.
|
|
510
|
+
- Renames and enum mappings are inferred from the diff; they're marked
|
|
511
|
+
`/* inferred rename — check */` in the generated code.
|
|
512
|
+
- Clients with no version header are treated as on the old version, so existing
|
|
513
|
+
integrations keep working without a change. Set the header name with
|
|
514
|
+
`--version-header` or `specshield.compat.header`; a later `fix` run adds another
|
|
515
|
+
`ApiVersion_<v>` class and the layer chains them.
|
|
516
|
+
- Tested by compiling the generated code into a Spring Boot app and calling it as an old
|
|
517
|
+
and a new client (`test-harness/spring-compat/verify.sh`), on Spring Boot 3.2 and 3.5.
|
|
518
|
+
|
|
437
519
|
## Remote Compare
|
|
438
520
|
|
|
439
521
|
Sends your specs to SpecShield's hosted diff engine. Useful for keeping the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "specshield",
|
|
3
|
-
"version": "3.4.
|
|
3
|
+
"version": "3.4.16",
|
|
4
4
|
"description": "Contract compatibility testing for APIs — catch breaking OpenAPI changes before they reach your consumers, with can-i-deploy deploy gating and GitHub PR checks. (a.k.a. bidirectional contract testing.)",
|
|
5
5
|
"main": "src/cli.js",
|
|
6
6
|
"homepage": "https://specshield.io",
|
|
@@ -72,7 +72,8 @@
|
|
|
72
72
|
"fs-extra": "^11.2.0",
|
|
73
73
|
"js-yaml": "^4.1.0",
|
|
74
74
|
"ora": "^5.4.1",
|
|
75
|
-
"prompts": "^2.4.2"
|
|
75
|
+
"prompts": "^2.4.2",
|
|
76
|
+
"yaml": "^2.8.1"
|
|
76
77
|
},
|
|
77
78
|
"devDependencies": {
|
|
78
79
|
"jest": "^29.7.0"
|
package/src/cli.js
CHANGED
|
@@ -13,6 +13,7 @@ const shareCommand = require('./commands/share');
|
|
|
13
13
|
const whoamiCommand = require('./commands/whoami');
|
|
14
14
|
const usageCommand = require('./commands/usage');
|
|
15
15
|
const deprecationsCommand = require('./commands/deprecations');
|
|
16
|
+
const fixCommand = require('./commands/fix');
|
|
16
17
|
|
|
17
18
|
const program = new Command();
|
|
18
19
|
|
|
@@ -36,6 +37,7 @@ program.addCommand(shareCommand);
|
|
|
36
37
|
program.addCommand(whoamiCommand);
|
|
37
38
|
program.addCommand(usageCommand);
|
|
38
39
|
program.addCommand(deprecationsCommand);
|
|
40
|
+
program.addCommand(fixCommand);
|
|
39
41
|
|
|
40
42
|
program.parseAsync(process.argv).catch((err) => {
|
|
41
43
|
const logger = require('./utils/logger');
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
const chalk = require('chalk');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const fsExtra = require('fs-extra');
|
|
7
|
+
const { loadSpec } = require('../core/loadSpec');
|
|
8
|
+
const { parseSpec } = require('../core/parseSpec');
|
|
9
|
+
const { fixSpec } = require('../core/fix/fixSpec');
|
|
10
|
+
const { applyOpsToText } = require('../core/fix/ops');
|
|
11
|
+
const { buildShim } = require('../core/fix/shim/transforms');
|
|
12
|
+
const { generateSpring } = require('../core/fix/shim/spring');
|
|
13
|
+
const { plural } = require('../core/usage/format');
|
|
14
|
+
const logger = require('../utils/logger');
|
|
15
|
+
const exitAfterFlush = require('../utils/exitAfterFlush');
|
|
16
|
+
|
|
17
|
+
const fix = new Command('fix')
|
|
18
|
+
.description('Turn breaking changes into non-breaking ones: expand-and-contract edits to the new spec, each verified by the diff engine')
|
|
19
|
+
.argument('<base>', 'The spec your clients use today')
|
|
20
|
+
.argument('<target>', 'The new spec with breaking changes')
|
|
21
|
+
.option('--out <file>', 'Where to write the fixed spec (default: <target>.fixed.<ext>)')
|
|
22
|
+
.option('--write', 'Edit <target> in place instead of writing a new file')
|
|
23
|
+
.option('--dry-run', 'Only report; write nothing')
|
|
24
|
+
.option('--sunset <date>', 'Add x-sunset: <date> to everything restored as deprecated (YYYY-MM-DD)')
|
|
25
|
+
.option('--spring <dir>', 'Also generate a Spring Boot version layer (Java) into this directory')
|
|
26
|
+
.option('--package <name>', 'Java package for --spring', 'com.example.api.compat')
|
|
27
|
+
.option('--version-header <name>', 'Request header that carries the client\'s API version (--spring)', 'X-API-Version')
|
|
28
|
+
.option('--json', 'Output machine-readable JSON')
|
|
29
|
+
.action(async (basePath, targetPath, opts) => {
|
|
30
|
+
try {
|
|
31
|
+
if (opts.sunset && !/^\d{4}-\d{2}-\d{2}$/.test(opts.sunset)) throw new Error('--sunset must be a date like 2027-03-31');
|
|
32
|
+
if (opts.write && opts.out) throw new Error('Use either --write or --out, not both');
|
|
33
|
+
const targetText = await loadSpec(targetPath);
|
|
34
|
+
const baseDoc = parseSpec(await loadSpec(basePath), basePath);
|
|
35
|
+
const targetDoc = parseSpec(targetText, targetPath);
|
|
36
|
+
|
|
37
|
+
const result = fixSpec(baseDoc, targetDoc, { sunset: opts.sunset || null });
|
|
38
|
+
const verified = result.suggestions.filter((s) => s.status === 'verified');
|
|
39
|
+
|
|
40
|
+
let outFile = null;
|
|
41
|
+
if (!opts.dryRun && result.ops.length > 0) {
|
|
42
|
+
outFile = opts.write ? targetPath : (opts.out || defaultOut(targetPath));
|
|
43
|
+
const json = path.extname(targetPath).toLowerCase() === '.json' || /^\s*\{/.test(targetText);
|
|
44
|
+
await fsExtra.outputFile(outFile, applyOpsToText(targetText, result.ops, { json }));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let shim = null;
|
|
48
|
+
if (opts.spring) {
|
|
49
|
+
shim = buildShim(result, baseDoc, targetDoc);
|
|
50
|
+
if (!opts.dryRun && shim.transforms.length > 0) {
|
|
51
|
+
shim.files = await generateSpring(shim, {
|
|
52
|
+
dir: opts.spring, pkg: opts.package, header: opts.versionHeader,
|
|
53
|
+
version: String((targetDoc.info && targetDoc.info.version) || 'next'),
|
|
54
|
+
basePath: serverBasePath(targetDoc),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (opts.json) {
|
|
60
|
+
process.stdout.write(JSON.stringify({
|
|
61
|
+
before: result.before,
|
|
62
|
+
after: result.after,
|
|
63
|
+
output: outFile,
|
|
64
|
+
suggestions: result.suggestions.map(({ ops, ...s }) => ({ ...s, edits: ops.length })),
|
|
65
|
+
remaining: result.remaining,
|
|
66
|
+
...(shim ? { spring: { transforms: shim.transforms, skipped: shim.skipped, files: shim.files || [] } } : {}),
|
|
67
|
+
}, null, 2) + '\n');
|
|
68
|
+
} else {
|
|
69
|
+
process.stdout.write(render(result, { baseDoc, targetDoc, outFile, verified, shim, dryRun: opts.dryRun, targetPath }) + '\n');
|
|
70
|
+
}
|
|
71
|
+
exitAfterFlush(result.after > 0 ? 1 : 0);
|
|
72
|
+
} catch (err) {
|
|
73
|
+
logger.error(`Error: ${err.message}`);
|
|
74
|
+
process.exit(2);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
function defaultOut(target) {
|
|
79
|
+
const ext = path.extname(target);
|
|
80
|
+
return path.join(path.dirname(target), `${path.basename(target, ext)}.fixed${ext || '.yaml'}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function serverBasePath(doc) {
|
|
84
|
+
if (typeof doc.basePath === 'string') return doc.basePath.replace(/\/$/, '');
|
|
85
|
+
const url = doc.servers && doc.servers[0] && doc.servers[0].url;
|
|
86
|
+
if (!url) return '';
|
|
87
|
+
const p = url.replace(/^[a-z]+:\/\/[^/]+/i, '').replace(/\{[^}]+\}/g, '').replace(/\/$/, '');
|
|
88
|
+
return p.startsWith('/') ? p : '';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function render(r, { baseDoc, targetDoc, outFile, verified, shim, dryRun, targetPath }) {
|
|
92
|
+
const lines = [''];
|
|
93
|
+
const v = (d) => (d.info && d.info.version ? ` ${d.info.version}` : '');
|
|
94
|
+
lines.push(chalk.bold(` SpecShield™ Fix — ${(targetDoc.info && targetDoc.info.title) || 'API'}${v(baseDoc)} →${v(targetDoc)}`));
|
|
95
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
96
|
+
if (r.before === 0) {
|
|
97
|
+
lines.push(chalk.green(' ✔ No breaking changes — nothing to fix.'));
|
|
98
|
+
lines.push('');
|
|
99
|
+
return lines.join('\n');
|
|
100
|
+
}
|
|
101
|
+
const fixedCount = r.before - r.after;
|
|
102
|
+
lines.push(` ${plural(r.before, 'breaking change')} · ${chalk.green(`${fixedCount} fixed`)}` +
|
|
103
|
+
(r.after ? ` · ${chalk.red(`${r.after} need${r.after === 1 ? 's' : ''} a decision`)}` : ''));
|
|
104
|
+
lines.push(chalk.gray(' Each fix was re-checked with the diff engine: it removes its breaking change and adds none.'));
|
|
105
|
+
|
|
106
|
+
if (verified.length) {
|
|
107
|
+
lines.push('');
|
|
108
|
+
lines.push(chalk.green.bold(` ✔ FIXES (${verified.length})`));
|
|
109
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
110
|
+
for (const s of verified) {
|
|
111
|
+
lines.push(` ${chalk.green('✔')} ${s.title}`);
|
|
112
|
+
lines.push(chalk.gray(` ${where(s.changes)}`));
|
|
113
|
+
lines.push(` ${chalk.cyan('→')} ${s.detail}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const open = r.suggestions.filter((s) => s.status === 'manual' || s.status === 'rejected');
|
|
118
|
+
if (open.length) {
|
|
119
|
+
lines.push('');
|
|
120
|
+
lines.push(chalk.red.bold(` ✖ NEEDS A DECISION (${open.length})`));
|
|
121
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
122
|
+
for (const s of open) {
|
|
123
|
+
const c = s.changes[0];
|
|
124
|
+
lines.push(` ${chalk.red('●')} ${c.description || `${c.type} ${c.method ? c.method.toUpperCase() : ''} ${c.path || ''} ${c.field || ''}`}`);
|
|
125
|
+
lines.push(chalk.gray(` ${s.status === 'rejected' ? `fix not applied — ${s.reason}` : s.reason}`));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (shim) {
|
|
130
|
+
lines.push('');
|
|
131
|
+
lines.push(chalk.bold(' Spring Boot version layer'));
|
|
132
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
133
|
+
if (shim.transforms.length === 0) {
|
|
134
|
+
lines.push(chalk.gray(' Nothing to generate: no change here can be undone by reshaping JSON.'));
|
|
135
|
+
} else {
|
|
136
|
+
lines.push(` ${plural(shim.transforms.length, 'transform')} — old clients get the old JSON shape; each was checked against sample payloads.`);
|
|
137
|
+
for (const t of shim.transforms) {
|
|
138
|
+
const assumed = t.kind === 'rename' || t.kind === 'enum';
|
|
139
|
+
lines.push(chalk.gray(` ${describeTransform(t)}`) + (assumed ? chalk.yellow(' (inferred rename — check)') : ''));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (const s of shim.skipped) lines.push(chalk.yellow(` not generated: ${s}`));
|
|
143
|
+
if (shim.files) for (const f of shim.files) lines.push(chalk.green(` ✔ ${f}`));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
lines.push('');
|
|
147
|
+
if (outFile) {
|
|
148
|
+
lines.push(chalk.green(` ✔ Wrote ${outFile}`) + chalk.gray(` (${plural(r.ops.length, 'edit')}, comments and layout kept)`));
|
|
149
|
+
if (outFile !== targetPath) lines.push(chalk.gray(` Review: diff -u ${targetPath} ${outFile}`));
|
|
150
|
+
} else if (dryRun && r.ops.length) {
|
|
151
|
+
lines.push(chalk.gray(' --dry-run: nothing written.'));
|
|
152
|
+
}
|
|
153
|
+
lines.push('');
|
|
154
|
+
return lines.join('\n');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function where(changes) {
|
|
158
|
+
const eps = [...new Set(changes.filter((c) => c.method).map((c) => `${c.method.toUpperCase()} ${c.path}`))];
|
|
159
|
+
if (eps.length === 0) return changes[0].field || '';
|
|
160
|
+
return eps.length <= 3 ? eps.join(', ') : `${eps.slice(0, 3).join(', ')} and ${eps.length - 3} more`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function describeTransform(t) {
|
|
164
|
+
const at = `${t.method} ${t.path} ${t.side}`;
|
|
165
|
+
if (t.kind === 'rename') return `${at}: ${t.from} → ${t.to}`;
|
|
166
|
+
if (t.kind === 'convert') return `${at}: ${t.field} ${t.from} → ${t.to}`;
|
|
167
|
+
if (t.kind === 'enum') return `${at}: ${t.field} "${t.from}" → "${t.to}"`;
|
|
168
|
+
if (t.kind === 'default') return `${at}: ${t.field} defaults to ${JSON.stringify(t.value)}`;
|
|
169
|
+
if (t.kind === 'unwrap') return `${at}: unwrap the list from \`${t.property}\``;
|
|
170
|
+
return `${at}: ${t.kind}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = fix;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { normalizeSpec } = require('../normalizeSpec');
|
|
4
|
+
const { diffSpecs } = require('../diffEngine');
|
|
5
|
+
const { BREAKING_TYPES } = require('../classifyChanges');
|
|
6
|
+
const { suggest, detectRenames, detectEnumRenames, reshapedBodies, sig } = require('./strategies');
|
|
7
|
+
const { applyOps, clone } = require('./ops');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Break → fix. For every breaking change between `baseDoc` and `targetDoc`
|
|
11
|
+
* (raw parsed specs), proposes the expand-and-contract edit to the target
|
|
12
|
+
* that keeps existing clients working — and keeps it only if the diff engine
|
|
13
|
+
* agrees: applied on top of the fixes accepted so far, the suggestion must
|
|
14
|
+
* remove the breaking change(s) it addresses and must not introduce any other
|
|
15
|
+
* breaking change. Suggestions are applied in that order, so the returned
|
|
16
|
+
* `fixedDoc` is exactly what was verified.
|
|
17
|
+
*/
|
|
18
|
+
function fixSpec(baseDoc, targetDoc, { sunset = null, depth = 0 } = {}) {
|
|
19
|
+
const baseNorm = normalizeSpec(baseDoc);
|
|
20
|
+
const raw = diffSpecs(baseNorm, normalizeSpec(targetDoc));
|
|
21
|
+
const breaking = raw.filter((d) => BREAKING_TYPES.has(d.type));
|
|
22
|
+
const original = new Set(breaking.map(sig));
|
|
23
|
+
const deprecate = deprecator(targetDoc, sunset);
|
|
24
|
+
|
|
25
|
+
// Fixes depend on each other: restoring a removed field that references an
|
|
26
|
+
// enum which lost a value brings that enum break into view, and only a
|
|
27
|
+
// second round can fix it. So run rounds; within a round a fix is accepted
|
|
28
|
+
// when it removes its own break(s), even if it exposes another. At the end the
|
|
29
|
+
// result must contain no break the original target didn't have — otherwise
|
|
30
|
+
// fall back to strict mode, where no fix may introduce anything.
|
|
31
|
+
const relaxed = run({ baseDoc, targetDoc, baseNorm, deprecate, depth, strict: false });
|
|
32
|
+
const ok = [...relaxed.currentBreaking].every((x) => original.has(x));
|
|
33
|
+
const result = ok ? relaxed : run({ baseDoc, targetDoc, baseNorm, deprecate, depth, strict: true });
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
suggestions: result.suggestions,
|
|
37
|
+
fixedDoc: result.current,
|
|
38
|
+
ops: result.ops,
|
|
39
|
+
before: breaking.length,
|
|
40
|
+
after: result.currentBreaking.size,
|
|
41
|
+
remaining: breaking.filter((c) => result.currentBreaking.has(sig(c))),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function run({ baseDoc, targetDoc, baseNorm, deprecate, depth, strict }) {
|
|
46
|
+
let current = clone(targetDoc);
|
|
47
|
+
let currentBreaking = breakingSigs(baseNorm, current);
|
|
48
|
+
const ops = [];
|
|
49
|
+
const all = [];
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
|
|
52
|
+
for (let round = 0; round < 5; round++) {
|
|
53
|
+
const raw = diffSpecs(baseNorm, normalizeSpec(current));
|
|
54
|
+
const ctx = {
|
|
55
|
+
base: baseDoc,
|
|
56
|
+
target: current,
|
|
57
|
+
renames: detectRenames(raw, baseNorm, normalizeSpec(current)),
|
|
58
|
+
enumRenames: detectEnumRenames(raw, baseNorm, normalizeSpec(current)),
|
|
59
|
+
reshaped: reshapedBodies(raw),
|
|
60
|
+
deprecate,
|
|
61
|
+
// Transforms for changes nested inside a reshaped body (see bodyShapeChanged).
|
|
62
|
+
nested: depth < 2
|
|
63
|
+
? (b, t) => fixSpec(b, t, { depth: depth + 1 }).suggestions.flatMap((x) => x.transforms)
|
|
64
|
+
: null,
|
|
65
|
+
};
|
|
66
|
+
const fresh = raw.filter((d) => BREAKING_TYPES.has(d.type) && !seen.has(sig(d)));
|
|
67
|
+
if (fresh.length === 0 && round > 0) break;
|
|
68
|
+
const suggestions = mergeIdentical(raw.filter((d) => BREAKING_TYPES.has(d.type) && (round === 0 || !seen.has(sig(d)) || retry(all, d)))
|
|
69
|
+
.map((c) => suggest(c, ctx)));
|
|
70
|
+
for (const d of raw) if (BREAKING_TYPES.has(d.type)) seen.add(sig(d));
|
|
71
|
+
|
|
72
|
+
let progress = false;
|
|
73
|
+
for (const s of suggestions) {
|
|
74
|
+
if (!s.strategy) { s.status = 'manual'; continue; }
|
|
75
|
+
if (s.changes.every((c) => !currentBreaking.has(sig(c)))) { s.status = 'covered'; continue; }
|
|
76
|
+
let candidate;
|
|
77
|
+
let after;
|
|
78
|
+
try {
|
|
79
|
+
candidate = applyOps(clone(current), s.ops);
|
|
80
|
+
after = breakingSigs(baseNorm, candidate);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
reject(s, `the edited spec no longer parses: ${err.message}`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const unfixed = s.changes.filter((c) => after.has(sig(c)));
|
|
86
|
+
const introduced = [...after].filter((x) => !currentBreaking.has(x));
|
|
87
|
+
if (unfixed.length > 0) { reject(s, 'the diff engine still reports the breaking change'); continue; }
|
|
88
|
+
// Relaxed rounds let a fix expose a break that a later round fixes (a
|
|
89
|
+
// restored field brings its enum's removed value back into view); the
|
|
90
|
+
// final subset check in fixSpec keeps that honest.
|
|
91
|
+
if (introduced.length > 0 && strict) {
|
|
92
|
+
reject(s, `it would add a breaking change: ${describe(introduced[0])}`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
s.status = 'verified';
|
|
96
|
+
current = candidate;
|
|
97
|
+
currentBreaking = after;
|
|
98
|
+
ops.push(...s.ops);
|
|
99
|
+
progress = true;
|
|
100
|
+
}
|
|
101
|
+
mergeInto(all, suggestions);
|
|
102
|
+
if (!progress) break;
|
|
103
|
+
}
|
|
104
|
+
return { suggestions: all, current, currentBreaking, ops };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A change rejected in an earlier round gets another chance once other fixes landed. */
|
|
108
|
+
function retry(all, d) {
|
|
109
|
+
return all.some((s) => s.status === 'rejected' && s.changes.some((c) => sig(c) === sig(d)));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Later rounds' verdicts replace earlier ones for the same changes. */
|
|
113
|
+
function mergeInto(all, next) {
|
|
114
|
+
for (const s of next) {
|
|
115
|
+
const keys = new Set(s.changes.map(sig));
|
|
116
|
+
for (let i = all.length - 1; i >= 0; i--) {
|
|
117
|
+
if (all[i].changes.some((c) => keys.has(sig(c))) && all[i].status !== 'verified') all.splice(i, 1);
|
|
118
|
+
}
|
|
119
|
+
if (s.status === 'covered' && all.some((x) => x.status === 'verified' && x.changes.some((c) => keys.has(sig(c))))) continue;
|
|
120
|
+
all.push(s);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function reject(s, reason) {
|
|
125
|
+
s.status = 'rejected';
|
|
126
|
+
s.reason = reason;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function breakingSigs(baseNorm, doc) {
|
|
130
|
+
return new Set(diffSpecs(baseNorm, normalizeSpec(doc)).filter((d) => BREAKING_TYPES.has(d.type)).map(sig));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function describe(signature) {
|
|
134
|
+
const [type, method, path, field] = signature.split('|');
|
|
135
|
+
return `${type}${method ? ` ${method.toUpperCase()} ${path}` : ''}${field ? ` ${field}` : ''}`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A change to a shared component shows up once per operation that uses it;
|
|
140
|
+
* the fix is the same edit each time. One suggestion, many changes.
|
|
141
|
+
*/
|
|
142
|
+
function mergeIdentical(list) {
|
|
143
|
+
const byOps = new Map();
|
|
144
|
+
const out = [];
|
|
145
|
+
for (const s of list) {
|
|
146
|
+
if (!s.strategy || s.ops.length === 0) { out.push(s); continue; }
|
|
147
|
+
const key = JSON.stringify(s.ops);
|
|
148
|
+
const prev = byOps.get(key);
|
|
149
|
+
if (prev) {
|
|
150
|
+
prev.changes.push(...s.changes);
|
|
151
|
+
prev.transforms.push(...s.transforms);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
byOps.set(key, s);
|
|
155
|
+
out.push(s);
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Marks a restored node deprecated the way the spec's version allows:
|
|
162
|
+
* `deprecated: true` (OpenAPI 3; beside a $ref it is honoured by 3.1 and
|
|
163
|
+
* ignored by 3.0 tools), `x-deprecated` on Swagger 2.0 schemas, and
|
|
164
|
+
* `x-sunset` when a sunset date was given.
|
|
165
|
+
*/
|
|
166
|
+
function deprecator(targetDoc, sunset) {
|
|
167
|
+
const swagger2 = typeof targetDoc.swagger === 'string';
|
|
168
|
+
return (node, note = null) => {
|
|
169
|
+
if (!node || typeof node !== 'object') return node;
|
|
170
|
+
const isSchemaish = !node.responses && !node.in;
|
|
171
|
+
if (swagger2 && isSchemaish) node['x-deprecated'] = true;
|
|
172
|
+
else node.deprecated = true;
|
|
173
|
+
if (sunset) node['x-sunset'] = sunset;
|
|
174
|
+
if (note && !node.$ref) node.description = node.description ? `${node.description} Deprecated: ${note}` : `Deprecated: ${note}`;
|
|
175
|
+
return node;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
module.exports = { fixSpec };
|