2018-07-08 06:32:23 +02:00
|
|
|
/**
|
|
|
|
* @fileoverview Ensure modules are not required twice at top level of a module
|
|
|
|
* @author devsnek
|
2024-09-23 22:23:05 +02:00
|
|
|
* @author RedYetiDev
|
2018-07-08 06:32:23 +02:00
|
|
|
*/
|
|
|
|
'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
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
2024-09-23 22:23:05 +02:00
|
|
|
const topLevelTypes = new Set([
|
2021-12-26 04:51:07 +01:00
|
|
|
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
|
|
|
|
'ClassBody', 'MethodDefinition',
|
2024-09-23 22:23:05 +02:00
|
|
|
]);
|
2018-07-08 06:32:23 +02:00
|
|
|
|
2024-09-23 22:23:05 +02:00
|
|
|
const isTopLevel = (node) => {
|
|
|
|
while (node) {
|
|
|
|
if (topLevelTypes.has(node.type)) return false;
|
2021-12-26 04:51:07 +01:00
|
|
|
node = node.parent;
|
|
|
|
}
|
2024-09-23 22:23:05 +02:00
|
|
|
return true;
|
|
|
|
};
|
2018-07-08 06:32:23 +02:00
|
|
|
|
2024-05-09 17:27:39 +02:00
|
|
|
module.exports = {
|
|
|
|
create(context) {
|
2024-05-23 21:45:18 +02:00
|
|
|
if (context.languageOptions.sourceType === 'module') {
|
2024-05-09 17:27:39 +02:00
|
|
|
return {};
|
2018-07-08 06:32:23 +02:00
|
|
|
}
|
|
|
|
|
2024-09-23 22:23:05 +02:00
|
|
|
const requiredModules = new Set();
|
2018-07-08 06:32:23 +02:00
|
|
|
|
2024-09-23 22:23:05 +02:00
|
|
|
return {
|
|
|
|
CallExpression(node) {
|
2024-09-25 10:51:28 +02:00
|
|
|
if (isRequireCall(node)) {
|
2024-09-23 22:23:05 +02: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 10:51:28 +02:00
|
|
|
} else if (isTopLevel(node)) {
|
2024-09-23 22:23:05 +02:00
|
|
|
requiredModules.add(moduleName);
|
|
|
|
}
|
2024-05-09 17:27:39 +02:00
|
|
|
}
|
2018-07-08 06:32:23 +02:00
|
|
|
}
|
2024-05-09 17:27:39 +02:00
|
|
|
},
|
|
|
|
};
|
|
|
|
},
|
2018-07-08 06:32:23 +02:00
|
|
|
};
|