no-unexpected-plugin-keys.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const path = require('path');
  3. const utils = require('../utils');
  4. const VALID_KEYS = [ 'enable', 'package', 'path', 'env' ];
  5. module.exports = {
  6. meta: {
  7. docs: {
  8. description: 'Disallow unexpected plugin keys in config/plugin.*.js',
  9. category: 'Possible Errors',
  10. recommended: true,
  11. url: 'https://github.com/eggjs/eslint-plugin-eggache#no-unexpected-plugin-keys',
  12. },
  13. messages: {
  14. unexpectedKey: 'Unexpected key: {{ key }}',
  15. },
  16. },
  17. create(context) {
  18. // only `config/plugin.*.js`
  19. if (!isPlugin(context)) return {};
  20. return {
  21. ExpressionStatement(node) {
  22. // only consider the root scope
  23. if (!node.parent || node.parent.type !== 'Program') return;
  24. if (node.expression.type !== 'AssignmentExpression') return;
  25. const { left, right } = node.expression;
  26. // only conside object, cause `exports.view = false` always valid.
  27. if (utils.isExports(left) && right.type === 'ObjectExpression') {
  28. checkNode(context, right);
  29. }
  30. if (utils.isModule(left) && right.type === 'ObjectExpression') {
  31. for (const item of right.properties) {
  32. if (item.value.type === 'ObjectExpression') {
  33. checkNode(context, item.value);
  34. }
  35. }
  36. }
  37. },
  38. };
  39. },
  40. };
  41. function checkNode(context, node) {
  42. for (const testNode of node.properties) {
  43. if (!VALID_KEYS.includes(testNode.key.name)) {
  44. context.report({
  45. node: testNode,
  46. messageId: 'unexpectedKey',
  47. data: {
  48. key: testNode.key.name,
  49. },
  50. });
  51. }
  52. }
  53. }
  54. function isPlugin(context) {
  55. const filePath = context.getFilename();
  56. if (filePath === '<input>') return true;
  57. const baseName = path.basename(filePath);
  58. const dirname = path.basename(path.dirname(filePath));
  59. return dirname === 'config' && baseName.startsWith('plugin.');
  60. }