Ohm-Management - Projektarbeit B-ME
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.

config-validator.js 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /**
  2. * @fileoverview Validates configs.
  3. * @author Brandon Mills
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const path = require("path"),
  10. ajv = require("../util/ajv"),
  11. lodash = require("lodash"),
  12. configSchema = require("../../conf/config-schema.js"),
  13. util = require("util");
  14. const ruleValidators = new WeakMap();
  15. //------------------------------------------------------------------------------
  16. // Private
  17. //------------------------------------------------------------------------------
  18. let validateSchema;
  19. // Defitions for deprecation warnings.
  20. const deprecationWarningMessages = {
  21. ESLINT_LEGACY_ECMAFEATURES: "The 'ecmaFeatures' config file property is deprecated, and has no effect.",
  22. ESLINT_LEGACY_OBJECT_REST_SPREAD: "The 'parserOptions.ecmaFeatures.experimentalObjectRestSpread' option is deprecated. Use 'parserOptions.ecmaVersion' instead."
  23. };
  24. const severityMap = {
  25. error: 2,
  26. warn: 1,
  27. off: 0
  28. };
  29. /**
  30. * Gets a complete options schema for a rule.
  31. * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
  32. * @returns {Object} JSON Schema for the rule's options.
  33. */
  34. function getRuleOptionsSchema(rule) {
  35. const schema = rule.schema || rule.meta && rule.meta.schema;
  36. // Given a tuple of schemas, insert warning level at the beginning
  37. if (Array.isArray(schema)) {
  38. if (schema.length) {
  39. return {
  40. type: "array",
  41. items: schema,
  42. minItems: 0,
  43. maxItems: schema.length
  44. };
  45. }
  46. return {
  47. type: "array",
  48. minItems: 0,
  49. maxItems: 0
  50. };
  51. }
  52. // Given a full schema, leave it alone
  53. return schema || null;
  54. }
  55. /**
  56. * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
  57. * @param {options} options The given options for the rule.
  58. * @returns {number|string} The rule's severity value
  59. */
  60. function validateRuleSeverity(options) {
  61. const severity = Array.isArray(options) ? options[0] : options;
  62. const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
  63. if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
  64. return normSeverity;
  65. }
  66. throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, "")}').\n`);
  67. }
  68. /**
  69. * Validates the non-severity options passed to a rule, based on its schema.
  70. * @param {{create: Function}} rule The rule to validate
  71. * @param {array} localOptions The options for the rule, excluding severity
  72. * @returns {void}
  73. */
  74. function validateRuleSchema(rule, localOptions) {
  75. if (!ruleValidators.has(rule)) {
  76. const schema = getRuleOptionsSchema(rule);
  77. if (schema) {
  78. ruleValidators.set(rule, ajv.compile(schema));
  79. }
  80. }
  81. const validateRule = ruleValidators.get(rule);
  82. if (validateRule) {
  83. validateRule(localOptions);
  84. if (validateRule.errors) {
  85. throw new Error(validateRule.errors.map(
  86. error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
  87. ).join(""));
  88. }
  89. }
  90. }
  91. /**
  92. * Validates a rule's options against its schema.
  93. * @param {{create: Function}|null} rule The rule that the config is being validated for
  94. * @param {string} ruleId The rule's unique name.
  95. * @param {array|number} options The given options for the rule.
  96. * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
  97. * no source is prepended to the message.
  98. * @returns {void}
  99. */
  100. function validateRuleOptions(rule, ruleId, options, source) {
  101. if (!rule) {
  102. return;
  103. }
  104. try {
  105. const severity = validateRuleSeverity(options);
  106. if (severity !== 0) {
  107. validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
  108. }
  109. } catch (err) {
  110. const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
  111. if (typeof source === "string") {
  112. throw new Error(`${source}:\n\t${enhancedMessage}`);
  113. } else {
  114. throw new Error(enhancedMessage);
  115. }
  116. }
  117. }
  118. /**
  119. * Validates an environment object
  120. * @param {Object} environment The environment config object to validate.
  121. * @param {string} source The name of the configuration source to report in any errors.
  122. * @param {Environments} envContext Env context
  123. * @returns {void}
  124. */
  125. function validateEnvironment(environment, source, envContext) {
  126. // not having an environment is ok
  127. if (!environment) {
  128. return;
  129. }
  130. Object.keys(environment).forEach(env => {
  131. if (!envContext.get(env)) {
  132. const message = `${source}:\n\tEnvironment key "${env}" is unknown\n`;
  133. throw new Error(message);
  134. }
  135. });
  136. }
  137. /**
  138. * Validates a rules config object
  139. * @param {Object} rulesConfig The rules config object to validate.
  140. * @param {string} source The name of the configuration source to report in any errors.
  141. * @param {function(string): {create: Function}} ruleMapper A mapper function from strings to loaded rules
  142. * @returns {void}
  143. */
  144. function validateRules(rulesConfig, source, ruleMapper) {
  145. if (!rulesConfig) {
  146. return;
  147. }
  148. Object.keys(rulesConfig).forEach(id => {
  149. validateRuleOptions(ruleMapper(id), id, rulesConfig[id], source);
  150. });
  151. }
  152. /**
  153. * Formats an array of schema validation errors.
  154. * @param {Array} errors An array of error messages to format.
  155. * @returns {string} Formatted error message
  156. */
  157. function formatErrors(errors) {
  158. return errors.map(error => {
  159. if (error.keyword === "additionalProperties") {
  160. const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
  161. return `Unexpected top-level property "${formattedPropertyPath}"`;
  162. }
  163. if (error.keyword === "type") {
  164. const formattedField = error.dataPath.slice(1);
  165. const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
  166. const formattedValue = JSON.stringify(error.data);
  167. return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
  168. }
  169. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  170. return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
  171. }).map(message => `\t- ${message}.\n`).join("");
  172. }
  173. /**
  174. * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
  175. * for each unique file path, but repeated invocations with the same file path have no effect.
  176. * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
  177. * @param {string} source The name of the configuration source to report the warning for.
  178. * @param {string} errorCode The warning message to show.
  179. * @returns {void}
  180. */
  181. const emitDeprecationWarning = lodash.memoize((source, errorCode) => {
  182. const rel = path.relative(process.cwd(), source);
  183. const message = deprecationWarningMessages[errorCode];
  184. process.emitWarning(
  185. `${message} (found in "${rel}")`,
  186. "DeprecationWarning",
  187. errorCode
  188. );
  189. });
  190. /**
  191. * Validates the top level properties of the config object.
  192. * @param {Object} config The config object to validate.
  193. * @param {string} source The name of the configuration source to report in any errors.
  194. * @returns {void}
  195. */
  196. function validateConfigSchema(config, source) {
  197. validateSchema = validateSchema || ajv.compile(configSchema);
  198. if (!validateSchema(config)) {
  199. throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`);
  200. }
  201. if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
  202. emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
  203. }
  204. if (
  205. (config.parser || "espree") === "espree" &&
  206. config.parserOptions &&
  207. config.parserOptions.ecmaFeatures &&
  208. config.parserOptions.ecmaFeatures.experimentalObjectRestSpread
  209. ) {
  210. emitDeprecationWarning(source, "ESLINT_LEGACY_OBJECT_REST_SPREAD");
  211. }
  212. }
  213. /**
  214. * Validates an entire 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. * @param {function(string): {create: Function}} ruleMapper A mapper function from rule IDs to defined rules
  218. * @param {Environments} envContext The env context
  219. * @returns {void}
  220. */
  221. function validate(config, source, ruleMapper, envContext) {
  222. validateConfigSchema(config, source);
  223. validateRules(config.rules, source, ruleMapper);
  224. validateEnvironment(config.env, source, envContext);
  225. for (const override of config.overrides || []) {
  226. validateRules(override.rules, source, ruleMapper);
  227. validateEnvironment(override.env, source, envContext);
  228. }
  229. }
  230. //------------------------------------------------------------------------------
  231. // Public Interface
  232. //------------------------------------------------------------------------------
  233. module.exports = {
  234. getRuleOptionsSchema,
  235. validate,
  236. validateRuleOptions
  237. };