2018-07-08 04:32:23 +00:00
|
|
|
/**
|
|
|
|
* @fileoverview Ensure modules are not required twice at top level of a module
|
|
|
|
* @author devsnek
|
2024-09-23 20:23:05 +00:00
|
|
|
* @author RedYetiDev
|
2018-07-08 04:32:23 +00:00
|
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
|
2019-05-15 19:29:56 +00:00
|
|
|
const { isRequireCall, isString } = require('./rules-utils.js');
|
2019-05-13 18:50:55 +00:00
|
|
|
|
2018-07-08 04:32:23 +00:00
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// Rule Definition
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
2024-09-23 20:23:05 +00:00
|
|
|
const topLevelTypes = new Set([
|
2021-12-26 03:51:07 +00:00
|
|
|
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
|
|
|
|
'ClassBody', 'MethodDefinition',
|
2024-09-23 20:23:05 +00:00
|
|
|
]);
|
2018-07-08 04:32:23 +00:00
|
|
|
|
2024-09-23 20:23:05 +00:00
|
|
|
const isTopLevel = (node) => {
|
|
|
|
while (node) {
|
|
|
|
if (topLevelTypes.has(node.type)) return false;
|
2021-12-26 03:51:07 +00:00
|
|
|
node = node.parent;
|
|
|
|
}
|
2024-09-23 20:23:05 +00:00
|
|
|
return true;
|
|
|
|
};
|
2018-07-08 04:32:23 +00:00
|
|
|
|
2024-05-09 15:27:39 +00:00
|
|
|
module.exports = {
|
|
|
|
create(context) {
|
2024-05-23 19:45:18 +00:00
|
|
|
if (context.languageOptions.sourceType === 'module') {
|
2024-05-09 15:27:39 +00:00
|
|
|
return {};
|
2018-07-08 04:32:23 +00:00
|
|
|
}
|
|
|
|
|
2024-09-23 20:23:05 +00:00
|
|
|
const requiredModules = new Set();
|
2018-07-08 04:32:23 +00:00
|
|
|
|
2024-09-23 20:23:05 +00:00
|
|
|
return {
|
|
|
|
CallExpression(node) {
|
2024-09-25 08:51:28 +00:00
|
|
|
if (isRequireCall(node)) {
|
2024-09-23 20:23:05 +00:00
|
|
|
const [firstArg] = node.arguments;
|
|
|
|
if (isString(firstArg)) {
|
|
|
|
const moduleName = firstArg.value.trim();
|
|
|
|
if (requiredModules.has(moduleName)) {
|
|
|
|
context.report({
|
|
|
|
node,
|
|
|
|
message: `'${moduleName}' require is duplicated.`,
|
|
|
|
});
|
2024-09-25 08:51:28 +00:00
|
|
|
} else if (isTopLevel(node)) {
|
2024-09-23 20:23:05 +00:00
|
|
|
requiredModules.add(moduleName);
|
|
|
|
}
|
2024-05-09 15:27:39 +00:00
|
|
|
}
|
2018-07-08 04:32:23 +00:00
|
|
|
}
|
2024-05-09 15:27:39 +00:00
|
|
|
},
|
|
|
|
};
|
|
|
|
},
|
2018-07-08 04:32:23 +00:00
|
|
|
};
|