config-validator.js 13 KB

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