specshield 3.5.0 → 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,400 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Deterministic example instances of a schema, with an optional override at
5
+ * one location — the building block of a witness: "a valid request, except
6
+ * that this one field holds this value (or is left out)".
7
+ *
8
+ * The generator aims for instances ajv accepts but never has to be perfect:
9
+ * every witness is validated afterwards, and one that doesn't validate under
10
+ * the spec it claims to satisfy is discarded.
11
+ */
12
+
13
+ const S = require('./schema');
14
+
15
+ const OMIT = Symbol('omit');
16
+
17
+ const FORMATS = {
18
+ 'date-time': '2026-01-15T10:00:00Z',
19
+ date: '2026-01-15',
20
+ time: '10:00:00Z',
21
+ uuid: '3fa85f64-5717-4562-b3fc-2c963f66afa6',
22
+ email: 'jane@example.com',
23
+ 'idn-email': 'jane@example.com',
24
+ uri: 'https://example.com/a',
25
+ 'uri-reference': '/a',
26
+ url: 'https://example.com/a',
27
+ hostname: 'example.com',
28
+ 'idn-hostname': 'example.com',
29
+ ipv4: '192.0.2.1',
30
+ ipv6: '2001:db8::1',
31
+ byte: 'YWJj',
32
+ binary: 'abc',
33
+ password: 'secret-1',
34
+ duration: 'P1D',
35
+ int32: '1',
36
+ int64: '1',
37
+ };
38
+
39
+ /**
40
+ * @param doc the spec document `schema` lives in
41
+ * @param schema a schema node of `doc`
42
+ * @param opts.side 'request' (skip readOnly) | 'response' (skip writeOnly)
43
+ * @param opts.full include every optional property (default: required only)
44
+ * @param opts.examples use the spec's own `example` values for scalars
45
+ * @param opts.variant which oneOf/anyOf branch to take (index, wraps around)
46
+ * @param opts.target { steps, value } — at `steps`, put `value` (OMIT leaves it out)
47
+ * @returns the instance, or undefined when the root itself is omitted
48
+ */
49
+ // Size limits: "full" instances include optional properties only this close to
50
+ // the root, and no instance grows past this many values. Recursive specs
51
+ // (an object whose fields expand into other objects) would otherwise explode.
52
+ const FULL_DEPTH = 3;
53
+ const MAX_NODES = 1500;
54
+
55
+ function generate(doc, schema, opts = {}) {
56
+ const o = { side: 'request', full: false, examples: true, variant: 0, target: null, ...opts, budget: { left: MAX_NODES } };
57
+ const v = gen(doc, schema, o, [], 0, null);
58
+ return v === OMIT ? undefined : v;
59
+ }
60
+
61
+ function gen(doc, node, o, steps, depth, discriminated) {
62
+ if (o.target && sameSteps(steps, o.target.steps)) return clone(o.target.value);
63
+ if (depth > 14) return null;
64
+ o.budget.left--;
65
+ const s = S.effective(doc, node);
66
+ if (!s) return 'value';
67
+
68
+ if (s.const !== undefined) return clone(s.const);
69
+ const variants = s.oneOf || s.anyOf;
70
+ if (Array.isArray(variants) && variants.length) return genVariant(doc, s, variants, o, steps, depth);
71
+
72
+ if (Array.isArray(s.enum) && s.enum.length) {
73
+ const vals = s.enum.filter((v) => v !== null);
74
+ return clone(vals.length ? vals[0] : s.enum[0]);
75
+ }
76
+ const type = S.typeOf(s);
77
+ const leaf = type !== 'object' && type !== 'array';
78
+ if (o.examples && leaf && s.example !== undefined && !onPath(steps, o.target)) return clone(s.example);
79
+ if (o.examples && leaf && s.default !== undefined && !onPath(steps, o.target)) return clone(s.default);
80
+
81
+ switch (type) {
82
+ case 'object': return genObject(doc, s, o, steps, depth, discriminated);
83
+ case 'array': return genArray(doc, s, o, steps, depth);
84
+ case 'integer': return number(s, true);
85
+ case 'number': return number(s, false);
86
+ case 'boolean': return true;
87
+ case 'null': return null;
88
+ case 'string': return string(s);
89
+ default: return s.properties ? genObject(doc, s, o, steps, depth, discriminated) : 'value';
90
+ }
91
+ }
92
+
93
+ function genObject(doc, s, o, steps, depth, discriminated) {
94
+ const out = {};
95
+ const required = new Set(s.required || []);
96
+ const skip = o.side === 'request' ? 'readOnly' : 'writeOnly';
97
+ for (const [name, child] of Object.entries(s.properties || {})) {
98
+ const at = [...steps, { prop: name }];
99
+ const through = onPath(at, o.target);
100
+ const c = S.deref(doc, child);
101
+ if (!through && c && c[skip] === true) continue;
102
+ const roomy = o.full && depth < FULL_DEPTH && o.budget.left > 0;
103
+ if (!through && !roomy && !required.has(name)) continue;
104
+ const v = gen(doc, child, o, at, depth + 1, null);
105
+ if (v !== OMIT) out[name] = v;
106
+ }
107
+ const ap = s.additionalProperties;
108
+ if (ap && typeof ap === 'object') {
109
+ const at = [...steps, { map: true }];
110
+ if (onPath(at, o.target) || (o.full && depth < FULL_DEPTH && Object.keys(out).length === 0)) {
111
+ const v = gen(doc, ap, o, at, depth + 1, null);
112
+ if (v !== OMIT) out.key = v;
113
+ }
114
+ }
115
+ if (discriminated && !(s.properties && s.properties[discriminated.property] && S.effective(doc, s.properties[discriminated.property]).enum)) {
116
+ out[discriminated.property] = discriminated.value;
117
+ }
118
+ // minProperties: pad with generic entries only when nothing else is declared.
119
+ for (let i = Object.keys(out).length; i < (s.minProperties || 0) && s.additionalProperties !== false; i++) out[`key${i}`] = 'value';
120
+ return out;
121
+ }
122
+
123
+ function genArray(doc, s, o, steps, depth) {
124
+ const at = [...steps, { items: true }];
125
+ const min = s.minItems || 0;
126
+ const max = s.maxItems === undefined ? Infinity : s.maxItems;
127
+ const n = Math.min(max, Math.max(min, o.budget.left > 0 ? 1 : 0));
128
+ const out = [];
129
+ for (let i = 0; i < n; i++) {
130
+ const v = gen(doc, s.items || {}, i === 0 ? o : { ...o, target: null }, at, depth + 1, null);
131
+ if (v === OMIT) continue;
132
+ out.push(s.uniqueItems && i > 0 ? vary(v, i) : v);
133
+ }
134
+ return out;
135
+ }
136
+
137
+ function genVariant(doc, s, variants, o, steps, depth) {
138
+ // An explicit variant on the target's path wins; otherwise o.variant picks one.
139
+ const key = s.oneOf ? 'oneOf' : 'anyOf';
140
+ let index = o.variant % variants.length;
141
+ for (let i = 0; i < variants.length; i++) {
142
+ if (onPath([...steps, { variant: key, index: i }], o.target)) { index = i; break; }
143
+ }
144
+ const variant = variants[index];
145
+ const disc = s.discriminator && s.discriminator.propertyName
146
+ ? { property: s.discriminator.propertyName, value: discriminatorValue(s.discriminator, variant) }
147
+ : null;
148
+ let v = gen(doc, variant, o, [...steps, { variant: key, index }], depth + 1, disc);
149
+ if (v === OMIT) return OMIT;
150
+ // Properties declared next to oneOf apply to every branch.
151
+ if (s.properties && v && typeof v === 'object' && !Array.isArray(v)) {
152
+ const base = genObject(doc, { ...s, oneOf: undefined, anyOf: undefined }, o, steps, depth, null);
153
+ v = { ...base, ...v };
154
+ }
155
+ return v;
156
+ }
157
+
158
+ function discriminatorValue(disc, variant) {
159
+ const ref = variant && variant.$ref;
160
+ if (disc.mapping) {
161
+ for (const [value, target] of Object.entries(disc.mapping)) {
162
+ if (target === ref || (ref && ref.endsWith(`/${target}`))) return value;
163
+ }
164
+ }
165
+ return ref ? ref.split('/').pop() : 'value';
166
+ }
167
+
168
+ // ─── scalars ────────────────────────────────────────────────────────────────
169
+
170
+ function number(s, integer) {
171
+ let lo = typeof s.minimum === 'number' ? s.minimum : -Infinity;
172
+ let hi = typeof s.maximum === 'number' ? s.maximum : Infinity;
173
+ const step = integer ? 1 : 0.5;
174
+ if (s.exclusiveMinimum === true) lo += step; else if (typeof s.exclusiveMinimum === 'number') lo = Math.max(lo, s.exclusiveMinimum + step);
175
+ if (s.exclusiveMaximum === true) hi -= step; else if (typeof s.exclusiveMaximum === 'number') hi = Math.min(hi, s.exclusiveMaximum - step);
176
+ let v = integer ? 1 : 1.5;
177
+ if (v < lo) v = integer ? Math.ceil(lo) : lo;
178
+ if (v > hi) v = integer ? Math.floor(hi) : hi;
179
+ if (typeof s.multipleOf === 'number' && s.multipleOf > 0) {
180
+ v = Math.ceil(v / s.multipleOf) * s.multipleOf;
181
+ if (v > hi) v = Math.floor(hi / s.multipleOf) * s.multipleOf;
182
+ v = Number(v.toFixed(10));
183
+ }
184
+ return v;
185
+ }
186
+
187
+ function string(s, base = null) {
188
+ const min = s.minLength || 0;
189
+ const max = s.maxLength === undefined ? Infinity : s.maxLength;
190
+ if (s.pattern) {
191
+ const m = fromPattern(s.pattern, { min, max });
192
+ if (m !== null) return m;
193
+ }
194
+ return ofLength(base !== null ? base : (FORMATS[s.format] || 'abc'), s.format, min, max);
195
+ }
196
+
197
+ /**
198
+ * Lengthens or shortens a string to fit [min, max] without breaking its
199
+ * format: padding goes where the format allows it (a URI's path, an email's
200
+ * local part), not at the end of a domain.
201
+ */
202
+ function ofLength(v, format, min, max) {
203
+ if (v.length >= min && v.length <= max) return v;
204
+ if (v.length > max) return v.slice(0, max);
205
+ const pad = 'x'.repeat(min - v.length);
206
+ if (format === 'email' || format === 'idn-email') return pad + v;
207
+ if (format === 'uri' || format === 'url' || format === 'uri-reference') return v + pad;
208
+ if (format === 'hostname' || format === 'idn-hostname') return `${pad.replace(/x{60}/g, 'x'.repeat(59) + '.')}${v}`;
209
+ if (format && FORMATS[format]) return v; // fixed-length formats (date, uuid…): leave it to validation
210
+ return v + pad;
211
+ }
212
+
213
+ // ─── strings from a regular expression ─────────────────────────────────────
214
+
215
+ /**
216
+ * A short string matching `pattern`, within [min, max] length, or null.
217
+ * Covers what API specs use: literals, escapes (\d \w \s), classes, groups,
218
+ * alternation, quantifiers and anchors. Lookarounds and backreferences → null.
219
+ */
220
+ function fromPattern(pattern, { min = 0, max = Infinity } = {}) {
221
+ let ast;
222
+ try { ast = parseRegex(pattern); } catch { return null; }
223
+ let re;
224
+ try { re = new RegExp(pattern, 'u'); } catch { try { re = new RegExp(pattern); } catch { return null; } }
225
+ const shortest = emit(ast.node, { extra: 0 });
226
+ if (shortest === null || shortest.length > max) return null;
227
+ // Spend exactly the characters still needed on the pattern's repeats.
228
+ let s = shortest.length >= min ? shortest : emit(ast.node, { extra: min - shortest.length });
229
+ if (s === null) return null;
230
+ if (s.length < min) {
231
+ // An unanchored pattern matches inside a longer string.
232
+ if (!ast.end) s += 'x'.repeat(min - s.length);
233
+ else if (!ast.start) s = 'x'.repeat(min - s.length) + s;
234
+ }
235
+ return s.length >= min && s.length <= max && re.test(s) ? s : null;
236
+ }
237
+
238
+ function parseRegex(src) {
239
+ let i = 0;
240
+ const start = src[0] === '^';
241
+ if (start) i = 1;
242
+ const peek = () => src[i];
243
+ const end = src.length > i && src[src.length - 1] === '$' && src[src.length - 2] !== '\\';
244
+ const stop = end ? src.length - 1 : src.length;
245
+
246
+ function alternation() {
247
+ const branches = [sequence()];
248
+ while (i < stop && peek() === '|') { i++; branches.push(sequence()); }
249
+ return branches.length === 1 ? branches[0] : { alt: branches };
250
+ }
251
+ function sequence() {
252
+ const items = [];
253
+ while (i < stop && peek() !== '|' && peek() !== ')') {
254
+ let atom = atomNode();
255
+ atom = quantified(atom);
256
+ items.push(atom);
257
+ }
258
+ return { seq: items };
259
+ }
260
+ function atomNode() {
261
+ const c = src[i++];
262
+ if (c === '(') {
263
+ if (src[i] === '?') {
264
+ if (src[i + 1] === ':') i += 2;
265
+ else if (src[i + 1] === '<' && src[i + 2] !== '=' && src[i + 2] !== '!') { i = src.indexOf('>', i) + 1; } else throw new Error('lookaround');
266
+ }
267
+ const inner = alternation();
268
+ if (src[i++] !== ')') throw new Error('unbalanced');
269
+ return inner;
270
+ }
271
+ if (c === '[') return charClass();
272
+ if (c === '\\') return escape();
273
+ if (c === '.') return { chars: 'a' };
274
+ if (c === '^' || c === '$') return { lit: '' };
275
+ return { lit: c };
276
+ }
277
+ function escape() {
278
+ const c = src[i++];
279
+ if (c === 'd') return { chars: '1' };
280
+ if (c === 'w') return { chars: 'a' };
281
+ if (c === 's') return { chars: ' ' };
282
+ if (c === 'D' || c === 'W' || c === 'S') return { chars: c === 'S' ? 'a' : '-' };
283
+ if (c === 'b' || c === 'B') return { lit: '' };
284
+ if (/[1-9]/.test(c)) throw new Error('backreference');
285
+ if (c === 'u' && /^[0-9a-fA-F]{4}$/.test(src.slice(i, i + 4))) { const ch = String.fromCharCode(parseInt(src.slice(i, i + 4), 16)); i += 4; return { lit: ch }; }
286
+ if (c === 'x' && /^[0-9a-fA-F]{2}$/.test(src.slice(i, i + 2))) { const ch = String.fromCharCode(parseInt(src.slice(i, i + 2), 16)); i += 2; return { lit: ch }; }
287
+ if (c === 'n') return { lit: '\n' };
288
+ if (c === 't') return { lit: '\t' };
289
+ return { lit: c };
290
+ }
291
+ function charClass() {
292
+ let negate = false;
293
+ if (src[i] === '^') { negate = true; i++; }
294
+ const members = [];
295
+ let first = true;
296
+ while (i < src.length && (src[i] !== ']' || first)) {
297
+ first = false;
298
+ let c = src[i++];
299
+ if (c === '\\') {
300
+ const e = src[i++];
301
+ c = e === 'd' ? '1' : e === 'w' ? 'a' : e === 's' ? ' ' : e;
302
+ members.push([c, c]);
303
+ continue;
304
+ }
305
+ if (src[i] === '-' && src[i + 1] && src[i + 1] !== ']') {
306
+ let hi = src[i + 1];
307
+ i += 2;
308
+ if (hi === '\\') hi = src[i++];
309
+ members.push([c, hi]);
310
+ } else members.push([c, c]);
311
+ }
312
+ i++; // ]
313
+ if (!negate) {
314
+ // Prefer a letter or digit when the class allows one — reads better.
315
+ for (const pref of ['a', 'A', '1', 'x']) if (members.some(([lo, hi]) => pref >= lo && pref <= hi)) return { chars: pref };
316
+ return { chars: members.length ? members[0][0] : 'a' };
317
+ }
318
+ for (const cand of ['a', '1', 'x', 'Z', '_', '-', ' ']) {
319
+ if (!members.some(([lo, hi]) => cand >= lo && cand <= hi)) return { chars: cand };
320
+ }
321
+ return { chars: '~' };
322
+ }
323
+ function quantified(atom) {
324
+ const c = src[i];
325
+ let q = null;
326
+ if (c === '*') q = [0, Infinity];
327
+ else if (c === '+') q = [1, Infinity];
328
+ else if (c === '?') q = [0, 1];
329
+ else if (c === '{') {
330
+ const m = /^\{(\d+)(,(\d*))?\}/.exec(src.slice(i));
331
+ if (m) { q = [Number(m[1]), m[2] ? (m[3] ? Number(m[3]) : Infinity) : Number(m[1])]; i += m[0].length - 1; }
332
+ }
333
+ if (!q) return atom;
334
+ i++;
335
+ if (src[i] === '?' || src[i] === '+') i++; // lazy / possessive
336
+ return { repeat: atom, min: q[0], max: q[1] };
337
+ }
338
+
339
+ const node = alternation();
340
+ if (i !== stop) throw new Error('unparsed');
341
+ return { node, start, end };
342
+ }
343
+
344
+ /** The shortest match, with `state.extra` more characters spent on repeats left to right. */
345
+ function emit(n, state) {
346
+ if (n.lit !== undefined) return n.lit;
347
+ if (n.chars !== undefined) return n.chars;
348
+ if (n.seq) {
349
+ let out = '';
350
+ for (const x of n.seq) { const s = emit(x, state); if (s === null) return null; out += s; }
351
+ return out;
352
+ }
353
+ if (n.alt) return emit(n.alt[0], state);
354
+ if (n.repeat) {
355
+ const unit = emit(n.repeat, { extra: 0 });
356
+ if (unit === null) return null;
357
+ let count = n.min;
358
+ if (state.extra > 0 && unit.length > 0 && n.max > n.min) {
359
+ const more = Math.min(n.max - n.min, Math.ceil(state.extra / unit.length));
360
+ count += more;
361
+ state.extra -= more * unit.length;
362
+ }
363
+ let out = '';
364
+ for (let k = 0; k < count; k++) { const s = emit(n.repeat, state); if (s === null) return null; out += s; }
365
+ return out;
366
+ }
367
+ return '';
368
+ }
369
+
370
+ // ─── helpers ────────────────────────────────────────────────────────────────
371
+
372
+ function sameSteps(a, b) {
373
+ if (a.length !== b.length) return false;
374
+ return a.every((s, i) => stepKey(s) === stepKey(b[i]));
375
+ }
376
+
377
+ function stepKey(s) {
378
+ if (s.prop !== undefined) return `p:${s.prop}`;
379
+ if (s.items) return 'i';
380
+ if (s.map) return 'm';
381
+ return `v:${s.variant}:${s.index}`;
382
+ }
383
+
384
+ /** True when `steps` is a prefix of (or equal to) the target's steps. */
385
+ function onPath(steps, target) {
386
+ if (!target || steps.length > target.steps.length) return false;
387
+ return steps.every((s, i) => stepKey(s) === stepKey(target.steps[i]));
388
+ }
389
+
390
+ function vary(v, i) {
391
+ if (typeof v === 'string') return `${v}${i}`;
392
+ if (typeof v === 'number') return v + i;
393
+ return v;
394
+ }
395
+
396
+ function clone(v) {
397
+ return v === undefined || v === OMIT || v === null || typeof v !== 'object' ? v : JSON.parse(JSON.stringify(v));
398
+ }
399
+
400
+ module.exports = { generate, fromPattern, string, ofLength, number, OMIT, sameSteps, stepKey, FORMATS };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const S = require('./schema');
4
+
5
+ /**
6
+ * Is any ajv error about the location `steps` names? At it, under it, the
7
+ * parent reporting it missing or unexpected, or a oneOf/anyOf above it.
8
+ */
9
+ function relatesTo(errors, steps) {
10
+ const at = S.instancePath(steps);
11
+ const last = steps[steps.length - 1];
12
+ const parent = S.instancePath(steps.slice(0, -1));
13
+ return errors.some((e) => {
14
+ if (e.path === at || e.path.startsWith(at + '/')) return true;
15
+ if (last && last.prop !== undefined && e.path === parent) {
16
+ if (e.keyword === 'required' && e.params.missingProperty === last.prop) return true;
17
+ if (e.keyword === 'additionalProperties' && e.params.additionalProperty === last.prop) return true;
18
+ }
19
+ return (e.keyword === 'oneOf' || e.keyword === 'anyOf') && at.startsWith(e.path) && at !== e.path;
20
+ });
21
+ }
22
+
23
+ module.exports = { relatesTo };
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Witnesses for people: terminal lines, a curl command to reproduce one, and
5
+ * GitHub-flavoured Markdown for job summaries.
6
+ */
7
+
8
+ const chalk = require('chalk');
9
+ const L = require('../fix/locate');
10
+ const S = require('./schema');
11
+
12
+ const BADGE = {
13
+ proven: () => chalk.green.bold('PROOF'),
14
+ example: () => chalk.yellow.bold('EXAMPLE'),
15
+ compatible: () => chalk.cyan.bold('COMPATIBLE'),
16
+ unproven: () => chalk.gray.bold('NO PROOF'),
17
+ };
18
+
19
+ const RUN_MARK = {
20
+ confirmed: () => chalk.green('✔ confirmed'),
21
+ 'not-reproduced': () => chalk.red('✖ not reproduced'),
22
+ inconclusive: () => chalk.yellow('? inconclusive'),
23
+ skipped: () => chalk.gray('– skipped'),
24
+ error: () => chalk.red('✖ error'),
25
+ };
26
+
27
+ const MAX_JSON = 240;
28
+ const W = 22;
29
+
30
+ /** A curl command for a rendered request. `base` defaults to $BASE_URL. */
31
+ function curl(req, base = null) {
32
+ const parts = ['curl'];
33
+ if (req.method !== 'GET') parts.push('-X', req.method);
34
+ parts.push(base ? shellQuote(base + req.path) : `"$BASE_URL${dq(req.path)}"`);
35
+ for (const [k, v] of Object.entries(req.headers || {})) parts.push('-H', shellQuote(`${k}: ${v}`));
36
+ if (req.bodyText) parts.push('-d', shellQuote(req.bodyText));
37
+ else if (req.body !== null && req.body !== undefined) parts.push('-d', shellQuote(JSON.stringify(req.body)));
38
+ return parts.join(' ');
39
+ }
40
+
41
+ function shellQuote(s) {
42
+ return `'${String(s).replace(/'/g, `'\\''`)}'`;
43
+ }
44
+
45
+ function dq(s) {
46
+ return String(s).replace(/(["\\$`])/g, '\\$1');
47
+ }
48
+
49
+ function json(v, max = MAX_JSON) {
50
+ const s = JSON.stringify(v);
51
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
52
+ }
53
+
54
+ /**
55
+ * A long body is shown around the change, not from the top: the object that
56
+ * holds the changed field, labelled with where it sits ("rules[0]").
57
+ */
58
+ function excerpt(body, p, max = MAX_JSON) {
59
+ const full = JSON.stringify(body);
60
+ if (full.length <= max || !p.diff || !p.diff.field) return { text: json(body, max), where: null };
61
+ const parsed = L.parseField(p.diff.field);
62
+ if (!parsed || parsed.steps.length === 0) return { text: json(body, max), where: null };
63
+ for (let n = parsed.steps.length - 1; n >= 0; n--) {
64
+ const ptr = S.instancePath(parsed.steps.slice(0, n));
65
+ const v = at(body, ptr);
66
+ if (v === undefined || v === null || typeof v !== 'object') continue;
67
+ const where = ptr.replace(/\/(\d+)(?=\/|$)/g, '[$1]').replace(/^\//, '').replace(/\//g, '.');
68
+ return { text: json(v, max), where: where || null };
69
+ }
70
+ return { text: json(body, max), where: null };
71
+ }
72
+
73
+ function removedField(p) {
74
+ const parsed = p.diff && p.diff.field ? L.parseField(p.diff.field) : null;
75
+ if (!parsed || !parsed.steps.length) return null;
76
+ const last = parsed.steps[parsed.steps.length - 1];
77
+ if (last.prop === undefined) return null;
78
+ const ptr = S.instancePath(parsed.steps);
79
+ const human = (x) => x.replace(/\/(\d+)(?=\/|$)/g, '[$1]').replace(/^\//, '').replace(/\//g, '.');
80
+ return { ptr, path: human(ptr), parent: human(S.instancePath(parsed.steps.slice(0, -1))), leaf: last.prop };
81
+ }
82
+
83
+ function at(body, ptr) {
84
+ let cur = body;
85
+ for (const k of ptr.split('/').slice(1)) {
86
+ if (cur === null || typeof cur !== 'object') return undefined;
87
+ cur = cur[k.replace(/~1/g, '/').replace(/~0/g, '~')];
88
+ }
89
+ return cur;
90
+ }
91
+
92
+ /** The lines under one change in a terminal report (indented by `pad`). */
93
+ function lines(p, { pad = ' ', base = null, showCurl = true } = {}) {
94
+ const out = [];
95
+ if (!p) { out.push(chalk.gray(`${pad}no proof: this change type isn't covered`)); return out; }
96
+ const label = (s) => chalk.gray(s.padEnd(W));
97
+ if (p.status === 'proven' || p.status === 'example') {
98
+ if (p.side === 'response' && p.response) {
99
+ out.push(`${pad}${label('request')}${p.request.method} ${p.request.path}${p.request.body !== null ? ` ${json(p.request.body, 120)}` : ''}`);
100
+ const show = (b) => { const e = excerpt(b, p); return `${e.where ? chalk.gray(`${e.where}: `) : ''}${e.text}`; };
101
+ const gone = p.status === 'example' ? removedField(p) : null;
102
+ if (gone) {
103
+ // A removed field: show the field, not the (long) object around it.
104
+ if (p.before) out.push(`${pad}${label('old spec sent')}${gone.path} = ${json(at(p.before.body, gone.ptr), 160)}`);
105
+ out.push(`${pad}${label('new spec sends')}${gone.parent ? `${gone.parent} ` : 'a body '}without "${gone.leaf}" ${chalk.gray(`(${p.response.status})`)}`);
106
+ } else {
107
+ if (p.before) out.push(`${pad}${label('old spec sent')}${show(p.before.body)}`);
108
+ out.push(`${pad}${label(p.status === 'proven' ? 'new spec allows' : 'new spec sends')}${show(p.response.body)} ${chalk.gray(`(${p.response.status})`)}`);
109
+ }
110
+ } else if (p.request) {
111
+ const e = p.request.body !== null ? excerpt(p.request.body, p) : null;
112
+ const body = e ? ` ${e.where ? chalk.gray(`${e.where}: `) : ''}${e.text}` : '';
113
+ out.push(`${pad}${label(p.status === 'proven' ? 'worked before' : 'request')}${p.request.method} ${p.request.path}${body}`);
114
+ }
115
+ if (p.status === 'proven') {
116
+ const verb = p.side === 'response' ? 'old clients reject it' : 'fails now';
117
+ p.why.forEach((w, i) => out.push(`${pad}${label(i === 0 ? verb : '')}${w}`));
118
+ if (p.also.length) out.push(chalk.gray(`${pad}${''.padEnd(W)}(also, from other changes in this release: ${p.also.join('; ')})`));
119
+ } else {
120
+ out.push(chalk.yellow(`${pad}${p.reason}`));
121
+ }
122
+ if (p.endpoints > 1) {
123
+ out.push(chalk.gray(`${pad}${''.padEnd(W)}${p.status === 'proven' ? `proven at ${p.provenOn} of ${p.endpoints} places` : `${p.endpoints} places`}; showing one`));
124
+ }
125
+ if (showCurl && p.request) out.push(chalk.gray(`${pad}${label('reproduce')}`) + chalk.cyan(curl(p.request, base)));
126
+ } else {
127
+ out.push(chalk.gray(`${pad}${p.reason}`));
128
+ }
129
+ if (p.run) out.push(`${pad}${label('on the build')}${RUN_MARK[p.run.outcome]()} ${chalk.gray(`— ${p.run.detail}`)}`);
130
+ return out;
131
+ }
132
+
133
+ function badge(p) {
134
+ return (BADGE[p ? p.status : 'unproven'] || BADGE.unproven)();
135
+ }
136
+
137
+ /** A Markdown block for one change's proof (GitHub job summary, PR comments). */
138
+ function markdown(p) {
139
+ if (!p) return '';
140
+ const out = [];
141
+ if (p.status === 'proven' || p.status === 'example') {
142
+ const gone = p.status === 'example' && p.side === 'response' ? removedField(p) : null;
143
+ if (gone && p.response) {
144
+ out.push(`Request \`${p.request.method} ${p.request.path}\` → ${p.response.status}`);
145
+ if (p.before) out.push('', `The old spec sent \`${gone.path}\`:`, '', '```json', JSON.stringify(at(p.before.body, gone.ptr), null, 2), '```');
146
+ out.push('', `The new spec sends ${gone.parent ? `\`${gone.parent}\`` : 'the body'} without it.`);
147
+ } else if (p.side === 'response' && p.response) {
148
+ out.push(`Request \`${p.request.method} ${p.request.path}\` → ${p.response.status}`);
149
+ out.push('', p.status === 'proven' ? 'The new spec allows this response:' : 'The new spec sends:', '', '```json', JSON.stringify(p.response.body, null, 2), '```');
150
+ } else if (p.request) {
151
+ out.push(p.status === 'proven' ? 'This request worked before and fails now:' : 'Request:', '', '```http', `${p.request.method} ${p.request.path}`);
152
+ for (const [k, v] of Object.entries(p.request.headers || {})) out.push(`${k}: ${v}`);
153
+ if (p.request.bodyText) out.push('', p.request.bodyText);
154
+ else if (p.request.body !== null) out.push('', JSON.stringify(p.request.body, null, 2));
155
+ out.push('```');
156
+ }
157
+ if (p.status === 'proven') {
158
+ out.push('', `${p.side === 'response' ? 'Old clients reject it' : 'Rejected by the new spec'}: ${p.why.join('; ')}`);
159
+ if (p.also.length) out.push('', `_Also, from other changes in this release: ${p.also.join('; ')}_`);
160
+ } else out.push('', p.reason);
161
+ if (p.request) out.push('', '```sh', curl(p.request), '```');
162
+ } else {
163
+ out.push(p.reason || '');
164
+ }
165
+ if (p.run) out.push('', `On the build: **${p.run.outcome}** — ${p.run.detail}`);
166
+ return out.join('\n');
167
+ }
168
+
169
+ module.exports = { curl, lines, badge, markdown, json };