normalizeRuleSettings.mjs 1.7 KB

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