2 * @fileoverview Restrict usage of specified node modules.
3 * @author Christian Schulz
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 module.exports = function (context) {
12 // trim restricted module names
13 var restrictedModules = context.options;
15 // if no modules are restricted we don't need to check the CallExpressions
16 if (restrictedModules.length === 0) {
21 * Function to check if a node is a string literal.
22 * @param {ASTNode} node The node to check.
23 * @returns {boolean} If the node is a string literal.
25 function isString(node) {
26 return node && node.type === "Literal" && typeof node.value === "string";
30 * Function to check if a node is a require call.
31 * @param {ASTNode} node The node to check.
32 * @returns {boolean} If the node is a require call.
34 function isRequireCall(node) {
35 return node.callee.type === "Identifier" && node.callee.name === "require";
39 * Function to check if a node has an argument that is an restricted module and return its name.
40 * @param {ASTNode} node The node to check
41 * @returns {undefined|String} restricted module name or undefined if node argument isn't restricted.
43 function getRestrictedModuleName(node) {
46 // node has arguments and first argument is string
47 if (node.arguments.length && isString(node.arguments[0])) {
48 var argumentValue = node.arguments[0].value.trim();
50 // check if argument value is in restricted modules array
51 if (restrictedModules.indexOf(argumentValue) !== -1) {
52 moduleName = argumentValue;
60 "CallExpression": function (node) {
61 if (isRequireCall(node)) {
62 var restrictedModuleName = getRestrictedModuleName(node);
64 if (restrictedModuleName) {
65 context.report(node, "'{{moduleName}}' module is restricted from being used.", {
66 moduleName: restrictedModuleName