checkAgainstRule.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import Result from 'postcss/lib/result';
  2. import getStylelintRule from './getStylelintRule.mjs';
  3. import { isPlainObject } from './validateTypes.mjs';
  4. import { lexer } from 'css-tree';
  5. import normalizeRuleSettings from '../normalizeRuleSettings.mjs';
  6. /**
  7. * @type {import('stylelint').Utils['checkAgainstRule']}
  8. */
  9. export default async 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 = { lexer } } = options;
  13. if (!ruleName) throw new Error('Expected a "ruleName" option');
  14. const rule = await getStylelintRule(ruleName, 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. /** @type {import('stylelint').StylelintPostcssResult} */
  31. const stylelint = result?.stylelint ?? {
  32. ruleSeverities: {},
  33. customMessages: {},
  34. customUrls: {},
  35. ruleMetadata: {},
  36. fixersData: {},
  37. rangesOfComputedEditInfos: [],
  38. disabledRanges: {},
  39. };
  40. // @ts-expect-error -- TS2339: Property 'stylelint' does not exist on type 'Result<undefined>'.
  41. tmpPostcssResult.stylelint = stylelint;
  42. const [primary, secondary] = settings;
  43. const ruleFunc = rule(primary, secondary || {}, context);
  44. await ruleFunc(
  45. root,
  46. // NOTE: This temporary PostCSS result doesn't have a property for Stylelint use.
  47. // Problems may occur if some rules use the property.
  48. // @ts-expect-error -- TS2345: Argument of type 'Result' is not assignable to parameter of type 'PostcssResult'.
  49. tmpPostcssResult,
  50. );
  51. for (const warning of tmpPostcssResult.warnings()) callback(warning);
  52. }