normalizeRuleSettings.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const { isPlainObject } = require('./utils/validateTypes');
  3. // Rule settings can take a number of forms, e.g.
  4. // a. "rule-name": null
  5. // b. "rule-name": [null, ...]
  6. // c. "rule-name": primaryOption
  7. // d. "rule-name": [primaryOption]
  8. // e. "rule-name": [primaryOption, secondaryOption]
  9. // Where primaryOption can be anything: primitive, Object, or Array.
  10. /**
  11. * This function normalizes all the possibilities into the
  12. * standard form: [primaryOption, secondaryOption]
  13. * Except in the cases with null, a & b, in which case
  14. * null is returned
  15. * @template T
  16. * @template {Object} O
  17. * @param {import('stylelint').ConfigRuleSettings<T, O>} rawSettings
  18. * @param {import('stylelint').Rule<T, O>} [rule]
  19. * @return {[T] | [T, O] | null}
  20. */
  21. module.exports = function normalizeRuleSettings(rawSettings, rule) {
  22. if (rawSettings === null || rawSettings === undefined) {
  23. return null;
  24. }
  25. if (!Array.isArray(rawSettings)) {
  26. return [rawSettings];
  27. }
  28. // Everything below is an array ...
  29. const [primary, secondary] = rawSettings;
  30. if (rawSettings.length > 0 && (primary === null || primary === undefined)) {
  31. return null;
  32. }
  33. if (rule && !rule.primaryOptionArray) {
  34. return rawSettings;
  35. }
  36. // Everything below is a rule that CAN have an array for a primary option ...
  37. // (they might also have something else, e.g. rule-properties-order can
  38. // have the string "alphabetical")
  39. if (rawSettings.length === 1 && Array.isArray(primary)) {
  40. return rawSettings;
  41. }
  42. if (rawSettings.length === 2 && !isPlainObject(primary) && isPlainObject(secondary)) {
  43. return rawSettings;
  44. }
  45. // `T` must be an array type, but TSC thinks it's probably invalid to
  46. // cast `[T]` to `T` so we cast through `any` first.
  47. return [/** @type {T} */ (/** @type {any} */ (rawSettings))];
  48. };