check-extraneous.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * @author Toru Nagashima
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const getAllowModules = require("./get-allow-modules")
  7. const getPackageJson = require("./get-package-json")
  8. /**
  9. * Checks whether or not each requirement target is published via package.json.
  10. *
  11. * It reads package.json and checks the target exists in `dependencies`.
  12. *
  13. * @param {RuleContext} context - A context to report.
  14. * @param {string} filePath - The current file path.
  15. * @param {ImportTarget[]} targets - A list of target information to check.
  16. * @returns {void}
  17. */
  18. module.exports = function checkForExtraneous(context, filePath, targets) {
  19. const packageInfo = getPackageJson(filePath)
  20. if (!packageInfo) {
  21. return
  22. }
  23. const allowed = new Set(getAllowModules(context))
  24. const dependencies = new Set(
  25. [].concat(
  26. Object.keys(packageInfo.dependencies || {}),
  27. Object.keys(packageInfo.devDependencies || {}),
  28. Object.keys(packageInfo.peerDependencies || {}),
  29. Object.keys(packageInfo.optionalDependencies || {})
  30. )
  31. )
  32. for (const target of targets) {
  33. const extraneous =
  34. target.moduleName != null &&
  35. target.filePath != null &&
  36. !dependencies.has(target.moduleName) &&
  37. !allowed.has(target.moduleName)
  38. if (extraneous) {
  39. context.report({
  40. node: target.node,
  41. loc: target.node.loc,
  42. message: '"{{moduleName}}" is extraneous.',
  43. data: target,
  44. })
  45. }
  46. }
  47. }