/
pattern.ts
84 lines (71 loc) · 2.2 KB
/
pattern.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import type { Optional } from '@stoplight/types';
import { createRulesetFunction, IFunctionResult } from '@stoplight/spectral-core';
import { printValue } from '@stoplight/spectral-runtime';
import { optionSchemas } from './optionSchemas';
export type Options =
| {
/** regex that target must match */
match: string;
}
| {
/** regex that target must not match */
notMatch: string;
}
| {
match: string;
notMatch: string;
};
// regex in a string like {"match": "/[a-b]+/im"} or {"match": "[a-b]+"} in a json ruleset
// the available flags are "gimsuy" as described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
const REGEXP_PATTERN = /^\/(.+)\/([a-z]*)$/;
const cache = new Map<string, RegExp>();
function getFromCache(pattern: string): RegExp {
const existingPattern = cache.get(pattern);
if (existingPattern !== void 0) {
existingPattern.lastIndex = 0;
return existingPattern;
}
const newPattern = createRegex(pattern);
cache.set(pattern, newPattern);
return newPattern;
}
function createRegex(pattern: string): RegExp {
const splitRegex = REGEXP_PATTERN.exec(pattern);
if (splitRegex !== null) {
// with slashes like /[a-b]+/ and possibly with flags like /[a-b]+/im
return new RegExp(splitRegex[1], splitRegex[2]);
} else {
// without slashes like [a-b]+
return new RegExp(pattern);
}
}
export default createRulesetFunction<string, Options>(
{
input: {
type: 'string',
},
options: optionSchemas.pattern,
},
function pattern(targetVal, opts) {
let results: Optional<IFunctionResult[]>;
if ('match' in opts) {
const pattern = getFromCache(opts.match);
if (!pattern.test(targetVal)) {
results = [
{
message: `#{{print("value")}} must match the pattern ${printValue(opts.match)}`,
},
];
}
}
if ('notMatch' in opts) {
const pattern = getFromCache(opts.notMatch);
if (pattern.test(targetVal)) {
(results ??= []).push({
message: `#{{print("value")}} must not match the pattern ${printValue(opts.notMatch)}`,
});
}
}
return results;
},
);