global-require.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * @author Jamund Ferguson
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const ACCEPTABLE_PARENTS = [
  7. "AssignmentExpression",
  8. "VariableDeclarator",
  9. "MemberExpression",
  10. "ExpressionStatement",
  11. "CallExpression",
  12. "ConditionalExpression",
  13. "Program",
  14. "VariableDeclaration",
  15. ]
  16. /**
  17. * Finds the eslint-scope reference in the given scope.
  18. * @param {Object} scope The scope to search.
  19. * @param {ASTNode} node The identifier node.
  20. * @returns {Reference|null} Returns the found reference or null if none were found.
  21. */
  22. function findReference(scope, node) {
  23. const references = scope.references.filter(
  24. reference =>
  25. reference.identifier.range[0] === node.range[0] &&
  26. reference.identifier.range[1] === node.range[1]
  27. )
  28. /* istanbul ignore else: correctly returns null */
  29. if (references.length === 1) {
  30. return references[0]
  31. }
  32. return null
  33. }
  34. /**
  35. * Checks if the given identifier node is shadowed in the given scope.
  36. * @param {Object} scope The current scope.
  37. * @param {ASTNode} node The identifier node to check.
  38. * @returns {boolean} Whether or not the name is shadowed.
  39. */
  40. function isShadowed(scope, node) {
  41. const reference = findReference(scope, node)
  42. return reference && reference.resolved && reference.resolved.defs.length > 0
  43. }
  44. module.exports = {
  45. meta: {
  46. type: "suggestion",
  47. docs: {
  48. description:
  49. "require `require()` calls to be placed at top-level module scope",
  50. category: "Stylistic Issues",
  51. recommended: false,
  52. url:
  53. "https://github.com/mysticatea/eslint-plugin-node/blob/v11.1.0/docs/rules/global-require.md",
  54. },
  55. fixable: null,
  56. schema: [],
  57. messages: {
  58. unexpected: "Unexpected require().",
  59. },
  60. },
  61. create(context) {
  62. return {
  63. CallExpression(node) {
  64. const currentScope = context.getScope()
  65. if (
  66. node.callee.name === "require" &&
  67. !isShadowed(currentScope, node.callee)
  68. ) {
  69. const isGoodRequire = context
  70. .getAncestors()
  71. .every(
  72. parent =>
  73. ACCEPTABLE_PARENTS.indexOf(parent.type) > -1
  74. )
  75. if (!isGoodRequire) {
  76. context.report({ node, messageId: "unexpected" })
  77. }
  78. }
  79. },
  80. }
  81. },
  82. }