• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * @fileoverview Rule to flag when using new Function
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13    meta: {
14        type: "suggestion",
15
16        docs: {
17            description: "disallow `new` operators with the `Function` object",
18            category: "Best Practices",
19            recommended: false,
20            url: "https://eslint.org/docs/rules/no-new-func"
21        },
22
23        schema: [],
24
25        messages: {
26            noFunctionConstructor: "The Function constructor is eval."
27        }
28    },
29
30    create(context) {
31
32        return {
33            "Program:exit"() {
34                const globalScope = context.getScope();
35                const variable = globalScope.set.get("Function");
36
37                if (variable && variable.defs.length === 0) {
38                    variable.references.forEach(ref => {
39                        const node = ref.identifier;
40                        const { parent } = node;
41
42                        if (
43                            parent &&
44                            (parent.type === "NewExpression" || parent.type === "CallExpression") &&
45                            node === parent.callee
46                        ) {
47                            context.report({
48                                node: parent,
49                                messageId: "noFunctionConstructor"
50                            });
51                        }
52                    });
53                }
54            }
55        };
56
57    }
58};
59