1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | const RegExpValidator = require("regexpp").RegExpValidator;
|
12 | const validator = new RegExpValidator({ ecmaVersion: 2018 });
|
13 | const validFlags = /[gimuys]/gu;
|
14 | const undefined1 = void 0;
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | module.exports = {
|
21 | meta: {
|
22 | type: "problem",
|
23 |
|
24 | docs: {
|
25 | description: "disallow invalid regular expression strings in `RegExp` constructors",
|
26 | category: "Possible Errors",
|
27 | recommended: true,
|
28 | url: "https://eslint.org/docs/rules/no-invalid-regexp"
|
29 | },
|
30 |
|
31 | schema: [{
|
32 | type: "object",
|
33 | properties: {
|
34 | allowConstructorFlags: {
|
35 | type: "array",
|
36 | items: {
|
37 | type: "string"
|
38 | }
|
39 | }
|
40 | },
|
41 | additionalProperties: false
|
42 | }]
|
43 | },
|
44 |
|
45 | create(context) {
|
46 |
|
47 | const options = context.options[0];
|
48 | let allowedFlags = null;
|
49 |
|
50 | if (options && options.allowConstructorFlags) {
|
51 | const temp = options.allowConstructorFlags.join("").replace(validFlags, "");
|
52 |
|
53 | if (temp) {
|
54 | allowedFlags = new RegExp(`[${temp}]`, "giu");
|
55 | }
|
56 | }
|
57 |
|
58 | |
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | function isString(node) {
|
65 | return node && node.type === "Literal" && typeof node.value === "string";
|
66 | }
|
67 |
|
68 | |
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | function validateRegExpPattern(pattern, uFlag) {
|
75 | try {
|
76 | validator.validatePattern(pattern, undefined1, undefined1, uFlag);
|
77 | return null;
|
78 | } catch (err) {
|
79 | return err.message;
|
80 | }
|
81 | }
|
82 |
|
83 | |
84 |
|
85 |
|
86 |
|
87 |
|
88 | function validateRegExpFlags(flags) {
|
89 | try {
|
90 | validator.validateFlags(flags);
|
91 | return null;
|
92 | } catch (err) {
|
93 | return `Invalid flags supplied to RegExp constructor '${flags}'`;
|
94 | }
|
95 | }
|
96 |
|
97 | return {
|
98 | "CallExpression, NewExpression"(node) {
|
99 | if (node.callee.type !== "Identifier" || node.callee.name !== "RegExp" || !isString(node.arguments[0])) {
|
100 | return;
|
101 | }
|
102 | const pattern = node.arguments[0].value;
|
103 | let flags = isString(node.arguments[1]) ? node.arguments[1].value : "";
|
104 |
|
105 | if (allowedFlags) {
|
106 | flags = flags.replace(allowedFlags, "");
|
107 | }
|
108 |
|
109 |
|
110 | const message = validateRegExpFlags(flags) || (
|
111 | flags
|
112 | ? validateRegExpPattern(pattern, flags.indexOf("u") !== -1)
|
113 | : validateRegExpPattern(pattern, true) && validateRegExpPattern(pattern, false)
|
114 | );
|
115 |
|
116 | if (message) {
|
117 | context.report({
|
118 | node,
|
119 | message: "{{message}}.",
|
120 | data: { message }
|
121 | });
|
122 | }
|
123 | }
|
124 | };
|
125 | }
|
126 | };
|