2018-07-08 06:32:23 +02:00
|
|
|
/**
|
|
|
|
* @fileoverview Ensure modules are not required twice at top level of a module
|
|
|
|
* @author devsnek
|
|
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
|
2019-05-15 21:29:56 +02:00
|
|
|
const { isRequireCall, isString } = require('./rules-utils.js');
|
2019-05-13 20:50:55 +02:00
|
|
|
|
2018-07-08 06:32:23 +02:00
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// Rule Definition
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
2021-12-26 04:51:07 +01:00
|
|
|
const secondLevelTypes = [
|
|
|
|
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
|
|
|
|
'ClassBody', 'MethodDefinition',
|
|
|
|
];
|
2018-07-08 06:32:23 +02:00
|
|
|
|
|
|
|
function isTopLevel(node) {
|
2021-12-26 04:51:07 +01:00
|
|
|
while (!secondLevelTypes.includes(node.type)) {
|
|
|
|
node = node.parent;
|
|
|
|
if (!node) {
|
|
|
|
return true;
|
2018-07-08 06:32:23 +02:00
|
|
|
}
|
2021-12-26 04:51:07 +01:00
|
|
|
}
|
|
|
|
return false;
|
2018-07-08 06:32:23 +02:00
|
|
|
}
|
|
|
|
|
2024-05-09 17:27:39 +02:00
|
|
|
module.exports = {
|
|
|
|
create(context) {
|
|
|
|
if (context.parserOptions.sourceType === 'module') {
|
|
|
|
return {};
|
2018-07-08 06:32:23 +02:00
|
|
|
}
|
|
|
|
|
2024-05-09 17:27:39 +02:00
|
|
|
function getRequiredModuleNameFromCall(node) {
|
|
|
|
// Node has arguments and first argument is string
|
|
|
|
if (node.arguments.length && isString(node.arguments[0])) {
|
|
|
|
return node.arguments[0].value.trim();
|
|
|
|
}
|
2018-07-08 06:32:23 +02:00
|
|
|
|
2024-05-09 17:27:39 +02:00
|
|
|
return undefined;
|
|
|
|
}
|
2018-07-08 06:32:23 +02:00
|
|
|
|
2024-05-09 17:27:39 +02:00
|
|
|
const required = new Set();
|
|
|
|
|
|
|
|
const rules = {
|
|
|
|
CallExpression: (node) => {
|
|
|
|
if (isRequireCall(node) && isTopLevel(node)) {
|
|
|
|
const moduleName = getRequiredModuleNameFromCall(node);
|
|
|
|
if (moduleName === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (required.has(moduleName)) {
|
|
|
|
context.report(
|
|
|
|
node,
|
|
|
|
'\'{{moduleName}}\' require is duplicated.',
|
|
|
|
{ moduleName },
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
required.add(moduleName);
|
|
|
|
}
|
2018-07-08 06:32:23 +02:00
|
|
|
}
|
2024-05-09 17:27:39 +02:00
|
|
|
},
|
|
|
|
};
|
2018-07-08 06:32:23 +02:00
|
|
|
|
2024-05-09 17:27:39 +02:00
|
|
|
return rules;
|
|
|
|
},
|
2018-07-08 06:32:23 +02:00
|
|
|
};
|