123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- "use strict";
- const RegExpValidator = require("regexpp").RegExpValidator;
- const validator = new RegExpValidator();
- const validFlags = /[gimuys]/gu;
- const undefined1 = void 0;
- module.exports = {
- meta: {
- type: "problem",
- docs: {
- description: "disallow invalid regular expression strings in `RegExp` constructors",
- category: "Possible Errors",
- recommended: true,
- url: "https://eslint.org/docs/rules/no-invalid-regexp"
- },
- schema: [{
- type: "object",
- properties: {
- allowConstructorFlags: {
- type: "array",
- items: {
- type: "string"
- }
- }
- },
- additionalProperties: false
- }],
- messages: {
- regexMessage: "{{message}}."
- }
- },
- create(context) {
- const options = context.options[0];
- let allowedFlags = null;
- if (options && options.allowConstructorFlags) {
- const temp = options.allowConstructorFlags.join("").replace(validFlags, "");
- if (temp) {
- allowedFlags = new RegExp(`[${temp}]`, "giu");
- }
- }
-
- function isString(node) {
- return node && node.type === "Literal" && typeof node.value === "string";
- }
-
- function getFlags(node) {
- if (node.arguments.length < 2) {
- return "";
- }
- if (isString(node.arguments[1])) {
- return node.arguments[1].value;
- }
- return null;
- }
-
- function validateRegExpPattern(pattern, uFlag) {
- try {
- validator.validatePattern(pattern, undefined1, undefined1, uFlag);
- return null;
- } catch (err) {
- return err.message;
- }
- }
-
- function validateRegExpFlags(flags) {
- try {
- validator.validateFlags(flags);
- return null;
- } catch {
- return `Invalid flags supplied to RegExp constructor '${flags}'`;
- }
- }
- return {
- "CallExpression, NewExpression"(node) {
- if (node.callee.type !== "Identifier" || node.callee.name !== "RegExp" || !isString(node.arguments[0])) {
- return;
- }
- const pattern = node.arguments[0].value;
- let flags = getFlags(node);
- if (flags && allowedFlags) {
- flags = flags.replace(allowedFlags, "");
- }
- const message =
- (
- flags && validateRegExpFlags(flags)
- ) ||
- (
-
- flags === null
- ? validateRegExpPattern(pattern, true) && validateRegExpPattern(pattern, false)
- : validateRegExpPattern(pattern, flags.includes("u"))
- );
- if (message) {
- context.report({
- node,
- messageId: "regexMessage",
- data: { message }
- });
- }
- }
- };
- }
- };
|