config-validator.js 11 KB

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