specshield 3.4.15 → 3.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,263 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Finds things inside a RAW (un-normalized) spec document by the coordinates
5
+ * the diff engine reports — (method, path, field) — and returns JSON-pointer
6
+ * style paths (arrays of keys) into that document. Fixes are edits at those
7
+ * paths, so they land where the author would make them: inside the shared
8
+ * component a `$ref` points to, not in a copy.
9
+ *
10
+ * Field paths are the diff engine's: `requestBody.owner.name`,
11
+ * `responses.200.items[items].tag`, `responses.200.data.oneOf[1].x`,
12
+ * `requestBody.meta.<*>.label` (map values), `parameters.sort`.
13
+ */
14
+
15
+ const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];
16
+ const REF_PREFIXES = [
17
+ ['#/components/schemas/', ['components', 'schemas']],
18
+ ['#/definitions/', ['definitions']],
19
+ ['#/components/parameters/', ['components', 'parameters']],
20
+ ['#/parameters/', ['parameters']],
21
+ ['#/components/responses/', ['components', 'responses']],
22
+ ['#/responses/', ['responses']],
23
+ ['#/components/requestBodies/', ['components', 'requestBodies']],
24
+ ];
25
+
26
+ function get(doc, ptr) {
27
+ let cur = doc;
28
+ for (const k of ptr) {
29
+ if (cur === null || typeof cur !== 'object') return undefined;
30
+ cur = cur[k];
31
+ }
32
+ return cur;
33
+ }
34
+
35
+ /** "#/components/schemas/Pet" → ['components', 'schemas', 'Pet'] (also any local JSON pointer). */
36
+ function refToPtr(ref) {
37
+ if (typeof ref !== 'string' || !ref.startsWith('#/')) return null;
38
+ return ref.slice(2).split('/').map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
39
+ }
40
+
41
+ function ptrToRef(ptr) {
42
+ return '#/' + ptr.map((s) => String(s).replace(/~/g, '~0').replace(/\//g, '~1')).join('/');
43
+ }
44
+
45
+ /** Follows $ref chains from `ptr`; returns the pointer of the node that holds the content. */
46
+ function derefPtr(doc, ptr) {
47
+ let cur = ptr;
48
+ for (let i = 0; i < 20; i++) {
49
+ const node = get(doc, cur);
50
+ if (!node || typeof node !== 'object' || typeof node.$ref !== 'string') return cur;
51
+ const next = refToPtr(node.$ref);
52
+ if (!next) return cur; // external ref: stop here
53
+ cur = next;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ function operationPtr(doc, method, path) {
59
+ const ptr = ['paths', path, method.toLowerCase()];
60
+ return get(doc, ptr) ? ptr : null;
61
+ }
62
+
63
+ /** Path-level + operation-level parameters, op-level winning — like normalizeSpec. */
64
+ function parameterPtrs(doc, method, path) {
65
+ const out = new Map();
66
+ for (const base of [['paths', path, 'parameters'], ['paths', path, method.toLowerCase(), 'parameters']]) {
67
+ const list = get(doc, base);
68
+ if (!Array.isArray(list)) continue;
69
+ list.forEach((_, i) => {
70
+ const p = derefPtr(doc, [...base, i]);
71
+ const node = p && get(doc, p);
72
+ if (node && node.name && node.in) out.set(`${node.in}:${node.name}`, { ptr: p, listPtr: [...base, i], node });
73
+ });
74
+ }
75
+ return [...out.values()];
76
+ }
77
+
78
+ function findParameter(doc, method, path, name) {
79
+ return parameterPtrs(doc, method, path).find((p) => p.node.name === name && p.node.in !== 'body') || null;
80
+ }
81
+
82
+ function mediaSchemaPtr(doc, contentPtr) {
83
+ const content = get(doc, contentPtr);
84
+ if (!content || typeof content !== 'object') return null;
85
+ const type = content['application/json'] ? 'application/json' : Object.keys(content)[0];
86
+ if (!type || !content[type] || !content[type].schema) return null;
87
+ return [...contentPtr, type, 'schema'];
88
+ }
89
+
90
+ /** Pointer to the request body schema of an operation (OpenAPI 3 or Swagger 2.0 `in: body`). */
91
+ function requestSchemaPtr(doc, method, path) {
92
+ const op = operationPtr(doc, method, path);
93
+ if (!op) return null;
94
+ const rb = get(doc, [...op, 'requestBody']);
95
+ if (rb) {
96
+ const rbPtr = derefPtr(doc, [...op, 'requestBody']);
97
+ return rbPtr && mediaSchemaPtr(doc, [...rbPtr, 'content']);
98
+ }
99
+ const body = parameterPtrs(doc, method, path).find((p) => p.node.in === 'body');
100
+ return body && body.node.schema ? [...body.ptr, 'schema'] : null;
101
+ }
102
+
103
+ function responseSchemaPtr(doc, method, path, code) {
104
+ const op = operationPtr(doc, method, path);
105
+ if (!op || !get(doc, [...op, 'responses', code])) return null;
106
+ const rPtr = derefPtr(doc, [...op, 'responses', code]);
107
+ const resp = rPtr && get(doc, rPtr);
108
+ if (!resp) return null;
109
+ if (resp.schema) return [...rPtr, 'schema']; // Swagger 2.0
110
+ return resp.content ? mediaSchemaPtr(doc, [...rPtr, 'content']) : null;
111
+ }
112
+
113
+ /**
114
+ * Splits a diff field path into its root and schema steps:
115
+ * "responses.200.items[items].tag" → { side: 'response', code: '200', steps: ['items', '[items]', 'tag'] }
116
+ */
117
+ function parseField(field) {
118
+ let m = /^requestBody(.*)$/.exec(field || '');
119
+ let side;
120
+ let code = null;
121
+ let rest;
122
+ if (m) { side = 'request'; rest = m[1]; } else {
123
+ m = /^responses\.([^.[]+)(.*)$/.exec(field || '');
124
+ if (!m) return null;
125
+ side = 'response'; code = m[1]; rest = m[2];
126
+ }
127
+ const steps = [];
128
+ const re = /\.(oneOf|anyOf)\[(\d+)\]|\[items\]|\.<\*>|\.([^.[]+)/g;
129
+ let pos = 0;
130
+ let t;
131
+ while ((t = re.exec(rest)) !== null) {
132
+ if (t.index !== pos) return null;
133
+ pos = re.lastIndex;
134
+ if (t[1]) steps.push({ variant: t[1], index: Number(t[2]) });
135
+ else if (t[0] === '[items]') steps.push({ items: true });
136
+ else if (t[0] === '.<*>') steps.push({ map: true });
137
+ else steps.push({ prop: t[3] });
138
+ }
139
+ if (pos !== rest.length) return null;
140
+ return { side, code, steps };
141
+ }
142
+
143
+ function rootSchemaPtr(doc, method, path, parsed) {
144
+ return parsed.side === 'request'
145
+ ? requestSchemaPtr(doc, method, path)
146
+ : responseSchemaPtr(doc, method, path, parsed.code);
147
+ }
148
+
149
+ /**
150
+ * Finds the schema object that declares property `name`, starting at the
151
+ * schema at `ptr` and looking through $ref and allOf. Returns the pointer of
152
+ * that (dereferenced) schema object, or null.
153
+ */
154
+ function propertyOwnerPtr(doc, ptr, name, depth = 0) {
155
+ if (!ptr || depth > 12) return null;
156
+ const s = derefPtr(doc, ptr);
157
+ const node = s && get(doc, s);
158
+ if (!node || typeof node !== 'object') return null;
159
+ if (node.properties && Object.prototype.hasOwnProperty.call(node.properties, name)) return s;
160
+ for (let i = 0; i < (node.allOf || []).length; i++) {
161
+ const found = propertyOwnerPtr(doc, [...s, 'allOf', i], name, depth + 1);
162
+ if (found) return found;
163
+ }
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * Walks `steps` from the schema at `ptr`. Returns the pointer of the last
169
+ * step's schema node (not dereferenced), or null when a step is missing.
170
+ */
171
+ function walk(doc, ptr, steps) {
172
+ let cur = ptr;
173
+ for (const step of steps) {
174
+ if (!cur) return null;
175
+ if (step.prop !== undefined) {
176
+ const owner = propertyOwnerPtr(doc, cur, step.prop);
177
+ if (!owner) return null;
178
+ cur = [...owner, 'properties', step.prop];
179
+ continue;
180
+ }
181
+ const s = derefPtr(doc, cur);
182
+ const node = s && get(doc, s);
183
+ if (!node) return null;
184
+ if (step.items) cur = node.items ? [...s, 'items'] : null;
185
+ else if (step.map) cur = node.additionalProperties && typeof node.additionalProperties === 'object' ? [...s, 'additionalProperties'] : null;
186
+ else cur = Array.isArray(node[step.variant]) && node[step.variant][step.index] ? [...s, step.variant, step.index] : null;
187
+ }
188
+ return cur;
189
+ }
190
+
191
+ /** Pointer of the schema node a diff field names, in `doc`. */
192
+ function fieldPtr(doc, method, path, field) {
193
+ const parsed = parseField(field);
194
+ if (!parsed) return null;
195
+ const root = rootSchemaPtr(doc, method, path, parsed);
196
+ return root && walk(doc, root, parsed.steps);
197
+ }
198
+
199
+ /**
200
+ * For a property path (last step is a property), the pointer of the schema
201
+ * object that should hold it in `doc` — where a removed property goes back.
202
+ * Prefers the schema that declares the property's siblings.
203
+ */
204
+ function parentObjectPtr(doc, method, path, field) {
205
+ const parsed = parseField(field);
206
+ if (!parsed || parsed.steps.length === 0) return null;
207
+ const last = parsed.steps[parsed.steps.length - 1];
208
+ if (last.prop === undefined) return null;
209
+ const root = rootSchemaPtr(doc, method, path, parsed);
210
+ const parent = root && walk(doc, root, parsed.steps.slice(0, -1));
211
+ if (!parent) return null;
212
+ return objectHolder(doc, parent);
213
+ }
214
+
215
+ function objectHolder(doc, ptr, depth = 0) {
216
+ const s = derefPtr(doc, ptr);
217
+ const node = s && get(doc, s);
218
+ if (!node || typeof node !== 'object' || depth > 12) return null;
219
+ if (node.properties || !node.allOf) return s;
220
+ // allOf: the last part that declares properties is the "own" part of a
221
+ // composed schema (allOf: [$ref Base, { properties: … }]).
222
+ for (let i = node.allOf.length - 1; i >= 0; i--) {
223
+ const part = get(doc, [...s, 'allOf', i]);
224
+ if (part && !part.$ref && part.properties) return [...s, 'allOf', i];
225
+ }
226
+ return objectHolder(doc, [...s, 'allOf', node.allOf.length - 1], depth + 1);
227
+ }
228
+
229
+ /** Every local $ref target reachable from `node` in `doc`, transitively (pointers). */
230
+ function collectRefs(doc, node, out = new Map()) {
231
+ if (!node || typeof node !== 'object') return out;
232
+ if (Array.isArray(node)) { node.forEach((n) => collectRefs(doc, n, out)); return out; }
233
+ if (typeof node.$ref === 'string') {
234
+ const ptr = refToPtr(node.$ref);
235
+ if (ptr && !out.has(node.$ref)) {
236
+ out.set(node.$ref, ptr);
237
+ collectRefs(doc, get(doc, ptr), out);
238
+ }
239
+ }
240
+ for (const [k, v] of Object.entries(node)) if (k !== '$ref') collectRefs(doc, v, out);
241
+ return out;
242
+ }
243
+
244
+ /** Inlines local $refs (cycles cut at `depth`) — for validating sample payloads with ajv. */
245
+ function inline(doc, node, depth = 0) {
246
+ if (!node || typeof node !== 'object') return node;
247
+ if (Array.isArray(node)) return node.map((n) => inline(doc, n, depth));
248
+ if (typeof node.$ref === 'string') {
249
+ const ptr = refToPtr(node.$ref);
250
+ if (!ptr || depth > 8) return {};
251
+ return inline(doc, get(doc, ptr), depth + 1);
252
+ }
253
+ const out = {};
254
+ for (const [k, v] of Object.entries(node)) out[k] = inline(doc, v, depth);
255
+ return out;
256
+ }
257
+
258
+ module.exports = {
259
+ HTTP_METHODS, REF_PREFIXES,
260
+ get, refToPtr, ptrToRef, derefPtr, operationPtr, parameterPtrs, findParameter,
261
+ requestSchemaPtr, responseSchemaPtr, parseField, rootSchemaPtr, propertyOwnerPtr, walk,
262
+ fieldPtr, parentObjectPtr, collectRefs, inline,
263
+ };
@@ -0,0 +1,233 @@
1
+ 'use strict';
2
+
3
+ const YAML = require('yaml');
4
+ const jsYaml = require('js-yaml');
5
+
6
+ /**
7
+ * Edits a fix makes to the target spec, as data:
8
+ *
9
+ * { op: 'set', path, value } set a key (parents created as needed)
10
+ * { op: 'delete', path } remove a key
11
+ * { op: 'push', path, value } append to an array unless already there
12
+ * { op: 'pull', path, value } remove a value from an array (drops the array if it empties)
13
+ * { op: 'insert', path, index, value } insert into an array at index
14
+ *
15
+ * The same ops apply to a plain object (to verify the fix with the diff
16
+ * engine) and to a `yaml` Document (to write the fix into the author's file
17
+ * with comments, ordering and quoting intact).
18
+ */
19
+
20
+ function clone(v) {
21
+ return v === undefined ? undefined : JSON.parse(JSON.stringify(v, (k, x) => (x instanceof Date ? x.toISOString().slice(0, 10) : x)));
22
+ }
23
+
24
+ // ─── plain objects ──────────────────────────────────────────────────────────
25
+
26
+ function applyOps(doc, ops) {
27
+ for (const o of ops) applyOne(doc, o);
28
+ return doc;
29
+ }
30
+
31
+ function applyOne(doc, o) {
32
+ const parentPath = o.path.slice(0, -1);
33
+ const key = o.path[o.path.length - 1];
34
+ if (o.op === 'set') {
35
+ const parent = ensure(doc, parentPath);
36
+ parent[key] = clone(o.value);
37
+ return;
38
+ }
39
+ const parent = getAt(doc, parentPath);
40
+ if (!parent || typeof parent !== 'object') return;
41
+ if (o.op === 'delete') { delete parent[key]; return; }
42
+ if (o.op === 'push') {
43
+ if (!Array.isArray(parent[key])) parent[key] = [];
44
+ if (!parent[key].some((x) => same(x, o.value))) parent[key].push(clone(o.value));
45
+ return;
46
+ }
47
+ if (o.op === 'pull') {
48
+ if (!Array.isArray(parent[key])) return;
49
+ parent[key] = parent[key].filter((x) => !same(x, o.value));
50
+ if (parent[key].length === 0) delete parent[key];
51
+ return;
52
+ }
53
+ if (o.op === 'insert') {
54
+ if (!Array.isArray(parent[key])) parent[key] = [];
55
+ parent[key].splice(o.index, 0, clone(o.value));
56
+ }
57
+ }
58
+
59
+ function getAt(doc, path) {
60
+ let cur = doc;
61
+ for (const k of path) {
62
+ if (cur === null || typeof cur !== 'object') return undefined;
63
+ cur = cur[k];
64
+ }
65
+ return cur;
66
+ }
67
+
68
+ function ensure(doc, path) {
69
+ let cur = doc;
70
+ for (const k of path) {
71
+ if (cur[k] === null || typeof cur[k] !== 'object') cur[k] = {};
72
+ cur = cur[k];
73
+ }
74
+ return cur;
75
+ }
76
+
77
+ function same(a, b) {
78
+ return JSON.stringify(a) === JSON.stringify(b);
79
+ }
80
+
81
+ // ─── yaml Documents ─────────────────────────────────────────────────────────
82
+
83
+ /**
84
+ * Applies ops to the source text of a YAML or JSON spec and returns the new
85
+ * text. YAML keeps its comments and layout; JSON keeps its indentation.
86
+ */
87
+ function applyOpsToText(text, ops, { json = false } = {}) {
88
+ if (json) {
89
+ const doc = JSON.parse(text);
90
+ applyOps(doc, ops);
91
+ const indent = (/\n([ \t]+)"/.exec(text) || [, ' '])[1];
92
+ return JSON.stringify(doc, null, indent) + (text.endsWith('\n') ? '\n' : '');
93
+ }
94
+ const doc = YAML.parseDocument(text, { keepSourceTokens: false });
95
+ for (const o of ops) applyYaml(doc, o);
96
+ const singles = (text.match(/'/g) || []).length;
97
+ const doubles = (text.match(/"/g) || []).length;
98
+ const out = doc.toString({ lineWidth: 0, flowCollectionPadding: false, singleQuote: singles > doubles });
99
+ return keepOriginalLines(text, out);
100
+ }
101
+
102
+ /**
103
+ * The yaml printer re-renders lines it didn't change: comment spacing,
104
+ * padding inside [ ] and { }, quote style. Put the author's line back
105
+ * wherever the new line is the same content, so the diff shows only the fix.
106
+ * Lines are matched in order, as far ahead as the next 200 original lines.
107
+ */
108
+ function keepOriginalLines(original, rendered) {
109
+ const src = original.split('\n');
110
+ const out = rendered.split('\n');
111
+ // Indentation is structure in YAML: it must match exactly.
112
+ const norm = (l) => {
113
+ const [, indent, rest] = /^(\s*)(.*)$/.exec(l);
114
+ return indent + rest.replace(/\s+#/, ' #').replace(/\s+/g, ' ').replace(/([[{]) /g, '$1').replace(/ ([\]}])/g, '$1').replace(/"/g, "'").trimEnd();
115
+ };
116
+ const keys = src.map(norm);
117
+ let i = 0;
118
+ const result = out.map((line) => {
119
+ const n = norm(line);
120
+ for (let k = i; k < Math.min(src.length, i + 200); k++) {
121
+ if (keys[k] === n) { i = k + 1; return src[k]; }
122
+ }
123
+ return line;
124
+ });
125
+ return result.join('\n');
126
+ }
127
+
128
+ function applyYaml(doc, o) {
129
+ const parentPath = o.path.slice(0, -1);
130
+ const key = o.path[o.path.length - 1];
131
+ if (o.op === 'set') {
132
+ const parent = ensureNode(doc, parentPath);
133
+ const pair = findPair(parent, key);
134
+ const node = createNode(doc, o.value);
135
+ if (pair) pair.value = node;
136
+ else parent.add(doc.createPair(keyScalar(key), node));
137
+ return;
138
+ }
139
+ const parent = nodeAt(doc, parentPath);
140
+ if (!parent) return;
141
+ if (o.op === 'delete') {
142
+ if (YAML.isMap(parent)) {
143
+ const pair = findPair(parent, key);
144
+ if (pair) parent.items.splice(parent.items.indexOf(pair), 1);
145
+ }
146
+ return;
147
+ }
148
+ let seq = childOf(parent, key);
149
+ if (o.op === 'pull') {
150
+ if (!YAML.isSeq(seq)) return;
151
+ seq.items = seq.items.filter((n) => !same(n.toJSON ? n.toJSON() : n, o.value));
152
+ if (seq.items.length === 0) applyYaml(doc, { op: 'delete', path: o.path });
153
+ return;
154
+ }
155
+ if (!YAML.isSeq(seq)) {
156
+ applyYaml(doc, { op: 'set', path: o.path, value: [] });
157
+ seq = childOf(nodeAt(doc, parentPath), key);
158
+ }
159
+ if (o.op === 'push') {
160
+ if (!seq.items.some((n) => same(n.toJSON ? n.toJSON() : n, o.value))) seq.items.push(createNode(doc, o.value));
161
+ } else if (o.op === 'insert') {
162
+ seq.items.splice(o.index, 0, createNode(doc, o.value));
163
+ }
164
+ }
165
+
166
+ /**
167
+ * A string that YAML would read back as something else — a date like
168
+ * 2027-03-31, a number, true/null — is quoted, so the file says exactly what
169
+ * was verified.
170
+ */
171
+ function createNode(doc, value) {
172
+ const node = doc.createNode(clone(value));
173
+ YAML.visit(node, {
174
+ Scalar(_, s) {
175
+ // Judged by js-yaml, which reads the spec (YAML 1.1: dates are timestamps).
176
+ if (typeof s.value === 'string' && readsAsOther(s.value)) s.type = YAML.Scalar.QUOTE_SINGLE;
177
+ },
178
+ });
179
+ return node;
180
+ }
181
+
182
+ function readsAsOther(str) {
183
+ try {
184
+ return jsYaml.load(str) !== str;
185
+ } catch {
186
+ return true;
187
+ }
188
+ }
189
+
190
+ /** Keys in a spec are strings, but YAML may hold `200:` as a number — match by string form. */
191
+ function findPair(map, key) {
192
+ if (!YAML.isMap(map)) return null;
193
+ return map.items.find((p) => String(YAML.isScalar(p.key) ? p.key.value : p.key) === String(key)) || null;
194
+ }
195
+
196
+ function childOf(node, key) {
197
+ if (YAML.isMap(node)) { const p = findPair(node, key); return p ? p.value : undefined; }
198
+ if (YAML.isSeq(node)) return node.items[Number(key)];
199
+ return undefined;
200
+ }
201
+
202
+ function nodeAt(doc, path) {
203
+ let cur = doc.contents;
204
+ for (const k of path) {
205
+ cur = childOf(cur, k);
206
+ if (cur === undefined || cur === null) return undefined;
207
+ }
208
+ return cur;
209
+ }
210
+
211
+ function ensureNode(doc, path) {
212
+ let cur = doc.contents;
213
+ for (const k of path) {
214
+ let next = childOf(cur, k);
215
+ if (!YAML.isMap(next) && !YAML.isSeq(next)) {
216
+ next = doc.createNode({});
217
+ const pair = findPair(cur, k);
218
+ if (pair) pair.value = next;
219
+ else cur.add(doc.createPair(keyScalar(k), next));
220
+ }
221
+ cur = next;
222
+ }
223
+ return cur;
224
+ }
225
+
226
+ function keyScalar(key) {
227
+ // HTTP status codes stay quoted so they remain strings: '200'.
228
+ const s = new YAML.Scalar(String(key));
229
+ if (/^\d+$/.test(String(key))) s.type = YAML.Scalar.QUOTE_SINGLE;
230
+ return s;
231
+ }
232
+
233
+ module.exports = { applyOps, applyOpsToText, clone };