mirror of
https://github.com/nodejs/node.git
synced 2024-11-28 14:33:11 +01:00
5c22d19f44
PR-URL: https://github.com/nodejs/node/pull/54987 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
55 lines
1.4 KiB
JavaScript
55 lines
1.4 KiB
JavaScript
/**
|
|
* @fileoverview Ensure modules are not required twice at top level of a module
|
|
* @author devsnek
|
|
* @author RedYetiDev
|
|
*/
|
|
'use strict';
|
|
|
|
const { isRequireCall, isString } = require('./rules-utils.js');
|
|
|
|
//------------------------------------------------------------------------------
|
|
// Rule Definition
|
|
//------------------------------------------------------------------------------
|
|
|
|
const topLevelTypes = new Set([
|
|
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
|
|
'ClassBody', 'MethodDefinition',
|
|
]);
|
|
|
|
const isTopLevel = (node) => {
|
|
while (node) {
|
|
if (topLevelTypes.has(node.type)) return false;
|
|
node = node.parent;
|
|
}
|
|
return true;
|
|
};
|
|
|
|
module.exports = {
|
|
create(context) {
|
|
if (context.languageOptions.sourceType === 'module') {
|
|
return {};
|
|
}
|
|
|
|
const requiredModules = new Set();
|
|
|
|
return {
|
|
CallExpression(node) {
|
|
if (isRequireCall(node)) {
|
|
const [firstArg] = node.arguments;
|
|
if (isString(firstArg)) {
|
|
const moduleName = firstArg.value.trim();
|
|
if (requiredModules.has(moduleName)) {
|
|
context.report({
|
|
node,
|
|
message: `'${moduleName}' require is duplicated.`,
|
|
});
|
|
} else if (isTopLevel(node)) {
|
|
requiredModules.add(moduleName);
|
|
}
|
|
}
|
|
}
|
|
},
|
|
};
|
|
},
|
|
};
|