UNPKG

1.33 kBJavaScriptView Raw
1'use strict';
2const safeRegex = require('safe-regex');
3const getDocumentationUrl = require('./utils/get-documentation-url');
4
5const message = 'Unsafe regular expression.';
6
7const create = context => {
8 return {
9 'Literal[regex]': node => {
10 // Handle regex literal inside RegExp constructor in the other handler
11 if (
12 node.parent.type === 'NewExpression' &&
13 node.parent.callee.name === 'RegExp'
14 ) {
15 return;
16 }
17
18 if (!safeRegex(node.value)) {
19 context.report({
20 node,
21 message
22 });
23 }
24 },
25 'NewExpression[callee.name="RegExp"]': node => {
26 const arguments_ = node.arguments;
27
28 if (arguments_.length === 0 || arguments_[0].type !== 'Literal') {
29 return;
30 }
31
32 const hasRegExp = arguments_[0].regex;
33
34 let pattern;
35 let flags;
36 if (hasRegExp) {
37 ({pattern} = arguments_[0].regex);
38 flags = arguments_[1] && arguments_[1].type === 'Literal' ? arguments_[1].value : arguments_[0].regex.flags;
39 } else {
40 pattern = arguments_[0].value;
41 flags = arguments_[1] && arguments_[1].type === 'Literal' ? arguments_[1].value : '';
42 }
43
44 if (!safeRegex(`/${pattern}/${flags}`)) {
45 context.report({
46 node,
47 message
48 });
49 }
50 }
51 };
52};
53
54module.exports = {
55 create,
56 meta: {
57 type: 'problem',
58 docs: {
59 url: getDocumentationUrl(__filename)
60 }
61 }
62};