You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
11 KiB

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