1 | /**
|
2 | * @fileoverview Validate strings passed to the RegExp constructor
|
3 | * @author Michael Ficarra
|
4 | * @copyright 2014 Michael Ficarra. All rights reserved.
|
5 | */
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Requirements
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | var espree = require("espree");
|
13 |
|
14 | //------------------------------------------------------------------------------
|
15 | // Rule Definition
|
16 | //------------------------------------------------------------------------------
|
17 |
|
18 | module.exports = function(context) {
|
19 |
|
20 | /**
|
21 | * Check if node is a string
|
22 | * @param {ASTNode} node node to evaluate
|
23 | * @returns {boolean} True if its a string
|
24 | * @private
|
25 | */
|
26 | function isString(node) {
|
27 | return node && node.type === "Literal" && typeof node.value === "string";
|
28 | }
|
29 |
|
30 | /**
|
31 | * Validate strings passed to the RegExp constructor
|
32 | * @param {ASTNode} node node to evaluate
|
33 | * @returns {void}
|
34 | * @private
|
35 | */
|
36 | function check(node) {
|
37 | if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(node.arguments[0])) {
|
38 | var flags = isString(node.arguments[1]) ? node.arguments[1].value : "";
|
39 |
|
40 | try {
|
41 | void new RegExp(node.arguments[0].value);
|
42 | } catch (e) {
|
43 | context.report(node, e.message);
|
44 | }
|
45 |
|
46 | if (flags) {
|
47 |
|
48 | try {
|
49 | espree.parse("/./" + flags, context.parserOptions);
|
50 | } catch (ex) {
|
51 | context.report(node, "Invalid flags supplied to RegExp constructor '" + flags + "'");
|
52 | }
|
53 | }
|
54 |
|
55 | }
|
56 | }
|
57 |
|
58 | return {
|
59 | "CallExpression": check,
|
60 | "NewExpression": check
|
61 | };
|
62 |
|
63 | };
|
64 |
|
65 | module.exports.schema = [];
|