-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathno-ambiguous-paths.ts
50 lines (43 loc) · 1.46 KB
/
no-ambiguous-paths.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import type { Oas3Rule, Oas2Rule } from '../../visitors';
import type { UserContext } from '../../walk';
import type { Oas3Paths } from '../../typings/openapi';
import type { Oas2Paths } from '../../typings/swagger';
export const NoAmbiguousPaths: Oas3Rule | Oas2Rule = () => {
return {
Paths(pathMap: Oas3Paths | Oas2Paths, { report, location }: UserContext) {
const seenPaths: string[] = [];
for (const currentPath of Object.keys(pathMap)) {
const ambiguousPath = seenPaths.find((seenPath) =>
arePathsAmbiguous(seenPath, currentPath)
);
if (ambiguousPath) {
report({
message: `Paths should resolve unambiguously. Found two ambiguous paths: \`${ambiguousPath}\` and \`${currentPath}\`.`,
location: location.child([currentPath]).key(),
});
}
seenPaths.push(currentPath);
}
},
};
};
function arePathsAmbiguous(a: string, b: string) {
const partsA = a.split('/');
const partsB = b.split('/');
if (partsA.length !== partsB.length) return false;
let aVars = 0;
let bVars = 0;
let ambiguous = true;
for (let i = 0; i < partsA.length; i++) {
const aIsVar = partsA[i].match(/^{.+?}$/);
const bIsVar = partsB[i].match(/^{.+?}$/);
if (aIsVar || bIsVar) {
if (aIsVar) aVars++;
if (bIsVar) bVars++;
continue;
} else if (partsA[i] !== partsB[i]) {
ambiguous = false;
}
}
return ambiguous && aVars === bVars;
}