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,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 };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Isolation: make an instance satisfy two schemas at once everywhere except
5
+ * one protected location.
6
+ *
7
+ * A spec change rarely comes alone — the same body may gain a required field,
8
+ * change a type and drop another field in one release. A witness built for one
9
+ * of those changes would trip over the others, and "it fails" would prove
10
+ * nothing about the change it is meant to show. So before a witness is judged,
11
+ * every other part of it is repaired until both the old and the new schema
12
+ * accept it; only the protected location is left alone. A repair that the
13
+ * accepting schema rejects is undone, so the witness stays valid on its side.
14
+ */
15
+
16
+ const S = require('./schema');
17
+ const { generate } = require('./instance');
18
+ const { relatesTo } = require('./relate');
19
+
20
+ const VALUE_KEYWORDS = new Set([
21
+ 'type', 'enum', 'const', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum',
22
+ 'multipleOf', 'minLength', 'maxLength', 'minItems', 'maxItems', 'uniqueItems', 'oneOf', 'anyOf', 'minProperties',
23
+ ]);
24
+
25
+ /**
26
+ * @param value the instance (from the accepting side, A)
27
+ * @param a { doc, schema } — must keep accepting the result
28
+ * @param b { doc, schema } — repaired towards
29
+ * @param protect diff-engine steps of the location to leave alone, or null
30
+ * @param side 'request' | 'response'
31
+ * @returns the repaired instance (unchanged when nothing could be repaired)
32
+ */
33
+ function coSatisfy(value, { a, b, protect = null, side = 'request', cfg = {} }) {
34
+ if (value === undefined || !b || !b.schema) return value;
35
+ const at = protect ? S.instancePath(protect) : null;
36
+ const isProtected = (e) => Boolean(protect) && relatesTo([e], protect);
37
+ const validA = S.validator(a.doc, a.schema, { side });
38
+ const validB = S.validator(b.doc, b.schema, { side });
39
+ let x = clone(value);
40
+ for (let pass = 0; pass < 6; pass++) {
41
+ const rb = validB(x);
42
+ if (rb.ok) return x;
43
+ let changed = false;
44
+ for (const e of rb.errors) {
45
+ if (isProtected(e)) continue;
46
+ const fix = proposal(e, b, side, cfg);
47
+ if (!fix || (at !== null && overlaps(fix.pointer, at))) continue;
48
+ const y = apply(x, fix);
49
+ if (y === undefined || same(x, y)) continue;
50
+ if (!validA(y).ok) continue;
51
+ x = y;
52
+ changed = true;
53
+ }
54
+ if (!changed) break;
55
+ }
56
+ return x;
57
+ }
58
+
59
+ function proposal(e, b, side, cfg) {
60
+ if (e.keyword === 'required' && e.params.missingProperty !== undefined) {
61
+ const pointer = `${e.path}/${esc(e.params.missingProperty)}`;
62
+ const node = S.nodeAtPointer(b.doc, b.schema, pointer);
63
+ return { op: 'set', pointer, value: node ? generate(b.doc, node, { side, ...cfg }) : 'abc' };
64
+ }
65
+ if (e.keyword === 'additionalProperties' && e.params.additionalProperty !== undefined) {
66
+ return { op: 'delete', pointer: `${e.path}/${esc(e.params.additionalProperty)}` };
67
+ }
68
+ if (VALUE_KEYWORDS.has(e.keyword)) {
69
+ const node = S.nodeAtPointer(b.doc, b.schema, e.path);
70
+ if (!node) return null;
71
+ return { op: 'set', pointer: e.path, value: generate(b.doc, node, { side, ...cfg }) };
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /** A fix may not replace the protected value, anything containing it, or anything inside it. */
77
+ function overlaps(pointer, at) {
78
+ return pointer === at || at.startsWith(pointer + '/') || pointer === '' || pointer.startsWith(at + '/');
79
+ }
80
+
81
+ function apply(x, { op, pointer, value }) {
82
+ if (pointer === '') return op === 'set' ? clone(value) : undefined;
83
+ const root = clone(x);
84
+ const parts = pointer.split('/').slice(1).map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
85
+ let cur = root;
86
+ for (const k of parts.slice(0, -1)) {
87
+ if (cur === null || typeof cur !== 'object' || !(k in cur)) return undefined;
88
+ cur = cur[k];
89
+ }
90
+ if (cur === null || typeof cur !== 'object') return undefined;
91
+ const last = parts[parts.length - 1];
92
+ if (op === 'delete') delete cur[last];
93
+ else cur[last] = clone(value);
94
+ return root;
95
+ }
96
+
97
+ function esc(s) {
98
+ return String(s).replace(/~/g, '~0').replace(/\//g, '~1');
99
+ }
100
+
101
+ function clone(v) {
102
+ return v === undefined || v === null || typeof v !== 'object' ? v : JSON.parse(JSON.stringify(v));
103
+ }
104
+
105
+ function same(a, b) {
106
+ return JSON.stringify(a) === JSON.stringify(b);
107
+ }
108
+
109
+ module.exports = { coSatisfy };
@@ -0,0 +1,261 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Schema plumbing for witnesses: following $refs inside a raw (un-normalized)
5
+ * spec document, flattening allOf, walking the diff engine's field steps, and
6
+ * validating instances with ajv against the document's own schemas.
7
+ *
8
+ * Validation runs against the spec as written — $refs stay $refs, resolved by
9
+ * ajv against the document's components — so a witness is checked against the
10
+ * real contract, not a simplified copy of it.
11
+ */
12
+
13
+ const Ajv = require('ajv').default;
14
+ const addFormats = require('ajv-formats');
15
+ const L = require('../fix/locate');
16
+
17
+ // inlineRefs: false compiles each referenced component once, as its own
18
+ // function, instead of inlining it into every schema that mentions it — on a
19
+ // spec like Stripe's (thousands of mutually-referencing schemas) the difference
20
+ // between seconds and hours.
21
+ const OPTIONS = { strict: false, allErrors: true, validateFormats: true, logger: false, inlineRefs: false };
22
+ const bodyAjv = addFormats(new Ajv({ ...OPTIONS, coerceTypes: false }));
23
+ // Parameters arrive as strings ("?limit=10"); servers parse them into the
24
+ // declared type, so a parameter validates the way a server would read it.
25
+ const paramAjv = addFormats(new Ajv({ ...OPTIONS, coerceTypes: 'array' }));
26
+
27
+ const ANNOTATIONS = new Set(['example', 'examples', 'xml', 'discriminator', 'readOnly', 'writeOnly', 'deprecated', 'externalDocs', 'nullable', '$schema', '$id', 'x-nullable']);
28
+
29
+ function deref(doc, node, depth = 0) {
30
+ let cur = node;
31
+ for (let i = 0; cur && typeof cur === 'object' && typeof cur.$ref === 'string' && i < 20; i++) {
32
+ const ptr = L.refToPtr(cur.$ref);
33
+ if (!ptr) return null; // external ref
34
+ cur = L.get(doc, ptr);
35
+ }
36
+ return cur && typeof cur === 'object' ? cur : null;
37
+ }
38
+
39
+ /**
40
+ * The schema with $refs followed and allOf merged into one node — the shape a
41
+ * generator or a reader cares about. Constraints of every part are kept (the
42
+ * last part wins on a conflict, which ajv's own check then catches).
43
+ */
44
+ function effective(doc, node, depth = 0) {
45
+ const s = deref(doc, node);
46
+ if (!s || depth > 12) return s;
47
+ if (!Array.isArray(s.allOf)) return s;
48
+ const out = { ...s, properties: { ...(s.properties || {}) }, required: [...(s.required || [])] };
49
+ delete out.allOf;
50
+ for (const part of s.allOf) {
51
+ const p = effective(doc, part, depth + 1);
52
+ if (!p) continue;
53
+ for (const [k, v] of Object.entries(p)) {
54
+ if (k === 'properties') Object.assign(out.properties, v);
55
+ else if (k === 'required') out.required.push(...v);
56
+ else if (!(k in out) || k === 'type') out[k] = v;
57
+ }
58
+ }
59
+ if (Object.keys(out.properties).length === 0) delete out.properties;
60
+ if (out.required.length === 0) delete out.required;
61
+ return out;
62
+ }
63
+
64
+ /** The type a schema declares, ignoring "null" (OpenAPI 3.1 nullable). */
65
+ function typeOf(s) {
66
+ if (!s) return null;
67
+ if (Array.isArray(s.type)) return s.type.find((t) => t !== 'null') || null;
68
+ if (s.type) return s.type;
69
+ if (s.properties || s.additionalProperties) return 'object';
70
+ if (s.items) return 'array';
71
+ return null;
72
+ }
73
+
74
+ function nullable(s) {
75
+ return Boolean(s && (s.nullable === true || s['x-nullable'] === true || (Array.isArray(s.type) && s.type.includes('null'))));
76
+ }
77
+
78
+ /**
79
+ * Walks diff-engine steps ({prop}, {items}, {map}, {variant, index}) from a
80
+ * schema node. Returns the (un-dereferenced) node at the end, or null.
81
+ */
82
+ function nodeAt(doc, node, steps) {
83
+ let cur = node;
84
+ for (const step of steps) {
85
+ const s = effective(doc, cur);
86
+ if (!s) return null;
87
+ if (step.prop !== undefined) cur = s.properties && s.properties[step.prop];
88
+ else if (step.items) cur = s.items;
89
+ else if (step.map) cur = s.additionalProperties && typeof s.additionalProperties === 'object' ? s.additionalProperties : null;
90
+ else cur = Array.isArray(s[step.variant]) ? s[step.variant][step.index] : null;
91
+ if (!cur) return null;
92
+ }
93
+ return cur;
94
+ }
95
+
96
+ /**
97
+ * The schema node that governs the value at a JSON pointer of an instance
98
+ * ("/items/0/tag"), or null. Array indexes go to `items`, unknown keys to
99
+ * additionalProperties, and a oneOf/anyOf branch that declares the key wins.
100
+ */
101
+ function nodeAtPointer(doc, root, pointer) {
102
+ let cur = root;
103
+ for (const raw of pointer.split('/').slice(1)) {
104
+ const seg = raw.replace(/~1/g, '/').replace(/~0/g, '~');
105
+ const s = effective(doc, cur);
106
+ if (!s) return null;
107
+ if (s.properties && s.properties[seg]) { cur = s.properties[seg]; continue; }
108
+ if (/^\d+$/.test(seg) && s.items) { cur = s.items; continue; }
109
+ if (s.additionalProperties && typeof s.additionalProperties === 'object') { cur = s.additionalProperties; continue; }
110
+ const branch = (s.oneOf || s.anyOf || []).map((v) => effective(doc, v)).find((v) => v && v.properties && v.properties[seg]);
111
+ if (!branch) return null;
112
+ cur = branch.properties[seg];
113
+ }
114
+ return cur;
115
+ }
116
+
117
+ /** Steps → the JSON pointer of the value they name in an instance ("/items/0/tag"). */
118
+ function instancePath(steps) {
119
+ let p = '';
120
+ for (const s of steps) {
121
+ if (s.prop !== undefined) p += '/' + String(s.prop).replace(/~/g, '~0').replace(/\//g, '~1');
122
+ else if (s.items) p += '/0';
123
+ else if (s.map) p += '/key';
124
+ }
125
+ return p;
126
+ }
127
+
128
+ // ─── OpenAPI → JSON Schema ──────────────────────────────────────────────────
129
+
130
+ /**
131
+ * Rewrites OpenAPI-isms so ajv validates what the spec means:
132
+ * nullable / x-nullable → type also allows null
133
+ * exclusiveMinimum: true (3.0) → JSON Schema's numeric form
134
+ * readOnly properties → not required in a request
135
+ * writeOnly properties → not required in a response
136
+ * annotations, $schema, $id → dropped
137
+ */
138
+ function convert(doc, node, side, depth = 0, base = '') {
139
+ if (node === null || typeof node !== 'object' || depth > 200) return node;
140
+ if (Array.isArray(node)) return node.map((n) => convert(doc, n, side, depth + 1, base));
141
+
142
+ const out = {};
143
+ for (const [k, v] of Object.entries(node)) {
144
+ if (ANNOTATIONS.has(k) || k.startsWith('x-')) continue;
145
+ if (k === 'properties' && v && typeof v === 'object') {
146
+ out.properties = {};
147
+ for (const [name, p] of Object.entries(v)) out.properties[name] = convert(doc, p, side, depth + 1, base);
148
+ continue;
149
+ }
150
+ if (k === 'type' && v === 'file') continue; // Swagger 2.0 upload
151
+ if (k === '$ref' && typeof v === 'string' && base && v.startsWith('#/')) { out.$ref = base + v; continue; }
152
+ out[k] = convert(doc, v, side, depth + 1, base);
153
+ }
154
+
155
+ if (nullable(node) && out.type && !Array.isArray(out.type)) out.type = [out.type, 'null'];
156
+ if (nullable(node) && Array.isArray(out.enum) && !out.enum.includes(null)) out.enum = [...out.enum, null];
157
+ for (const [ex, bound] of [['exclusiveMinimum', 'minimum'], ['exclusiveMaximum', 'maximum']]) {
158
+ if (out[ex] === true && typeof out[bound] === 'number') { out[ex] = out[bound]; delete out[bound]; } else if (typeof out[ex] === 'boolean') delete out[ex];
159
+ }
160
+ if (Array.isArray(node.required) && node.properties) {
161
+ const skip = side === 'request' ? 'readOnly' : 'writeOnly';
162
+ out.required = node.required.filter((name) => {
163
+ const p = deref(doc, node.properties[name]);
164
+ return !(p && p[skip] === true);
165
+ });
166
+ }
167
+ return out;
168
+ }
169
+
170
+ // Each document's reusable schemas are registered once per ajv instance and
171
+ // side, under an id of their own; a validator's $refs point there.
172
+ let docSeq = 0;
173
+ const docIds = new WeakMap();
174
+ const registered = new WeakMap();
175
+
176
+ function docBase(ajv, doc, side) {
177
+ let id = docIds.get(doc);
178
+ if (!id) { id = `specshield://doc/${++docSeq}`; docIds.set(doc, id); }
179
+ const uri = `${id}/${side}`;
180
+ let set = registered.get(ajv);
181
+ if (!set) { set = new Set(); registered.set(ajv, set); }
182
+ if (!set.has(uri)) {
183
+ ajv.addSchema({
184
+ $id: uri,
185
+ components: { schemas: convert(doc, (doc.components && doc.components.schemas) || {}, side) },
186
+ definitions: convert(doc, doc.definitions || {}, side),
187
+ });
188
+ set.add(uri);
189
+ }
190
+ return uri;
191
+ }
192
+
193
+ const compiled = { body: new WeakMap(), param: new WeakMap() };
194
+
195
+ /**
196
+ * A validator for `schema` (a node of `doc`). `kind` 'param' parses string
197
+ * values the way a server reads a query/path/header parameter.
198
+ * Returns (value) → { ok, errors: [{ path, keyword, message, params }] }.
199
+ */
200
+ function validator(doc, schema, { side = 'request', kind = 'body' } = {}) {
201
+ if (!schema || typeof schema !== 'object') return () => ({ ok: true, errors: [] });
202
+ const cache = compiled[kind];
203
+ let bySide = cache.get(schema);
204
+ if (!bySide) { bySide = {}; cache.set(schema, bySide); }
205
+ if (!bySide[side]) {
206
+ let fn;
207
+ try {
208
+ const ajv = kind === 'param' ? paramAjv : bodyAjv;
209
+ fn = ajv.compile(convert(doc, schema, side, 0, docBase(ajv, doc, side)));
210
+ } catch (err) {
211
+ const message = `the spec's schema can't be compiled: ${err.message}`;
212
+ fn = null;
213
+ bySide[side] = () => ({ ok: false, invalidSchema: true, errors: [{ path: '', keyword: 'schema', message, params: {} }] });
214
+ }
215
+ if (fn) {
216
+ bySide[side] = (value) => {
217
+ const copy = value === undefined ? undefined : JSON.parse(JSON.stringify(value));
218
+ if (fn(copy)) return { ok: true, errors: [] };
219
+ return { ok: false, errors: dedupe((fn.errors || []).map((e) => ({ path: e.instancePath || '', keyword: e.keyword, message: e.message, params: e.params || {}, schemaPath: e.schemaPath || '' }))) };
220
+ };
221
+ }
222
+ }
223
+ return bySide[side];
224
+ }
225
+
226
+ /**
227
+ * ajv reports every failed branch of a oneOf/anyOf next to the union's own
228
+ * error. Keep the union's error and drop its branches' at the same place; keep
229
+ * each remaining distinct message once.
230
+ */
231
+ function dedupe(errors) {
232
+ // ajv's schemaPath restarts inside a $ref'd branch, so match by instance
233
+ // location: anything at or below a failed union is that union's detail.
234
+ const unions = errors.filter((e) => e.keyword === 'oneOf' || e.keyword === 'anyOf');
235
+ const inBranch = (e) => unions.some((u) => e.path === u.path || e.path.startsWith(`${u.path}/`));
236
+ const seen = new Set();
237
+ const out = [];
238
+ for (const e of errors) {
239
+ if (e.keyword === 'allOf' || e.keyword === 'if') continue;
240
+ if (e.keyword !== 'oneOf' && e.keyword !== 'anyOf' && inBranch(e)) continue;
241
+ const key = `${e.path}|${e.keyword}|${e.message}`;
242
+ if (!seen.has(key)) { seen.add(key); out.push(e); }
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /** "/items/0/tag must be integer" — an ajv error the way a person reads it. */
248
+ function describeError(e, root = 'body') {
249
+ const where = e.path ? `${root}${e.path.replace(/\/(\d+)(?=\/|$)/g, '[$1]').replace(/\//g, '.')}` : root;
250
+ if (e.keyword === 'required') return `${where} is missing required field "${e.params.missingProperty}"`;
251
+ if (e.keyword === 'enum') return `${where} must be one of ${JSON.stringify(e.params.allowedValues)}`;
252
+ if (e.keyword === 'additionalProperties') return `${where} has a field the spec doesn't allow: "${e.params.additionalProperty}"`;
253
+ if (e.keyword === 'type') return `${where} must be ${e.params.type}`;
254
+ if (e.keyword === 'oneOf' || e.keyword === 'anyOf') {
255
+ return e.params && Array.isArray(e.params.passingSchemas) ? `${where} matches more than one allowed form` : `${where} matches none of the allowed forms`;
256
+ }
257
+ if (e.keyword === 'schema') return e.message;
258
+ return `${where} ${e.message}`;
259
+ }
260
+
261
+ module.exports = { deref, effective, typeOf, nullable, nodeAt, nodeAtPointer, instancePath, convert, validator, describeError };