config-validator.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /**
  2. * @fileoverview Validates configs.
  3. * @author Brandon Mills
  4. */
  5. /* eslint class-methods-use-this: "off" */
  6. //------------------------------------------------------------------------------
  7. // Typedefs
  8. //------------------------------------------------------------------------------
  9. /** @typedef {import("../shared/types").Rule} Rule */
  10. //------------------------------------------------------------------------------
  11. // Requirements
  12. //------------------------------------------------------------------------------
  13. import util from "util";
  14. import * as ConfigOps from "./config-ops.js";
  15. import { emitDeprecationWarning } from "./deprecation-warnings.js";
  16. import ajvOrig from "./ajv.js";
  17. import { deepMergeArrays } from "./deep-merge-arrays.js";
  18. import configSchema from "../../conf/config-schema.js";
  19. import BuiltInEnvironments from "../../conf/environments.js";
  20. const ajv = ajvOrig();
  21. const ruleValidators = new WeakMap();
  22. const noop = Function.prototype;
  23. //------------------------------------------------------------------------------
  24. // Private
  25. //------------------------------------------------------------------------------
  26. let validateSchema;
  27. const severityMap = {
  28. error: 2,
  29. warn: 1,
  30. off: 0
  31. };
  32. const validated = new WeakSet();
  33. // JSON schema that disallows passing any options
  34. const noOptionsSchema = Object.freeze({
  35. type: "array",
  36. minItems: 0,
  37. maxItems: 0
  38. });
  39. //-----------------------------------------------------------------------------
  40. // Exports
  41. //-----------------------------------------------------------------------------
  42. export default class ConfigValidator {
  43. constructor({ builtInRules = new Map() } = {}) {
  44. this.builtInRules = builtInRules;
  45. }
  46. /**
  47. * Gets a complete options schema for a rule.
  48. * @param {Rule} rule A rule object
  49. * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`.
  50. * @returns {Object|null} JSON Schema for the rule's options.
  51. * `null` if rule wasn't passed or its `meta.schema` is `false`.
  52. */
  53. getRuleOptionsSchema(rule) {
  54. if (!rule) {
  55. return null;
  56. }
  57. if (!rule.meta) {
  58. return { ...noOptionsSchema }; // default if `meta.schema` is not specified
  59. }
  60. const schema = rule.meta.schema;
  61. if (typeof schema === "undefined") {
  62. return { ...noOptionsSchema }; // default if `meta.schema` is not specified
  63. }
  64. // `schema:false` is an allowed explicit opt-out of options validation for the rule
  65. if (schema === false) {
  66. return null;
  67. }
  68. if (typeof schema !== "object" || schema === null) {
  69. throw new TypeError("Rule's `meta.schema` must be an array or object");
  70. }
  71. // ESLint-specific array form needs to be converted into a valid JSON Schema definition
  72. if (Array.isArray(schema)) {
  73. if (schema.length) {
  74. return {
  75. type: "array",
  76. items: schema,
  77. minItems: 0,
  78. maxItems: schema.length
  79. };
  80. }
  81. // `schema:[]` is an explicit way to specify that the rule does not accept any options
  82. return { ...noOptionsSchema };
  83. }
  84. // `schema:<object>` is assumed to be a valid JSON Schema definition
  85. return schema;
  86. }
  87. /**
  88. * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
  89. * @param {options} options The given options for the rule.
  90. * @returns {number|string} The rule's severity value
  91. */
  92. validateRuleSeverity(options) {
  93. const severity = Array.isArray(options) ? options[0] : options;
  94. const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
  95. if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
  96. return normSeverity;
  97. }
  98. throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
  99. }
  100. /**
  101. * Validates the non-severity options passed to a rule, based on its schema.
  102. * @param {{create: Function}} rule The rule to validate
  103. * @param {Array} localOptions The options for the rule, excluding severity
  104. * @returns {void}
  105. */
  106. validateRuleSchema(rule, localOptions) {
  107. if (!ruleValidators.has(rule)) {
  108. try {
  109. const schema = this.getRuleOptionsSchema(rule);
  110. if (schema) {
  111. ruleValidators.set(rule, ajv.compile(schema));
  112. }
  113. } catch (err) {
  114. const errorWithCode = new Error(err.message, { cause: err });
  115. errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA";
  116. throw errorWithCode;
  117. }
  118. }
  119. const validateRule = ruleValidators.get(rule);
  120. if (validateRule) {
  121. const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions);
  122. validateRule(mergedOptions);
  123. if (validateRule.errors) {
  124. throw new Error(validateRule.errors.map(
  125. error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
  126. ).join(""));
  127. }
  128. }
  129. }
  130. /**
  131. * Validates a rule's options against its schema.
  132. * @param {{create: Function}|null} rule The rule that the config is being validated for
  133. * @param {string} ruleId The rule's unique name.
  134. * @param {Array|number} options The given options for the rule.
  135. * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
  136. * no source is prepended to the message.
  137. * @returns {void}
  138. */
  139. validateRuleOptions(rule, ruleId, options, source = null) {
  140. try {
  141. const severity = this.validateRuleSeverity(options);
  142. if (severity !== 0) {
  143. this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
  144. }
  145. } catch (err) {
  146. let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"
  147. ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}`
  148. : `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
  149. if (typeof source === "string") {
  150. enhancedMessage = `${source}:\n\t${enhancedMessage}`;
  151. }
  152. const enhancedError = new Error(enhancedMessage, { cause: err });
  153. if (err.code) {
  154. enhancedError.code = err.code;
  155. }
  156. throw enhancedError;
  157. }
  158. }
  159. /**
  160. * Validates an environment object
  161. * @param {Object} environment The environment config object to validate.
  162. * @param {string} source The name of the configuration source to report in any errors.
  163. * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
  164. * @returns {void}
  165. */
  166. validateEnvironment(
  167. environment,
  168. source,
  169. getAdditionalEnv = noop
  170. ) {
  171. // not having an environment is ok
  172. if (!environment) {
  173. return;
  174. }
  175. Object.keys(environment).forEach(id => {
  176. const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
  177. if (!env) {
  178. const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
  179. throw new Error(message);
  180. }
  181. });
  182. }
  183. /**
  184. * Validates a rules config object
  185. * @param {Object} rulesConfig The rules config object to validate.
  186. * @param {string} source The name of the configuration source to report in any errors.
  187. * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
  188. * @returns {void}
  189. */
  190. validateRules(
  191. rulesConfig,
  192. source,
  193. getAdditionalRule = noop
  194. ) {
  195. if (!rulesConfig) {
  196. return;
  197. }
  198. Object.keys(rulesConfig).forEach(id => {
  199. const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
  200. this.validateRuleOptions(rule, id, rulesConfig[id], source);
  201. });
  202. }
  203. /**
  204. * Validates a `globals` section of a config file
  205. * @param {Object} globalsConfig The `globals` section
  206. * @param {string|null} source The name of the configuration source to report in the event of an error.
  207. * @returns {void}
  208. */
  209. validateGlobals(globalsConfig, source = null) {
  210. if (!globalsConfig) {
  211. return;
  212. }
  213. Object.entries(globalsConfig)
  214. .forEach(([configuredGlobal, configuredValue]) => {
  215. try {
  216. ConfigOps.normalizeConfigGlobal(configuredValue);
  217. } catch (err) {
  218. throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
  219. }
  220. });
  221. }
  222. /**
  223. * Validate `processor` configuration.
  224. * @param {string|undefined} processorName The processor name.
  225. * @param {string} source The name of config file.
  226. * @param {function(id:string): Processor} getProcessor The getter of defined processors.
  227. * @returns {void}
  228. */
  229. validateProcessor(processorName, source, getProcessor) {
  230. if (processorName && !getProcessor(processorName)) {
  231. throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
  232. }
  233. }
  234. /**
  235. * Formats an array of schema validation errors.
  236. * @param {Array} errors An array of error messages to format.
  237. * @returns {string} Formatted error message
  238. */
  239. formatErrors(errors) {
  240. return errors.map(error => {
  241. if (error.keyword === "additionalProperties") {
  242. const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
  243. return `Unexpected top-level property "${formattedPropertyPath}"`;
  244. }
  245. if (error.keyword === "type") {
  246. const formattedField = error.dataPath.slice(1);
  247. const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
  248. const formattedValue = JSON.stringify(error.data);
  249. return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
  250. }
  251. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  252. return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
  253. }).map(message => `\t- ${message}.\n`).join("");
  254. }
  255. /**
  256. * Validates the top level properties of the config object.
  257. * @param {Object} config The config object to validate.
  258. * @param {string} source The name of the configuration source to report in any errors.
  259. * @returns {void}
  260. */
  261. validateConfigSchema(config, source = null) {
  262. validateSchema = validateSchema || ajv.compile(configSchema);
  263. if (!validateSchema(config)) {
  264. throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
  265. }
  266. if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
  267. emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
  268. }
  269. }
  270. /**
  271. * Validates an entire config object.
  272. * @param {Object} config The config object to validate.
  273. * @param {string} source The name of the configuration source to report in any errors.
  274. * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
  275. * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
  276. * @returns {void}
  277. */
  278. validate(config, source, getAdditionalRule, getAdditionalEnv) {
  279. this.validateConfigSchema(config, source);
  280. this.validateRules(config.rules, source, getAdditionalRule);
  281. this.validateEnvironment(config.env, source, getAdditionalEnv);
  282. this.validateGlobals(config.globals, source);
  283. for (const override of config.overrides || []) {
  284. this.validateRules(override.rules, source, getAdditionalRule);
  285. this.validateEnvironment(override.env, source, getAdditionalEnv);
  286. this.validateGlobals(config.globals, source);
  287. }
  288. }
  289. /**
  290. * Validate config array object.
  291. * @param {ConfigArray} configArray The config array to validate.
  292. * @returns {void}
  293. */
  294. validateConfigArray(configArray) {
  295. const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
  296. const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
  297. const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
  298. // Validate.
  299. for (const element of configArray) {
  300. if (validated.has(element)) {
  301. continue;
  302. }
  303. validated.add(element);
  304. this.validateEnvironment(element.env, element.name, getPluginEnv);
  305. this.validateGlobals(element.globals, element.name);
  306. this.validateProcessor(element.processor, element.name, getPluginProcessor);
  307. this.validateRules(element.rules, element.name, getPluginRule);
  308. }
  309. }
  310. }