specshield 3.5.0 → 3.5.2
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 +61 -0
- package/README.md +114 -2
- package/package.json +1 -1
- package/src/cli.js +4 -0
- package/src/commands/gate.js +42 -5
- package/src/commands/prove.js +149 -0
- package/src/commands/replay.js +195 -0
- package/src/core/configLoader.js +6 -2
- package/src/core/gate/runGate.js +19 -1
- package/src/core/prove/contract.js +241 -0
- package/src/core/prove/execute.js +135 -0
- package/src/core/prove/http.js +104 -0
- package/src/core/prove/index.js +84 -0
- package/src/core/prove/instance.js +400 -0
- package/src/core/prove/relate.js +23 -0
- package/src/core/prove/render.js +169 -0
- package/src/core/prove/repair.js +109 -0
- package/src/core/prove/schema.js +261 -0
- package/src/core/prove/subschema.js +257 -0
- package/src/core/prove/witness.js +702 -0
- package/src/core/replay/runReplay.js +169 -0
- package/src/core/replay/shape.js +100 -0
- package/src/core/replay/traffic.js +168 -0
- package/src/core/security/diff.js +304 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* HTTP for `prove --against` and `replay`: one request at a time, raw text in
|
|
5
|
+
* and out, HTTP errors returned as data (only connection failures throw), and
|
|
6
|
+
* a guard against pointing either command at a server by accident.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const axios = require('axios');
|
|
10
|
+
const net = require('net');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A server is "local" when it can only be a developer's or a CI job's own:
|
|
14
|
+
* loopback, private ranges, link-local, single-label hosts (docker-compose
|
|
15
|
+
* service names such as "api"), and the .local/.internal/.test/.localhost
|
|
16
|
+
* suffixes. Anything else needs --allow-remote.
|
|
17
|
+
*/
|
|
18
|
+
function isLocalHost(hostname) {
|
|
19
|
+
const h = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
|
|
20
|
+
if (!h) return false;
|
|
21
|
+
if (h === 'localhost' || /\.(localhost|local|internal|test)$/.test(h)) return true;
|
|
22
|
+
if (net.isIPv4(h)) {
|
|
23
|
+
const [a, b] = h.split('.').map(Number);
|
|
24
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || a === 0;
|
|
25
|
+
}
|
|
26
|
+
if (net.isIPv6(h)) return h === '::1' || /^f[cd]/.test(h) || /^fe80:/.test(h);
|
|
27
|
+
return !h.includes('.');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Validates a base URL and returns it without a trailing slash. */
|
|
31
|
+
function targetUrl(raw, { allowRemote = false, flag = '--against' } = {}) {
|
|
32
|
+
let u;
|
|
33
|
+
try { u = new URL(raw); } catch { throw new Error(`${flag} must be a URL like http://localhost:8080 (got "${raw}")`); }
|
|
34
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error(`${flag} must be an http(s) URL`);
|
|
35
|
+
if (!allowRemote && !isLocalHost(u.hostname)) {
|
|
36
|
+
throw new Error(`${flag} ${u.host} is not a local or private host. These requests are built to fail or to change data; pass --allow-remote if this server is a test environment you own.`);
|
|
37
|
+
}
|
|
38
|
+
return u.toString().replace(/\/+$/, '');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** "Name: value" pairs from repeated --header options. */
|
|
42
|
+
function parseHeaders(list = []) {
|
|
43
|
+
const out = {};
|
|
44
|
+
for (const h of list) {
|
|
45
|
+
const i = h.indexOf(':');
|
|
46
|
+
if (i <= 0) throw new Error(`--header must look like "Name: value" (got "${h}")`);
|
|
47
|
+
out[h.slice(0, i).trim()] = h.slice(i + 1).trim();
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Sends one request. Returns { status, headers, text, json, ms }; `json` is
|
|
54
|
+
* the parsed body when it is JSON. Rejects only when no response came back.
|
|
55
|
+
*/
|
|
56
|
+
async function send({ method, url, headers = {}, body, timeoutMs = 10000 }) {
|
|
57
|
+
const started = Date.now();
|
|
58
|
+
const res = await axios.request({
|
|
59
|
+
method,
|
|
60
|
+
url,
|
|
61
|
+
headers,
|
|
62
|
+
data: body,
|
|
63
|
+
timeout: timeoutMs,
|
|
64
|
+
validateStatus: () => true,
|
|
65
|
+
maxRedirects: 0,
|
|
66
|
+
responseType: 'text',
|
|
67
|
+
transformResponse: [(d) => d],
|
|
68
|
+
transitional: { silentJSONParsing: true },
|
|
69
|
+
});
|
|
70
|
+
const text = typeof res.data === 'string' ? res.data : res.data === undefined || res.data === null ? '' : String(res.data);
|
|
71
|
+
return { status: res.status, headers: res.headers || {}, text, json: parseJson(text, res.headers), ms: Date.now() - started };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseJson(text, headers) {
|
|
75
|
+
if (!text) return undefined;
|
|
76
|
+
const type = String((headers && (headers['content-type'] || headers['Content-Type'])) || '');
|
|
77
|
+
if (!/json/i.test(type) && !/^\s*[[{]/.test(text)) return undefined;
|
|
78
|
+
try { return JSON.parse(text); } catch { return undefined; }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Runs `fn` over `items` with at most `n` in flight; keeps the order. */
|
|
82
|
+
async function pool(items, n, fn) {
|
|
83
|
+
const out = new Array(items.length);
|
|
84
|
+
let next = 0;
|
|
85
|
+
async function worker() {
|
|
86
|
+
while (next < items.length) {
|
|
87
|
+
const i = next++;
|
|
88
|
+
out[i] = await fn(items[i], i);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, worker));
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
96
|
+
|
|
97
|
+
function describeNetworkError(err) {
|
|
98
|
+
if (err.code === 'ECONNREFUSED') return 'connection refused';
|
|
99
|
+
if (err.code === 'ECONNABORTED' || /timeout/i.test(err.message)) return 'timed out';
|
|
100
|
+
if (err.code === 'ENOTFOUND') return 'host not found';
|
|
101
|
+
return err.message;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { isLocalHost, targetUrl, parseHeaders, send, pool, SAFE_METHODS, describeNetworkError };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `specshield prove` as a library: classify the changes between two specs the
|
|
5
|
+
* way `compare` and `gate` do, and attach a witness to each breaking change
|
|
6
|
+
* (and to each constraint warning, which the engine reports without ruling on).
|
|
7
|
+
*
|
|
8
|
+
* The diff engine merges a field change that a shared schema spreads across
|
|
9
|
+
* several endpoints into one finding; its proof is the strongest witness among
|
|
10
|
+
* those endpoints, with a count of how many were proven.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const { normalizeSpec } = require('../normalizeSpec');
|
|
14
|
+
const { diffSpecs } = require('../diffEngine');
|
|
15
|
+
const { classifyChanges } = require('../classifyChanges');
|
|
16
|
+
const { context, proveChange, PROVABLE } = require('./witness');
|
|
17
|
+
|
|
18
|
+
const RANK = { proven: 3, example: 2, compatible: 1, unproven: 0 };
|
|
19
|
+
|
|
20
|
+
function prove(baseDoc, targetDoc) {
|
|
21
|
+
const raw = diffSpecs(normalizeSpec(baseDoc), normalizeSpec(targetDoc));
|
|
22
|
+
const classified = classifyChanges(raw);
|
|
23
|
+
const proofs = witnesses(baseDoc, targetDoc, raw);
|
|
24
|
+
|
|
25
|
+
const breaking = classified.breakingChanges.map((c) => attach(c, proofs));
|
|
26
|
+
const warnings = classified.warnings.map((c) => attach(c, proofs));
|
|
27
|
+
return {
|
|
28
|
+
breaking,
|
|
29
|
+
warnings,
|
|
30
|
+
nonBreaking: classified.additions.length + classified.modifications.length,
|
|
31
|
+
summary: summarize(breaking),
|
|
32
|
+
proofs,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Per-endpoint witnesses for every provable raw diff. */
|
|
37
|
+
function witnesses(baseDoc, targetDoc, raw = diffSpecs(normalizeSpec(baseDoc), normalizeSpec(targetDoc))) {
|
|
38
|
+
const ctx = context(baseDoc, targetDoc);
|
|
39
|
+
return raw.filter((d) => PROVABLE.has(d.type)).map((d) => ({ diff: d, witness: proveChange(ctx, d) }));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The proof for one classified change, drawn from the per-endpoint witnesses. */
|
|
43
|
+
function proofFor(change, proofs) {
|
|
44
|
+
const eps = endpointsOf(change);
|
|
45
|
+
const merged = Array.isArray(change.affectedEndpoints) && change.affectedEndpoints.length > 1;
|
|
46
|
+
const mine = proofs.filter(({ diff: d }) => {
|
|
47
|
+
if (d.type !== change.type) return false;
|
|
48
|
+
if (eps.length === 0) return !d.method && (d.field || null) === (change.field || null);
|
|
49
|
+
if (!d.method || !eps.includes(`${d.method.toUpperCase()} ${d.path}`)) return false;
|
|
50
|
+
return merged ? leaf(d.field) === leaf(change.field) : (d.field || null) === (change.field || null);
|
|
51
|
+
});
|
|
52
|
+
if (mine.length === 0) return null;
|
|
53
|
+
const best = mine.reduce((a, b) => (RANK[b.witness.status] > RANK[a.witness.status] ? b : a));
|
|
54
|
+
return {
|
|
55
|
+
...best.witness,
|
|
56
|
+
diff: { type: best.diff.type, method: best.diff.method || null, path: best.diff.path || null, field: best.diff.field || null },
|
|
57
|
+
endpoints: mine.length,
|
|
58
|
+
provenOn: mine.filter((p) => p.witness.status === 'proven').length,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function attach(change, proofs) {
|
|
63
|
+
return { ...change, proof: proofFor(change, proofs) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function summarize(changes) {
|
|
67
|
+
const out = { total: changes.length, proven: 0, example: 0, compatible: 0, unproven: 0 };
|
|
68
|
+
for (const c of changes) out[c.proof ? c.proof.status : 'unproven']++;
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function endpointsOf(c) {
|
|
73
|
+
if (Array.isArray(c.affectedEndpoints) && c.affectedEndpoints.length) return c.affectedEndpoints;
|
|
74
|
+
return c.method && c.path ? [`${c.method.toUpperCase()} ${c.path}`] : [];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Mirrors classifyChanges' leafFieldName: "responses.200.data[items].legacy_id" → "legacy_id". */
|
|
78
|
+
function leaf(field) {
|
|
79
|
+
if (!field) return null;
|
|
80
|
+
const parts = field.split('.');
|
|
81
|
+
return parts[parts.length - 1].replace(/\[.*$/, '');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { prove, witnesses, proofFor, summarize };
|
|
@@ -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 };
|