validateOptions.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. 'use strict';
  2. const arrayEqual = require('./arrayEqual');
  3. const { isPlainObject } = require('./validateTypes');
  4. const IGNORED_OPTIONS = new Set(['severity', 'message', 'reportDisables', 'disableFix']);
  5. /** @typedef {import('stylelint').RuleOptions} RuleOptions */
  6. /** @typedef {import('stylelint').RuleOptionsPossible} Possible */
  7. /** @typedef {import('stylelint').RuleOptionsPossibleFunc} PossibleFunc */
  8. /**
  9. * Validate a rule's options.
  10. *
  11. * See existing rules for examples.
  12. *
  13. * @param {import('stylelint').PostcssResult} result - postcss result
  14. * @param {string} ruleName
  15. * @param {...RuleOptions} optionDescriptions - Each optionDescription can
  16. * have the following properties:
  17. * - `actual` (required): the actual passed option value or object.
  18. * - `possible` (required): a schema representation of what values are
  19. * valid for those options. `possible` should be an object if the
  20. * options are an object, with corresponding keys; if the options are not an
  21. * object, `possible` isn't, either. All `possible` value representations
  22. * should be **arrays of either values or functions**. Values are === checked
  23. * against `actual`. Functions are fed `actual` as an argument and their
  24. * return value is interpreted: truthy = valid, falsy = invalid.
  25. * - `optional` (optional): If this is `true`, `actual` can be undefined.
  26. * @return {boolean} Whether or not the options are valid (true = valid)
  27. */
  28. function validateOptions(result, ruleName, ...optionDescriptions) {
  29. let noErrors = true;
  30. for (const optionDescription of optionDescriptions) {
  31. validate(optionDescription, ruleName, complain);
  32. }
  33. /**
  34. * @param {string} message
  35. */
  36. function complain(message) {
  37. noErrors = false;
  38. result.warn(message, {
  39. stylelintType: 'invalidOption',
  40. });
  41. result.stylelint = result.stylelint || {
  42. disabledRanges: {},
  43. ruleSeverities: {},
  44. customMessages: {},
  45. ruleMetadata: {},
  46. };
  47. result.stylelint.stylelintError = true;
  48. }
  49. return noErrors;
  50. }
  51. /**
  52. * @param {RuleOptions} opts
  53. * @param {string} ruleName
  54. * @param {(message: string) => void} complain
  55. */
  56. function validate(opts, ruleName, complain) {
  57. const possible = opts.possible;
  58. const actual = opts.actual;
  59. const optional = opts.optional;
  60. if (actual === false && !ruleName.startsWith('report')) {
  61. return complain(
  62. `Invalid option value "false" for rule "${ruleName}". Are you trying to disable this rule? If so use "null" instead`,
  63. );
  64. }
  65. if (actual === null || arrayEqual(actual, [null])) {
  66. return;
  67. }
  68. const nothingPossible =
  69. possible === undefined || (Array.isArray(possible) && possible.length === 0);
  70. if (nothingPossible && actual === true) {
  71. return;
  72. }
  73. if (actual === undefined) {
  74. if (nothingPossible || optional) {
  75. return;
  76. }
  77. complain(`Expected option value for rule "${ruleName}"`);
  78. return;
  79. }
  80. if (nothingPossible) {
  81. if (optional) {
  82. complain(
  83. `Incorrect configuration for rule "${ruleName}". Rule should have "possible" values for options validation`,
  84. );
  85. return;
  86. }
  87. complain(`Unexpected option value ${stringify(actual)} for rule "${ruleName}"`);
  88. return;
  89. }
  90. if (typeof possible === 'function') {
  91. if (!possible(actual)) {
  92. complain(`Invalid option ${stringify(actual)} for rule "${ruleName}"`);
  93. }
  94. return;
  95. }
  96. // If `possible` is an array instead of an object ...
  97. if (Array.isArray(possible)) {
  98. for (const a of [actual].flat()) {
  99. if (isValid(possible, a)) {
  100. continue;
  101. }
  102. complain(`Invalid option value ${stringify(a)} for rule "${ruleName}"`);
  103. }
  104. return;
  105. }
  106. // If actual is NOT an object ...
  107. if (!isPlainObject(actual) || typeof actual !== 'object' || actual == null) {
  108. complain(
  109. `Invalid option value ${stringify(actual)} for rule "${ruleName}": should be an object`,
  110. );
  111. return;
  112. }
  113. for (const [optionName, optionValue] of Object.entries(actual)) {
  114. if (IGNORED_OPTIONS.has(optionName)) {
  115. continue;
  116. }
  117. const possibleValue = possible && possible[optionName];
  118. if (!possibleValue) {
  119. complain(`Invalid option name "${optionName}" for rule "${ruleName}"`);
  120. continue;
  121. }
  122. for (const a of [optionValue].flat()) {
  123. if (isValid(possibleValue, a)) {
  124. continue;
  125. }
  126. complain(`Invalid value ${stringify(a)} for option "${optionName}" of rule "${ruleName}"`);
  127. }
  128. }
  129. }
  130. /**
  131. * @param {Possible | Possible[]} possible
  132. * @param {unknown} actual
  133. * @returns {boolean}
  134. */
  135. function isValid(possible, actual) {
  136. for (const possibility of [possible].flat()) {
  137. if (typeof possibility === 'function' && possibility(actual)) {
  138. return true;
  139. }
  140. if (actual === possibility) {
  141. return true;
  142. }
  143. }
  144. return false;
  145. }
  146. /**
  147. * @param {unknown} value
  148. * @returns {string}
  149. */
  150. function stringify(value) {
  151. if (typeof value === 'string') {
  152. return `"${value}"`;
  153. }
  154. return `"${JSON.stringify(value)}"`;
  155. }
  156. module.exports = /** @type {typeof import('stylelint').utils.validateOptions} */ (validateOptions);