no-restricted-exports.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @fileoverview Rule to disallow specified names in exports
  3. * @author Milos Djermanovic
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "Disallow specified names in exports",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-restricted-exports"
  21. },
  22. schema: [{
  23. type: "object",
  24. properties: {
  25. restrictedNamedExports: {
  26. type: "array",
  27. items: {
  28. type: "string"
  29. },
  30. uniqueItems: true
  31. }
  32. },
  33. additionalProperties: false
  34. }],
  35. messages: {
  36. restrictedNamed: "'{{name}}' is restricted from being used as an exported name."
  37. }
  38. },
  39. create(context) {
  40. const restrictedNames = new Set(context.options[0] && context.options[0].restrictedNamedExports);
  41. /**
  42. * Checks and reports given exported name.
  43. * @param {ASTNode} node exported `Identifier` or string `Literal` node to check.
  44. * @returns {void}
  45. */
  46. function checkExportedName(node) {
  47. const name = astUtils.getModuleExportName(node);
  48. if (restrictedNames.has(name)) {
  49. context.report({
  50. node,
  51. messageId: "restrictedNamed",
  52. data: { name }
  53. });
  54. }
  55. }
  56. return {
  57. ExportAllDeclaration(node) {
  58. if (node.exported) {
  59. checkExportedName(node.exported);
  60. }
  61. },
  62. ExportNamedDeclaration(node) {
  63. const declaration = node.declaration;
  64. if (declaration) {
  65. if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") {
  66. checkExportedName(declaration.id);
  67. } else if (declaration.type === "VariableDeclaration") {
  68. context.getDeclaredVariables(declaration)
  69. .map(v => v.defs.find(d => d.parent === declaration))
  70. .map(d => d.name) // Identifier nodes
  71. .forEach(checkExportedName);
  72. }
  73. } else {
  74. node.specifiers
  75. .map(s => s.exported)
  76. .forEach(checkExportedName);
  77. }
  78. }
  79. };
  80. }
  81. };