specshield 3.4.17 → 3.5.1

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.
@@ -0,0 +1,702 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Witnesses: for a breaking change, a concrete request that the old contract
5
+ * accepts and the new one rejects — or, for a response-side change, a response
6
+ * the new contract allows that a client written against the old one rejects.
7
+ *
8
+ * The method, per change:
9
+ *
10
+ * 1. Locate the change in both documents (operation, parameter or schema
11
+ * node, via the diff engine's field path).
12
+ * 2. Generate candidate values for that location — values the accepting
13
+ * side allows: its enums, boundaries, pattern matches, each oneOf branch,
14
+ * typed probes, and leaving the field out.
15
+ * 3. Build a whole request (or response) around each candidate, repair every
16
+ * other part of it until both specs accept it (isolation: other changes
17
+ * in the same release must not be what fails it), and validate it with
18
+ * ajv against BOTH full contracts. A candidate is a witness only when the
19
+ * accepting side accepts it and the other side rejects it.
20
+ * 4. Attribute the rejection to the change with a control: the finished
21
+ * witness with only the changed location swapped for a value the
22
+ * rejecting side allows. When the control passes, the change is provably
23
+ * the cause. Without a passing control, the rejection must be reported at
24
+ * the changed location itself.
25
+ *
26
+ * Results:
27
+ * proven a witness validated as above
28
+ * example the change is real but the specs can't show a rejection (a
29
+ * removed optional response field, an undeclared parameter the
30
+ * server will ignore): a concrete before/after instead
31
+ * compatible no witness, and a structural reason none exists: the sound
32
+ * subschema check (./subschema), a reordered oneOf branch, a
33
+ * numeric format that only widened, a response that only narrowed
34
+ * unproven no witness found; the reason says why
35
+ */
36
+
37
+ const { normalizeSpec } = require('../normalizeSpec');
38
+ const { diffSpecs } = require('../diffEngine');
39
+ const { BREAKING_TYPES } = require('../classifyChanges');
40
+ const L = require('../fix/locate');
41
+ const S = require('./schema');
42
+ const C = require('./contract');
43
+ const { generate, fromPattern, ofLength, OMIT, FORMATS } = require('./instance');
44
+ const { relatesTo } = require('./relate');
45
+ const { coSatisfy } = require('./repair');
46
+ const SS = require('./subschema');
47
+
48
+ const WARNING_TYPES = new Set(['CONSTRAINT_TIGHTENED', 'CONSTRAINT_PATTERN_CHANGED']);
49
+ const PROVABLE = new Set([...BREAKING_TYPES, ...WARNING_TYPES]);
50
+
51
+ const CONFIGS = [
52
+ { full: false, examples: true, variant: 0 },
53
+ { full: false, examples: false, variant: 0 },
54
+ { full: true, examples: true, variant: 0 },
55
+ { full: false, examples: true, variant: 1 },
56
+ { full: false, examples: true, variant: 2 },
57
+ { full: true, examples: false, variant: 1 },
58
+ ];
59
+
60
+ // Response-side changes that can only narrow what a server sends.
61
+ const NARROWING = new Set(['FIELD_BECAME_REQUIRED', 'ENUM_VALUE_REMOVED', 'SCHEMA_VARIANT_REMOVED', 'CONSTRAINT_TIGHTENED']);
62
+ // Request-side changes where leaving the value out is the natural witness.
63
+ const ABSENCE = new Set(['FIELD_BECAME_REQUIRED', 'REQUEST_REQUIRED_FIELD_ADDED', 'PARAMETER_BECAME_REQUIRED']);
64
+
65
+ /**
66
+ * Witnesses for every breaking change (and constraint warning) between two
67
+ * raw spec documents. Returns [{ diff, witness }] in diff-engine order.
68
+ */
69
+ function proveAll(baseDoc, targetDoc, { types = PROVABLE } = {}) {
70
+ const raw = diffSpecs(normalizeSpec(baseDoc), normalizeSpec(targetDoc));
71
+ const ctx = context(baseDoc, targetDoc);
72
+ return raw.filter((d) => types.has(d.type)).map((d) => ({ diff: d, witness: proveChange(ctx, d) }));
73
+ }
74
+
75
+ function context(baseDoc, targetDoc) {
76
+ const cache = new Map();
77
+ return {
78
+ base: baseDoc,
79
+ target: targetDoc,
80
+ contract(side, method, path) {
81
+ const key = `${side} ${method} ${path}`;
82
+ if (!cache.has(key)) cache.set(key, C.contractOf(side === 'base' ? baseDoc : targetDoc, method, path));
83
+ return cache.get(key);
84
+ },
85
+ };
86
+ }
87
+
88
+ function proveChange(ctx, d) {
89
+ try {
90
+ if (d.type === 'ENDPOINT_REMOVED' || d.type === 'METHOD_REMOVED') return removedOperation(ctx, d);
91
+ if (d.type === 'SCHEMA_REMOVED') return removedSchema(ctx, d);
92
+ if (d.type === 'RESPONSE_REMOVED') {
93
+ return result(d, 'unproven', { side: 'response', reason: 'A removed status code has no payload to show. It breaks clients that branch on that status; replay real traffic to see whether any receive it.' });
94
+ }
95
+ if (!d.method || !d.path || !d.field) return result(d, 'unproven', { reason: 'The change has no operation to send a request to.' });
96
+ if (d.field.startsWith('parameters.')) return parameterChange(ctx, d);
97
+ const parsed = L.parseField(d.field);
98
+ if (!parsed) return result(d, 'unproven', { reason: `Can't locate "${d.field}" in the spec.` });
99
+ return parsed.side === 'request' ? requestBodyChange(ctx, d, parsed) : responseChange(ctx, d, parsed);
100
+ } catch (err) {
101
+ return result(d, 'unproven', { reason: `Witness search failed: ${err.message}` });
102
+ }
103
+ }
104
+
105
+ // ─── operations and components ──────────────────────────────────────────────
106
+
107
+ function removedOperation(ctx, d) {
108
+ const oldC = ctx.contract('base', d.method, d.path);
109
+ const newC = ctx.contract('target', d.method, d.path);
110
+ for (const cfg of CONFIGS) {
111
+ const req = C.buildRequest(oldC, cfg);
112
+ if (C.checkRequest(oldC, req).length) continue;
113
+ return result(d, 'proven', {
114
+ side: 'request',
115
+ focus: 'operation',
116
+ request: render(oldC, req),
117
+ why: C.checkRequest(newC, req).map((p) => p.message),
118
+ expect: d.type === 'METHOD_REMOVED' ? 'method-not-allowed' : 'not-found',
119
+ tried: 1,
120
+ });
121
+ }
122
+ return result(d, 'unproven', { side: 'request', reason: 'Could not build a request the old spec accepts for this operation.' });
123
+ }
124
+
125
+ function removedSchema(ctx, d) {
126
+ const name = d.field.replace(/^components\.schemas\./, '');
127
+ const refs = new Set([`#/components/schemas/${name}`, `#/definitions/${name}`]);
128
+ const used = Object.values(ctx.base.paths || {}).some((item) => [...L.collectRefs(ctx.base, item).keys()].some((r) => refs.has(r)));
129
+ return used
130
+ ? result(d, 'unproven', { reason: `Operations used "${name}"; the proof is on the endpoint changes its removal caused.` })
131
+ : result(d, 'compatible', { reason: `No operation referenced "${name}", so no request or response can tell it is gone.` });
132
+ }
133
+
134
+ // ─── parameters ─────────────────────────────────────────────────────────────
135
+
136
+ function parameterChange(ctx, d) {
137
+ const name = d.field.slice('parameters.'.length);
138
+ const oldC = ctx.contract('base', d.method, d.path);
139
+ const newC = ctx.contract('target', d.method, d.path);
140
+ const inDesc = /\((query|header|path|cookie)\)/.exec(d.description || '');
141
+ const oldP = oldC.params.find((p) => p.name === name && (!inDesc || p.in === inDesc[1]))
142
+ || oldC.params.find((p) => p.name === name);
143
+ if (!oldP) return result(d, 'unproven', { reason: `Parameter "${name}" isn't in the old spec's operation.` });
144
+ const newP = newC.params.find((p) => p.key === oldP.key) || null;
145
+
146
+ const found = search({
147
+ candidates: probes(ctx.base, oldP.schema, ctx.target, newP && newP.schema, { omitFirst: ABSENCE.has(d.type), side: 'request', optional: !oldP.required }),
148
+ control: (cfg) => (newP ? (newP.schema ? generate(ctx.target, newP.schema, { side: 'request', ...cfg }) : 'abc') : OMIT),
149
+ make: (value, cfg) => isolate(oldC, newC, C.buildRequest(oldC, { ...cfg, target: { param: oldP.key, value } }), oldP.key, cfg),
150
+ swap: (req, v) => {
151
+ const params = { ...req.params };
152
+ if (v === OMIT) delete params[oldP.key]; else params[oldP.key] = v;
153
+ return { ...req, params };
154
+ },
155
+ accept: (req) => C.checkRequest(oldC, req),
156
+ reject: (req) => C.checkRequest(newC, req),
157
+ relates: (problems) => problems.some((p) => p.part === oldP.key),
158
+ });
159
+ if (found.witness) return requestWitness(d, oldC, newC, found, oldP.key);
160
+
161
+ if (d.type === 'PARAMETER_REMOVED' && oldP.in !== 'path') {
162
+ const req = firstValid(oldC, (cfg) => C.buildRequest(oldC, { ...cfg, full: true }), (r) => r.params[oldP.key] !== undefined);
163
+ if (req) {
164
+ return result(d, 'example', {
165
+ side: 'request', focus: oldP.key, request: render(oldC, req), expect: 'ignored', tried: found.tried,
166
+ reason: `The new spec no longer declares ${oldP.in} parameter "${name}". A server built from it ignores the value clients still send — or rejects the request, if it refuses unknown parameters.`,
167
+ });
168
+ }
169
+ }
170
+ const why = structural({ side: 'request', param: name, a: { doc: ctx.base, node: oldP.schema }, b: { doc: ctx.target, node: newP && newP.schema } });
171
+ if (why) return result(d, why.status, { side: 'request', tried: found.tried, reason: why.reason });
172
+ return result(d, 'unproven', { side: 'request', tried: found.tried, reason: noWitness(found.tried, 'request') });
173
+ }
174
+
175
+ // ─── request bodies ─────────────────────────────────────────────────────────
176
+
177
+ function requestBodyChange(ctx, d, parsed) {
178
+ const oldC = ctx.contract('base', d.method, d.path);
179
+ const newC = ctx.contract('target', d.method, d.path);
180
+ if (!oldC.body || !oldC.body.schema) return result(d, 'unproven', { side: 'request', reason: 'The old spec has no request body schema here.' });
181
+ if (!oldC.body.structured) return result(d, 'unproven', { side: 'request', reason: `The request body is ${oldC.body.mediaType}; witnesses are built for JSON and form bodies.` });
182
+ const steps = parsed.steps;
183
+ const aNode = S.nodeAt(ctx.base, oldC.body.schema, steps);
184
+ const bNode = newC.body && newC.body.schema ? S.nodeAt(ctx.target, newC.body.schema, steps) : null;
185
+ const leafOptional = !isRequiredAt(ctx.base, oldC.body.schema, steps);
186
+
187
+ const found = search({
188
+ candidates: aNode ? probes(ctx.base, aNode, ctx.target, bNode, { omitFirst: ABSENCE.has(d.type), side: 'request', optional: leafOptional }) : [OMIT],
189
+ control: (cfg) => (bNode ? generate(ctx.target, bNode, { side: 'request', ...cfg }) : OMIT),
190
+ make: (value, cfg) => {
191
+ const req = C.buildRequest(oldC, { ...cfg, target: { body: steps, value } });
192
+ if (newC.body && newC.body.schema) {
193
+ req.body = coSatisfy(req.body, { a: { doc: ctx.base, schema: oldC.body.schema }, b: { doc: ctx.target, schema: newC.body.schema }, protect: steps, side: 'request', cfg });
194
+ }
195
+ return isolate(oldC, newC, req, 'body', cfg);
196
+ },
197
+ swap: (req, v) => {
198
+ const body = setAt(req.body, S.instancePath(steps), v);
199
+ return body === undefined && v !== OMIT ? null : { ...req, body };
200
+ },
201
+ accept: (req) => C.checkRequest(oldC, req),
202
+ reject: (req) => C.checkRequest(newC, req),
203
+ relates: (problems) => problems.some((p) => p.part === 'body' && relatesTo(p.errors, steps)),
204
+ });
205
+ if (found.witness) return requestWitness(d, oldC, newC, found, 'body', steps);
206
+
207
+ const moved = movedVariant(steps, { doc: ctx.base, root: oldC.body.schema }, { doc: ctx.target, root: newC.body && newC.body.schema }, 'request');
208
+ if (moved) return result(d, moved.status, { side: 'request', tried: found.tried, reason: moved.reason });
209
+
210
+ if (d.type === 'REQUEST_FIELD_REMOVED' && aNode) {
211
+ const req = firstValid(oldC, (cfg) => C.buildRequest(oldC, { ...cfg, target: { body: steps, value: generate(ctx.base, aNode, { side: 'request', ...cfg }) } }));
212
+ if (req) {
213
+ return result(d, 'example', {
214
+ side: 'request', focus: 'body', request: render(oldC, req), expect: 'ignored', tried: found.tried,
215
+ reason: `The new spec no longer declares ${display(d.field)}. A server built from it drops the value clients still send — or rejects the request, if it refuses unknown fields.`,
216
+ });
217
+ }
218
+ }
219
+ const why = structural({
220
+ side: 'request', steps,
221
+ a: { doc: ctx.base, node: aNode, root: oldC.body.schema },
222
+ b: { doc: ctx.target, node: bNode, root: newC.body && newC.body.schema },
223
+ });
224
+ if (why) return result(d, why.status, { side: 'request', tried: found.tried, reason: why.reason });
225
+ return result(d, 'unproven', { side: 'request', tried: found.tried, reason: noWitness(found.tried, 'request') });
226
+ }
227
+
228
+ function requestWitness(d, oldC, newC, found, focus, steps = null) {
229
+ const hint = focus === 'body' && newC.body && newC.body.schema
230
+ ? (e) => unionHint(newC.doc, newC.body.schema, found.witness.body, e, 'request')
231
+ : () => null;
232
+ // The control a running build should accept: the found one, or else the same
233
+ // request rebuilt for the new spec with the changed part made valid.
234
+ let control = found.control;
235
+ if (!control) {
236
+ const like = { params: { ...found.witness.params }, body: focus === 'body' ? undefined : found.witness.body };
237
+ delete like.params[focus];
238
+ const c = isolate(newC, oldC, C.buildRequest(newC, { like }), null, CONFIGS[0]);
239
+ if (C.checkRequest(newC, c).length === 0) control = c;
240
+ }
241
+ return result(d, 'proven', {
242
+ side: 'request',
243
+ focus,
244
+ request: render(oldC, found.witness),
245
+ ...explain(found.problems, focus, steps, hint, Boolean(found.control)),
246
+ control: control ? render(newC, control) : null,
247
+ expect: 'rejected',
248
+ tried: found.tried,
249
+ });
250
+ }
251
+
252
+ // ─── responses ──────────────────────────────────────────────────────────────
253
+
254
+ function responseChange(ctx, d, parsed) {
255
+ const oldC = ctx.contract('base', d.method, d.path);
256
+ const newC = ctx.contract('target', d.method, d.path);
257
+ const code = parsed.code;
258
+ const oldR = oldC.responses[code];
259
+ const newR = newC.responses[code];
260
+ if (!oldR || !newR || !oldR.schema || !newR.schema) return result(d, 'unproven', { side: 'response', reason: `No JSON schema for status ${code} on both sides.` });
261
+ const steps = parsed.steps;
262
+ const aNode = S.nodeAt(ctx.target, newR.schema, steps); // what the server may send now
263
+ const bNode = S.nodeAt(ctx.base, oldR.schema, steps); // what old clients expect
264
+ const accept = S.validator(ctx.target, newR.schema, { side: 'response' });
265
+ const reject = S.validator(ctx.base, oldR.schema, { side: 'response' });
266
+ const asProblems = (r) => (r.ok ? [] : [{ part: 'response', label: 'response', message: r.errors.map((e) => S.describeError(e, 'response')).join('; '), errors: r.errors }]);
267
+
268
+ const found = search({
269
+ candidates: aNode ? probes(ctx.target, aNode, ctx.base, bNode, { omitFirst: false, side: 'response', optional: !isRequiredAt(ctx.target, newR.schema, steps) }) : [OMIT],
270
+ control: (cfg) => (bNode ? generate(ctx.base, bNode, { side: 'response', ...cfg }) : OMIT),
271
+ make: (value, cfg) => ({
272
+ body: coSatisfy(generate(ctx.target, newR.schema, { side: 'response', ...cfg, target: { steps, value } }), {
273
+ a: { doc: ctx.target, schema: newR.schema }, b: { doc: ctx.base, schema: oldR.schema }, protect: steps, side: 'response', cfg,
274
+ }),
275
+ }),
276
+ swap: (r, v) => {
277
+ const body = setAt(r.body, S.instancePath(steps), v);
278
+ return body === undefined && v !== OMIT ? null : { body };
279
+ },
280
+ accept: (r) => asProblems(accept(r.body)),
281
+ reject: (r) => asProblems(reject(r.body)),
282
+ relates: (problems) => problems.some((p) => relatesTo(p.errors, steps)),
283
+ });
284
+ const request = requestFor(newC, oldC);
285
+
286
+ if (found.witness) {
287
+ return result(d, 'proven', {
288
+ side: 'response', focus: 'response', request,
289
+ response: { status: code, body: found.witness.body },
290
+ ...explain(found.problems, 'response', steps, (e) => unionHint(ctx.base, oldR.schema, found.witness.body, e, 'response'), Boolean(found.control)),
291
+ expect: 'response',
292
+ tried: found.tried,
293
+ });
294
+ }
295
+
296
+ // A branch that only moved inside a oneOf/anyOf isn't a removal: check that before showing an example.
297
+ const moved = movedVariant(steps, { doc: ctx.base, root: oldR.schema }, { doc: ctx.target, root: newR.schema }, 'response');
298
+ if (moved) return result(d, moved.status, { side: 'response', tried: found.tried, reason: moved.reason });
299
+
300
+ if (d.type === 'RESPONSE_FIELD_REMOVED' && bNode) {
301
+ const after = firstOk((cfg) => generate(ctx.target, newR.schema, { side: 'response', ...cfg, full: true }), (b) => accept(b).ok);
302
+ const before = firstOk((cfg) => generate(ctx.base, oldR.schema, { side: 'response', ...cfg, full: true }), (b) => reject(b).ok);
303
+ if (after !== undefined) {
304
+ return result(d, 'example', {
305
+ side: 'response', focus: 'response', request,
306
+ response: { status: code, body: after },
307
+ before: before !== undefined ? { status: code, body: before } : null,
308
+ expect: 'response', tried: found.tried,
309
+ reason: `The old spec documented ${display(d.field)} without requiring it; the new spec drops it. A client that reads it now gets nothing.`,
310
+ });
311
+ }
312
+ }
313
+ // Old clients must accept what the server sends now: B (old) is the accepting side here.
314
+ const why = structural({
315
+ side: 'response', steps,
316
+ a: { doc: ctx.base, node: bNode, root: oldR.schema },
317
+ b: { doc: ctx.target, node: aNode, root: newR.schema },
318
+ });
319
+ if (why) return result(d, why.status, { side: 'response', tried: found.tried, reason: why.reason });
320
+ if (NARROWING.has(d.type)) {
321
+ return result(d, 'compatible', {
322
+ side: 'response', tried: found.tried,
323
+ reason: 'This only narrows what the server may send: every response the new spec allows here, the old spec allowed too. It can\'t break a client of the old spec on its own.',
324
+ });
325
+ }
326
+ return result(d, 'unproven', { side: 'response', tried: found.tried, reason: noWitness(found.tried, 'response') });
327
+ }
328
+
329
+ /** A request that reaches the operation: valid for the new spec, and for the old one when possible. */
330
+ function requestFor(newC, oldC) {
331
+ const req = firstValid(newC, (cfg) => isolate(newC, oldC, C.buildRequest(newC, cfg), null, cfg)) || C.buildRequest(newC, CONFIGS[0]);
332
+ return render(newC, req);
333
+ }
334
+
335
+ // ─── when there is no witness ───────────────────────────────────────────────
336
+
337
+ const NUMERIC_FORMATS = new Set([undefined, null, 'int32', 'int64', 'float', 'double']);
338
+
339
+ /**
340
+ * After the search finds nothing, a structural reason the change can't break
341
+ * anyone — so "no witness" becomes "compatible" with a justification instead
342
+ * of an absence of evidence. `a` is the old spec's side and `b` the new one's.
343
+ * For a request, the new schema must accept everything the old one did; for a
344
+ * response, old clients must accept everything the new schema lets the server
345
+ * send. Every "compatible" here rests on the sound subschema check (or on a
346
+ * wire-level argument for parameters). Returns { status, reason } or null.
347
+ */
348
+ function structural({ side, steps = [], param = null, a, b }) {
349
+ const from = side === 'request' ? a : b; // instances that must stay accepted
350
+ const to = side === 'request' ? b : a; // the schema that must accept them
351
+ const moved = movedVariant(steps, a, b, side);
352
+ if (moved) return moved;
353
+ if (!a.node || !b.node) return null;
354
+ const o = S.effective(a.doc, a.node);
355
+ const n = S.effective(b.doc, b.node);
356
+ if (!o || !n) return null;
357
+ const ot = S.typeOf(o);
358
+ const nt = S.typeOf(n);
359
+ const fmt = (x) => `${S.typeOf(x)}${x.format ? `:${x.format}` : ''}`;
360
+
361
+ if (ot && ot === nt && (ot === 'integer' || ot === 'number') && o.format !== n.format && NUMERIC_FORMATS.has(o.format) && NUMERIC_FORMATS.has(n.format)) {
362
+ return compatible(`Only the numeric format changed (${fmt(o)} → ${fmt(n)}). JSON numbers carry no width, so every value ${side === 'request' ? 'the old spec accepted is still accepted' : 'the server sends still reads the same to old clients'}.`);
363
+ }
364
+ if (param && side === 'request' && nt === 'array') {
365
+ const it = n.items ? S.typeOf(S.effective(b.doc, n.items)) : null;
366
+ if (!it || it === ot || it === 'string' || (ot === 'integer' && it === 'number')) {
367
+ return compatible(`On the wire a single value is a one-item list, so "${param}=1" reads the same under both specs.`);
368
+ }
369
+ }
370
+ if (SS.widens(from, to)) {
371
+ if (ot === 'integer' && nt === 'number') return compatible('integer → number widens the type: every integer is still a valid number.');
372
+ if (ot === 'number' && nt === 'integer' && side === 'response') return compatible('number → integer narrows what the server sends: every integer is a number old clients accept.');
373
+ return compatible(side === 'request'
374
+ ? 'The new schema accepts everything the old one did here (checked schema against schema), so no request that worked can fail on this change.'
375
+ : 'Everything the new schema lets the server send here, the old schema accepted too (checked schema against schema), so old clients can\'t break on this change.');
376
+ }
377
+ return null;
378
+ }
379
+
380
+ /**
381
+ * The diff engine compares oneOf/anyOf branches by position, so inserting or
382
+ * reordering branches reports changes in branches that only moved. When the
383
+ * old branch named by `steps` lives on in the new union — taken in full by one
384
+ * of its branches (for a oneOf, one no other branch can also match), and for a
385
+ * response still documenting the field the change is about — say so.
386
+ */
387
+ function movedVariant(steps, old, neu, side) {
388
+ let k = -1;
389
+ for (let i = steps.length - 1; i >= 0; i--) if (steps[i].variant) { k = i; break; }
390
+ if (k < 0 || !old.root || !neu.root) return null;
391
+ const branch = S.nodeAt(old.doc, old.root, steps.slice(0, k + 1));
392
+ const holder = S.effective(neu.doc, S.nodeAt(neu.doc, neu.root, steps.slice(0, k)));
393
+ const kind = steps[k].variant;
394
+ const union = holder && holder[kind];
395
+ if (!branch || !Array.isArray(union)) return null;
396
+ const rest = steps.slice(k + 1);
397
+ const from = { doc: old.doc, node: branch };
398
+ const j = union.findIndex((v) => SS.widens(from, { doc: neu.doc, node: v }) && (side === 'request' || rest.length === 0 || S.nodeAt(neu.doc, v, rest)));
399
+ if (j < 0) return null;
400
+ if (kind === 'oneOf' && !SS.exclusiveIn(neu.doc, union[j], union.filter((_, x) => x !== j))) return null;
401
+ const at = `${kind}[${steps[k].index}]`;
402
+ const there = `${kind}[${j}]`;
403
+ const unchanged = SS.equivalent(from, { doc: neu.doc, node: union[j] });
404
+ if (j === steps[k].index) {
405
+ return compatible(`${at} still accepts everything it did (checked schema against schema); the reported difference doesn't reach clients.`);
406
+ }
407
+ return compatible(`The branches were reordered: the old ${at} is the new ${there}${unchanged ? ', unchanged' : ', and accepts at least as much'}${side === 'response' && rest.length ? `, still documenting ${rest.map((x) => x.prop).filter(Boolean).join('.')}` : ''}. The engine compares branches by position, so the move shows up as changes; ${side === 'request' ? 'no request that matched before is rejected' : 'nothing old clients read is gone'}.`);
408
+ }
409
+
410
+ function compatible(reason) {
411
+ return { status: 'compatible', reason };
412
+ }
413
+
414
+ // ─── search ─────────────────────────────────────────────────────────────────
415
+
416
+ /**
417
+ * Tries each candidate under each generator config. A witness is accepted by
418
+ * `accept` (no problems) and rejected by `reject`. It counts when its control
419
+ * — the same finished artifact with only the changed location swapped for a
420
+ * value `reject` allows — passes (so the location alone causes the rejection),
421
+ * or, failing that, when the rejection is reported at the location itself.
422
+ */
423
+ function search({ candidates, control, make, swap, accept, reject, relates }) {
424
+ let tried = 0;
425
+ for (const cfg of CONFIGS) {
426
+ let swapIn;
427
+ try { swapIn = control(cfg); } catch { swapIn = undefined; }
428
+ for (const value of candidates) {
429
+ tried++;
430
+ let x;
431
+ try { x = make(value, cfg); } catch { continue; }
432
+ if (!x || accept(x).length) continue;
433
+ const problems = reject(x);
434
+ if (!problems.length) continue;
435
+ let ctrl = null;
436
+ if (swapIn !== undefined) {
437
+ try {
438
+ const c = swap(x, swapIn);
439
+ if (c && reject(c).length === 0) ctrl = c;
440
+ } catch { /* no control */ }
441
+ }
442
+ if (!ctrl && !relates(problems)) continue;
443
+ return { witness: x, problems, control: ctrl, tried };
444
+ }
445
+ }
446
+ return { witness: null, tried };
447
+ }
448
+
449
+ /** A copy of `value` with the JSON pointer `ptr` set to `v` (OMIT removes it). */
450
+ function setAt(value, ptr, v) {
451
+ if (ptr === '') return v === OMIT ? undefined : clone(v);
452
+ const root = clone(value);
453
+ const parts = ptr.split('/').slice(1).map((k) => k.replace(/~1/g, '/').replace(/~0/g, '~'));
454
+ let cur = root;
455
+ for (const k of parts.slice(0, -1)) {
456
+ if (cur === null || typeof cur !== 'object' || cur[k] === undefined) return undefined;
457
+ cur = cur[k];
458
+ }
459
+ if (cur === null || typeof cur !== 'object') return undefined;
460
+ const last = parts[parts.length - 1];
461
+ if (v === OMIT) delete cur[last]; else cur[last] = clone(v);
462
+ return root;
463
+ }
464
+
465
+ function clone(v) {
466
+ return v === undefined || v === null || typeof v !== 'object' ? v : JSON.parse(JSON.stringify(v));
467
+ }
468
+
469
+ /**
470
+ * The values worth trying at one location: what the accepting schema (a)
471
+ * allows, aimed at what the rejecting schema (b) forbids.
472
+ */
473
+ function probes(docA, aNode, docB, bNode, { omitFirst = false, side = 'request', optional = true } = {}) {
474
+ const a = S.effective(docA, aNode) || {};
475
+ const b = bNode ? S.effective(docB, bNode) : null;
476
+ const out = [];
477
+ const add = (v) => { if (v !== undefined) out.push(v); };
478
+
479
+ if (omitFirst && optional) add(OMIT);
480
+ if (Array.isArray(a.enum)) {
481
+ for (const v of a.enum) if (!b || !Array.isArray(b.enum) || !b.enum.some((x) => same(x, v))) add(v);
482
+ }
483
+ for (const cfg of CONFIGS) add(generate(docA, aNode, { side, ...cfg }));
484
+ const variants = a.oneOf || a.anyOf;
485
+ if (Array.isArray(variants)) variants.forEach((_, i) => add(generate(docA, aNode, { side, variant: i })));
486
+
487
+ const ta = S.typeOf(a);
488
+ // Just past the rejecting side's bounds first: the smallest value that shows the change.
489
+ const nums = b ? [add1(b.maximum, 1), sub(b.minimum, 1), add1(b.maximum, 0.5), sub(b.minimum, 0.5), b.exclusiveMinimum, b.exclusiveMaximum] : [];
490
+ nums.push(a.minimum, a.maximum, a.exclusiveMinimum, a.exclusiveMaximum);
491
+ if (ta === 'integer' || ta === 'number' || !ta) {
492
+ for (const n of nums) if (typeof n === 'number' && Number.isFinite(n)) add(ta === 'integer' ? Math.round(n) : n);
493
+ [0, 1, -1, 1.5, 1000000].forEach(add);
494
+ }
495
+ if (ta === 'string' || !ta) {
496
+ const lengths = [b && add1(b.maxLength, 1), b && sub(b.minLength, 1), a.minLength, a.maxLength].filter((n) => typeof n === 'number' && n >= 0 && n <= 10000);
497
+ for (const n of lengths) add(stringOf(a, n));
498
+ if (b && b.pattern && a.pattern !== b.pattern) {
499
+ for (const s of ['abc', 'ABC', '123', 'a-b', 'a b', 'a_b', '', 'x'.repeat(64)]) add(s);
500
+ }
501
+ ['abc', '1', 'true', '', ...Object.values(FORMATS).slice(0, 4)].forEach(add);
502
+ }
503
+ if (ta === 'array' || !ta) {
504
+ const item = a.items ? generate(docA, a.items, { side }) : 'abc';
505
+ add([]);
506
+ for (const n of [b && add1(b.maxItems, 1), b && sub(b.minItems, 1), a.minItems, a.maxItems]) {
507
+ if (typeof n === 'number' && n >= 0 && n <= 1000) add(Array.from({ length: n }, (_, i) => (typeof item === 'string' ? `${item}${i}` : typeof item === 'number' ? item + i : item)));
508
+ }
509
+ }
510
+ if (ta === 'object' || !ta) {
511
+ const base = generate(docA, aNode, { side, full: true });
512
+ if (base && typeof base === 'object' && !Array.isArray(base)) add({ ...base, extra_field: 'abc' });
513
+ add({});
514
+ }
515
+ [true, false, null, 'abc', 1, 1.5, [], {}].forEach(add);
516
+ if (!omitFirst && optional) add(OMIT);
517
+ return dedupe(out);
518
+ }
519
+
520
+ function stringOf(a, n) {
521
+ if (a.pattern) {
522
+ const s = fromPattern(a.pattern, { min: n, max: n });
523
+ if (s !== null) return s;
524
+ }
525
+ return ofLength(FORMATS[a.format] || 'a', a.format, n, n);
526
+ }
527
+
528
+ /**
529
+ * Makes `req` satisfy `other` (the contract on the far side) everywhere except
530
+ * `focus`: adds the parameters it requires, and swaps in a body it accepts
531
+ * when the original's problems there are unrelated to the change.
532
+ */
533
+ function isolate(contract, other, req, focus, cfg) {
534
+ const out = { ...req, params: { ...req.params } };
535
+ for (const p of other.params) {
536
+ if (p.key === focus || out.params[p.key] !== undefined || !p.required) continue;
537
+ out.params[p.key] = p.schema ? generate(other.doc, p.schema, { side: 'request', ...cfg }) : 'abc';
538
+ }
539
+ // A parameter both declare but with different rules: prefer a value both accept.
540
+ for (const p of other.params) {
541
+ if (p.key === focus || out.params[p.key] === undefined || !p.schema) continue;
542
+ const ok = S.validator(other.doc, p.schema, { side: 'request', kind: 'param' })(C.wire(out.params[p.key])).ok;
543
+ if (ok) continue;
544
+ const v = generate(other.doc, p.schema, { side: 'request', ...cfg });
545
+ const mine = contract.params.find((x) => x.key === p.key);
546
+ if (!mine || !mine.schema || S.validator(contract.doc, mine.schema, { side: 'request', kind: 'param' })(C.wire(v)).ok) out.params[p.key] = v;
547
+ }
548
+ if (focus !== 'body' && out.body !== undefined && contract.body && contract.body.schema && other.body && other.body.structured && other.body.schema) {
549
+ out.body = coSatisfy(out.body, { a: { doc: contract.doc, schema: contract.body.schema }, b: { doc: other.doc, schema: other.body.schema }, side: 'request', cfg });
550
+ }
551
+ return out;
552
+ }
553
+
554
+ function firstValid(contract, build, also = () => true) {
555
+ for (const cfg of CONFIGS) {
556
+ let req;
557
+ try { req = build(cfg); } catch { continue; }
558
+ if (req && C.checkRequest(contract, req).length === 0 && also(req)) return req;
559
+ }
560
+ return null;
561
+ }
562
+
563
+ function firstOk(build, ok) {
564
+ for (const cfg of CONFIGS) {
565
+ let v;
566
+ try { v = build(cfg); } catch { continue; }
567
+ if (v !== undefined && ok(v)) return v;
568
+ }
569
+ return undefined;
570
+ }
571
+
572
+ /** Is the property at the end of `steps` required in its parent? */
573
+ function isRequiredAt(doc, root, steps) {
574
+ if (!steps.length) return true;
575
+ const last = steps[steps.length - 1];
576
+ if (last.prop === undefined) return true;
577
+ const parent = S.effective(doc, S.nodeAt(doc, root, steps.slice(0, -1)));
578
+ return Boolean(parent && Array.isArray(parent.required) && parent.required.includes(last.prop));
579
+ }
580
+
581
+ // ─── results ────────────────────────────────────────────────────────────────
582
+
583
+ /**
584
+ * "matches none of the allowed forms" says little; name the value no branch
585
+ * takes — a discriminator the other spec doesn't know, or a scalar that fits
586
+ * no branch (a null that used to be allowed).
587
+ */
588
+ function unionHint(doc, root, instance, e, side) {
589
+ if (e.keyword !== 'oneOf' && e.keyword !== 'anyOf') return null;
590
+ const node = S.effective(doc, S.nodeAtPointer(doc, root, e.path));
591
+ const branches = node && (node.oneOf || node.anyOf);
592
+ if (!Array.isArray(branches)) return null;
593
+ const v = valueAt(instance, e.path);
594
+ if (v === null || typeof v !== 'object') return `${JSON.stringify(v)} fits none of them`;
595
+ for (const [k, x] of Object.entries(v)) {
596
+ if (x === null || typeof x === 'object') continue;
597
+ const pinned = branches.map((b) => S.effective(doc, b)).filter((b) => b && b.properties && b.properties[k])
598
+ .map((b) => S.effective(doc, b.properties[k])).filter((p) => p && (Array.isArray(p.enum) || p.const !== undefined));
599
+ if (pinned.length && !pinned.some((p) => (p.enum || [p.const]).includes(x))) {
600
+ return side === 'response' ? `"${k}": ${JSON.stringify(x)} is a kind the old spec didn't have` : `"${k}": ${JSON.stringify(x)} is no longer accepted`;
601
+ }
602
+ }
603
+ return null;
604
+ }
605
+
606
+ function valueAt(v, ptr) {
607
+ let cur = v;
608
+ for (const k of ptr.split('/').slice(1)) {
609
+ if (cur === null || typeof cur !== 'object') return undefined;
610
+ cur = cur[k.replace(/~1/g, '/').replace(/~0/g, '~')];
611
+ }
612
+ return cur;
613
+ }
614
+
615
+ /**
616
+ * Splits the rejecting side's complaints into the ones this change causes
617
+ * (`why`) and the ones other changes in the same release cause (`also`) —
618
+ * conflicts no single value can satisfy on both sides, such as a field that
619
+ * changed from integer to string next to the one being shown.
620
+ */
621
+ function explain(problems, focus, steps, hint = () => null, isolated = false) {
622
+ const why = [];
623
+ const also = [];
624
+ for (const p of problems) {
625
+ if (p.part !== 'body' && p.part !== 'response') {
626
+ (isolated || p.part === focus || focus === 'operation' ? why : also).push(p.message);
627
+ continue;
628
+ }
629
+ if (!p.errors.length) { (isolated || p.part === focus ? why : also).push(p.message); continue; }
630
+ for (const e of p.errors) {
631
+ const h = hint(e);
632
+ const msg = S.describeError(e, p.label) + (h ? ` — ${h}` : '');
633
+ // With a passing control the change is the only difference, so every complaint is its doing.
634
+ (isolated || (p.part === focus && (!steps || relatesTo([e], steps))) ? why : also).push(msg);
635
+ }
636
+ }
637
+ return { why, also };
638
+ }
639
+
640
+ function result(d, status, extra = {}) {
641
+ return {
642
+ status,
643
+ side: extra.side || null,
644
+ focus: extra.focus || null,
645
+ operation: d.method && d.path ? { method: d.method.toUpperCase(), path: d.path } : null,
646
+ request: extra.request || null,
647
+ response: extra.response || null,
648
+ before: extra.before || null,
649
+ why: extra.why || [],
650
+ also: extra.also || [],
651
+ control: extra.control || null,
652
+ expect: extra.expect || null,
653
+ reason: extra.reason || null,
654
+ tried: extra.tried || 0,
655
+ };
656
+ }
657
+
658
+ /**
659
+ * The request as it goes on the wire: method, path with query, headers, and
660
+ * the body — `body` structured, `bodyText` exactly as sent when it isn't JSON
661
+ * (a form). Swagger 2.0 formData parameters become a form body too.
662
+ */
663
+ function render(contract, req) {
664
+ const { path, headers, form } = C.urlOf(contract, req);
665
+ const b = contract.body;
666
+ if (req.body !== undefined && b && b.form) {
667
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
668
+ return { method: req.method, path, headers, body: req.body, bodyText: C.formEncode(req.body) };
669
+ }
670
+ if (form) {
671
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
672
+ return { method: req.method, path, headers, body: null, bodyText: form };
673
+ }
674
+ if (req.body !== undefined) headers['Content-Type'] = b && b.json ? b.mediaType.replace('*/*', 'application/json') : 'application/json';
675
+ return { method: req.method, path, headers, body: req.body === undefined ? null : req.body };
676
+ }
677
+
678
+ function noWitness(tried, side) {
679
+ return side === 'request'
680
+ ? `No request the old spec accepts is rejected by the new one (${tried} tried). This change may be compatible on the wire — or need values the generator can't produce.`
681
+ : `No response the new spec allows is rejected by the old one (${tried} tried).`;
682
+ }
683
+
684
+ function display(field) {
685
+ return `"${field.replace(/^requestBody\./, '').replace(/^responses\.[^.]+\./, '')}"`;
686
+ }
687
+
688
+ function dedupe(values) {
689
+ const seen = new Set();
690
+ return values.filter((v) => {
691
+ const k = v === OMIT ? '\u0000omit' : JSON.stringify(v);
692
+ if (seen.has(k)) return false;
693
+ seen.add(k);
694
+ return true;
695
+ });
696
+ }
697
+
698
+ function same(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
699
+ function sub(n, d) { return typeof n === 'number' ? n - d : undefined; }
700
+ function add1(n, d) { return typeof n === 'number' ? n + d : undefined; }
701
+
702
+ module.exports = { proveAll, proveChange, context, probes, PROVABLE, WARNING_TYPES };