config-validator.js 12 KB

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