checkAgainstRule.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const Result = require('postcss/lib/result').default;
  3. const normalizeRuleSettings = require('../normalizeRuleSettings');
  4. const { isPlainObject } = require('./validateTypes');
  5. const getStylelintRule = require('./getStylelintRule');
  6. /**
  7. * @type {import('stylelint').Utils['checkAgainstRule']}
  8. */
  9. module.exports = function checkAgainstRule(options, callback) {
  10. if (!isPlainObject(options)) throw new Error('Expected an options object');
  11. if (!callback) throw new Error('Expected a callback function');
  12. const { ruleName, ruleSettings, root, result, context = {} } = options;
  13. if (!ruleName) throw new Error('Expected a "ruleName" option');
  14. const rule = getStylelintRule(ruleName, result && result.stylelint.config);
  15. if (!rule) throw new Error(`Rule "${ruleName}" does not exist`);
  16. if (!ruleSettings) throw new Error('Expected a "ruleSettings" option');
  17. if (!root) throw new Error('Expected a "root" option');
  18. const settings = normalizeRuleSettings(ruleSettings, rule);
  19. if (!settings) {
  20. return;
  21. }
  22. const tmpPostcssResult = new Result(
  23. // NOTE: The first argument is unused, so passing `undefined` raises no problems.
  24. // But this PostCSS's behavior may change in the future.
  25. // @ts-expect-error -- TS2345: Argument of type 'undefined' is not assignable to parameter of type 'Processor'.
  26. undefined,
  27. undefined,
  28. undefined,
  29. );
  30. const [primary, secondary] = settings;
  31. const ruleFunc = rule(primary, secondary || {}, context);
  32. ruleFunc(
  33. root,
  34. // NOTE: This temporary PostCSS result doesn't have a property for Stylelint use.
  35. // Problems may occur if some rules use the property.
  36. // @ts-expect-error -- TS2345: Argument of type 'Result' is not assignable to parameter of type 'PostcssResult'.
  37. tmpPostcssResult,
  38. );
  39. for (const warning of tmpPostcssResult.warnings()) callback(warning);
  40. };