validateDisableSettings.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. const validateOptions = require('./utils/validateOptions');
  3. const { isRegExp, isString } = require('./utils/validateTypes');
  4. /**
  5. * @typedef {import('stylelint').PostcssResult} PostcssResult
  6. * @typedef {import('stylelint').DisableOptions} DisableOptions
  7. * @typedef {import('stylelint').DisablePropertyName} DisablePropertyName
  8. * @typedef {import('stylelint').StylelintPostcssResult} StylelintPostcssResult
  9. */
  10. /**
  11. * Validates that the stylelint config for `result` has a valid disable field
  12. * named `field`, and returns the result in normalized form as well as a
  13. * `StylelintPostcssResult` for convenience.
  14. *
  15. * Returns `null` if no disables should be reported, and automatically reports
  16. * an invalid configuration. If this returns non-`null`, it guarantees that
  17. * `result._postcssResult` is defined as well.
  18. *
  19. * @param {PostcssResult | undefined} result
  20. * @param {DisablePropertyName} field
  21. * @return {[boolean, Required<DisableOptions>, StylelintPostcssResult] | null}
  22. */
  23. module.exports = function validateDisableSettings(result, field) {
  24. // Files with `CssSyntaxError`s don't have `_postcssResult`s.
  25. if (!result) return null;
  26. const stylelintResult = result.stylelint;
  27. // Files with linting errors may not have configs associated with them.
  28. if (!stylelintResult.config) return null;
  29. const rawSettings = stylelintResult.config[field];
  30. /** @type {boolean} */
  31. let enabled;
  32. /** @type {DisableOptions} */
  33. let options;
  34. if (Array.isArray(rawSettings)) {
  35. enabled = rawSettings[0];
  36. options = rawSettings[1] || {};
  37. } else {
  38. enabled = rawSettings || false;
  39. options = {};
  40. }
  41. const validOptions = validateOptions(
  42. result,
  43. field,
  44. {
  45. actual: enabled,
  46. possible: [true, false],
  47. },
  48. {
  49. actual: options,
  50. possible: {
  51. except: [isString, isRegExp],
  52. },
  53. },
  54. );
  55. if (!validOptions) return null;
  56. // If the check is disabled with no exceptions, there's no reason to run
  57. // it at all.
  58. if (!enabled && !options.except) return null;
  59. return [
  60. enabled,
  61. {
  62. except: options.except || [],
  63. severity: options.severity || stylelintResult.config.defaultSeverity || 'error',
  64. },
  65. stylelintResult,
  66. ];
  67. };