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