blob: 494569e236c6aaf654ab51afa34c75286599b981 [file] [log] [blame]
Mathias Bynens79e2cf02020-05-29 16:46:17 +02001'use strict';
2
3const normalizeRuleSettings = require('../normalizeRuleSettings');
4const Result = require('postcss/lib/result');
5const rules = require('../rules');
6
7/**
8 * Useful for third-party code (e.g. plugins) to run a PostCSS Root
9 * against a specific rule and do something with the warnings
Tim van der Lippe0a9b84d2021-03-24 11:53:15 +000010 * @template T
11 * @template {Object} O
Mathias Bynens79e2cf02020-05-29 16:46:17 +020012 * @param {{
13 ruleName: string,
Tim van der Lippe16b82282021-11-08 13:50:26 +000014 ruleSettings: import('stylelint').ConfigRuleSettings<T, O>,
Tim van der Lippeefb716a2020-12-01 12:54:04 +000015 root: import('postcss').Root,
Mathias Bynens79e2cf02020-05-29 16:46:17 +020016 }} options
Tim van der Lippe16b82282021-11-08 13:50:26 +000017 * @param {(warning: import('postcss').Warning) => void} callback
Mathias Bynens79e2cf02020-05-29 16:46:17 +020018 * @returns {void}
19 */
Tim van der Lippe16b82282021-11-08 13:50:26 +000020function checkAgainstRule(options, callback) {
Mathias Bynens79e2cf02020-05-29 16:46:17 +020021 if (!options)
22 throw new Error(
23 "checkAgainstRule requires an options object with 'ruleName', 'ruleSettings', and 'root' properties",
24 );
25
26 if (!callback) throw new Error('checkAgainstRule requires a callback');
27
28 if (!options.ruleName) throw new Error("checkAgainstRule requires a 'ruleName' option");
29
30 if (!Object.keys(rules).includes(options.ruleName))
31 throw new Error(`Rule '${options.ruleName}' does not exist`);
32
33 if (!options.ruleSettings) throw new Error("checkAgainstRule requires a 'ruleSettings' option");
34
35 if (!options.root) throw new Error("checkAgainstRule requires a 'root' option");
36
37 const settings = normalizeRuleSettings(options.ruleSettings, options.ruleName);
38
39 if (!settings) {
40 return;
41 }
42
Tim van der Lippecc71b282021-02-12 15:51:14 +000043 // @ts-expect-error - this error should not occur with PostCSS 8
Mathias Bynens79e2cf02020-05-29 16:46:17 +020044 const tmpPostcssResult = new Result();
45
Tim van der Lippe0a9b84d2021-03-24 11:53:15 +000046 rules[options.ruleName](
47 settings[0],
48 /** @type {O} */ (settings[1]),
49 {},
50 )(options.root, tmpPostcssResult);
Mathias Bynens79e2cf02020-05-29 16:46:17 +020051 tmpPostcssResult.warnings().forEach(callback);
Tim van der Lippe16b82282021-11-08 13:50:26 +000052}
53
54module.exports = /** @type {typeof import('stylelint').utils.checkAgainstRule} */ (
55 checkAgainstRule
56);