eslint-config-webpack 4.9.6 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,11 +33,58 @@ import config from "eslint-config-webpack";
33
33
 
34
34
  export default defineConfig([
35
35
  {
36
- extends: [config]
37
- }
36
+ extends: [config],
37
+ },
38
38
  ]);
39
39
  ```
40
40
 
41
+ ### Webpack-specific configs
42
+
43
+ Two opt-in configs cover conventions only webpack's own repositories need. They
44
+ are not part of `recommended` — extend them explicitly:
45
+
46
+ ```js
47
+ import { defineConfig } from "eslint/config";
48
+ import config from "eslint-config-webpack";
49
+ import configs from "eslint-config-webpack/configs.js";
50
+
51
+ export default defineConfig([
52
+ {
53
+ extends: [config, configs["webpack/special"], configs["webpack/schemas"]],
54
+ },
55
+ ]);
56
+ ```
57
+
58
+ | Config | Files | What it checks |
59
+ | ----------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
60
+ | `webpack/special` | source files | `webpack/require-license-comment` — every file opens with the MIT license header. |
61
+ | `webpack/schemas` | `**/schemas/**/*.json` | `webpack/valid-schema` — the JSON schema conventions webpack's declaration and validator generators rely on. `webpack/format-schema` — key order, and definitions kept in sync with the base schema (autofixable). |
62
+
63
+ `webpack/valid-schema` accepts options for which keywords a schema may use.
64
+ `keywords` replaces the default set — webpack's own — outright, `allow` adds to
65
+ it and `disallow` removes from it:
66
+
67
+ ```js
68
+ export default defineConfig([
69
+ {
70
+ extends: [configs["webpack/schemas"]],
71
+ rules: {
72
+ "webpack/valid-schema": [
73
+ "error",
74
+ { allow: ["x-generator"], disallow: ["cli"] },
75
+ ],
76
+ },
77
+ },
78
+ ]);
79
+ ```
80
+
81
+ Every other check is unconditional. The rule reports a schema that uses a
82
+ keyword outside that set, puts anything next to a `$ref`, gives `type` more than one
83
+ value, uses `instanceof` without `tsType`, `absolutePath` off a string or
84
+ `properties` off a non-object, describes `properties` without
85
+ `additionalProperties`, nests or mis-sizes `oneOf`/`anyOf`/`allOf`, or leaves a
86
+ property without a description starting in uppercase and ending in a single dot.
87
+
41
88
  [npm]: https://img.shields.io/npm/v/eslint-config-webpack.svg
42
89
  [npm-url]: https://npmjs.com/package/eslint-config-webpack
43
90
  [test]: https://github.com/webpack/eslint-config-webpack/actions/workflows/test.yml/badge.svg
@@ -3,6 +3,10 @@ import { configs } from "../plugins/webpack/index.js";
3
3
  /** @type {import("eslint").Linter.Config} */
4
4
  const recommendedWebpackSpecialConfig = configs.recommended;
5
5
 
6
+ /** @type {import("eslint").Linter.Config} */
7
+ const webpackSchemasConfig = configs.schemas;
8
+
6
9
  export default {
7
10
  "webpack/special": recommendedWebpackSpecialConfig,
11
+ "webpack/schemas": webpackSchemasConfig,
8
12
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-config-webpack",
3
- "version": "4.9.6",
3
+ "version": "4.11.0",
4
4
  "description": "Provides Webpack's eslint rules as an extensible shared config",
5
5
  "keywords": [
6
6
  "eslint",
@@ -46,7 +46,7 @@
46
46
  "eslint-config-prettier": "^10.1.8",
47
47
  "eslint-plugin-import": "^2.32.0",
48
48
  "eslint-plugin-jest": "^29.15.2",
49
- "eslint-plugin-jsdoc": "^62.9.0",
49
+ "eslint-plugin-jsdoc": "^63.0.0",
50
50
  "eslint-plugin-n": "^18.0.1",
51
51
  "eslint-plugin-prettier": "^5.5.5",
52
52
  "eslint-plugin-react": "^7.37.5",
@@ -55,11 +55,11 @@
55
55
  "globals": "^17.6.0",
56
56
  "jsonc-eslint-parser": "^3.1.0",
57
57
  "semver": "^7.8.0",
58
- "sort-package-json": "^3.6.0",
58
+ "sort-package-json": "^4.0.0",
59
59
  "typescript-eslint": "^8.59.3"
60
60
  },
61
61
  "devDependencies": {
62
- "@changesets/cli": "^2.31.0",
62
+ "@changesets/cli": "^3.0.2",
63
63
  "@changesets/get-github-info": "^0.8.0",
64
64
  "@types/semver": "^7.7.1",
65
65
  "eslint": "^9.39.2",
@@ -1,13 +1,19 @@
1
1
  import { createRequire } from "node:module";
2
+ // eslint-disable-next-line import/no-unresolved
3
+ import * as parserJsonc from "jsonc-eslint-parser";
2
4
  import { allExtensions } from "../../configs/utils/extensions.js";
5
+ import { rule as formatSchema } from "./rules/format-schema.js";
3
6
  import { rule as requireLicenseComment } from "./rules/require-license-comment.js";
7
+ import { rule as validSchema } from "./rules/valid-schema.js";
4
8
 
5
9
  const require = createRequire(import.meta.url);
6
10
 
7
11
  const { version } = require("../../package.json");
8
12
 
9
13
  const rules = {
14
+ "format-schema": formatSchema,
10
15
  "require-license-comment": requireLicenseComment,
16
+ "valid-schema": validSchema,
11
17
  };
12
18
 
13
19
  /** @type {import("eslint").Linter.Config["rules"]} */
@@ -19,7 +25,7 @@ const recommendedRules = {
19
25
  ),
20
26
  };
21
27
 
22
- /** @type {Record<"recommended", import("eslint").Linter.Config>} */
28
+ /** @type {Record<"recommended" | "schemas", import("eslint").Linter.Config>} */
23
29
  const configs = {
24
30
  recommended: {
25
31
  name: "webpack/recommended",
@@ -32,6 +38,23 @@ const configs = {
32
38
  },
33
39
  rules: recommendedRules,
34
40
  },
41
+ schemas: {
42
+ name: "webpack/schemas",
43
+ files: ["**/schemas/**/*.json"],
44
+ languageOptions: {
45
+ parser: parserJsonc,
46
+ },
47
+ plugins: {
48
+ get webpack() {
49
+ // eslint-disable-next-line no-use-before-define
50
+ return plugin;
51
+ },
52
+ },
53
+ rules: {
54
+ "webpack/format-schema": "error",
55
+ "webpack/valid-schema": "error",
56
+ },
57
+ },
35
58
  };
36
59
 
37
60
  const plugin = {
@@ -0,0 +1,329 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { KEYWORD_ORDER } from "./schema-keywords.js";
4
+
5
+ /** @typedef {import("jsonc-eslint-parser").AST.JSONProgram} JSONProgram */
6
+ // A schema node holds arbitrary JSON, so its values have no narrower type.
7
+ // eslint-disable-next-line jsdoc/reject-any-type
8
+ /** @typedef {{ [key: string]: any }} Schema */
9
+
10
+ const TYPE_ORDER = [
11
+ "array",
12
+ "enum",
13
+ "RegExp",
14
+ "number",
15
+ "boolean",
16
+ "string",
17
+ "object",
18
+ "Function",
19
+ undefined,
20
+ ];
21
+
22
+ const NESTED_WITH_NAME = ["definitions", "properties"];
23
+
24
+ const NESTED_DIRECT = ["items", "additionalProperties", "not"];
25
+
26
+ const NESTED_ARRAY = ["oneOf", "anyOf", "allOf"];
27
+
28
+ const IMPLEMENTS_PREFIX = "#/definitions/";
29
+
30
+ /**
31
+ * @typedef {object} Visitor
32
+ * @property {((json: Schema, context: VisitContext) => Schema)=} schema schema visitor
33
+ * @property {((json: Schema[], context: VisitContext) => Schema[])=} array array visitor
34
+ * @property {((json: Schema, context: VisitContext) => Schema)=} object object visitor
35
+ */
36
+
37
+ /**
38
+ * @typedef {object} VisitContext
39
+ * @property {Schema} schema the whole schema being processed
40
+ * @property {Schema} definitions its definitions
41
+ * @property {string} importPrefix prefix added to relative `tsType` imports
42
+ */
43
+
44
+ /**
45
+ * @param {Visitor} visitor visitor
46
+ * @param {Schema} json schema node
47
+ * @param {VisitContext} context visit context
48
+ * @returns {Schema} the processed node
49
+ */
50
+ function processSchema(visitor, json, context) {
51
+ json = { ...json };
52
+ if (visitor.schema) json = visitor.schema(json, context);
53
+
54
+ for (const name of NESTED_WITH_NAME) {
55
+ if (name in json && json[name] && typeof json[name] === "object") {
56
+ if (visitor.object) json[name] = visitor.object(json[name], context);
57
+ for (const key of Object.keys(json[name])) {
58
+ json[name][key] = processSchema(visitor, json[name][key], context);
59
+ }
60
+ }
61
+ }
62
+ for (const name of NESTED_DIRECT) {
63
+ if (name in json && json[name] && typeof json[name] === "object") {
64
+ json[name] = processSchema(visitor, json[name], context);
65
+ }
66
+ }
67
+ for (const name of NESTED_ARRAY) {
68
+ if (name in json && Array.isArray(json[name])) {
69
+ json[name] = [...json[name]];
70
+ for (let i = 0; i < json[name].length; i++) {
71
+ json[name][i] = processSchema(visitor, json[name][i], context);
72
+ }
73
+ if (visitor.array) json[name] = visitor.array(json[name], context);
74
+ }
75
+ }
76
+
77
+ return json;
78
+ }
79
+
80
+ /**
81
+ * @param {Schema} object object to sort
82
+ * @returns {Schema} object with alphabetically sorted keys
83
+ */
84
+ function sortObjectAlphabetically(object) {
85
+ /** @type {Schema} */
86
+ const result = {};
87
+ for (const key of Object.keys(object).toSorted()) {
88
+ result[key] = object[key];
89
+ }
90
+ return result;
91
+ }
92
+
93
+ /**
94
+ * @param {Schema[]} array array to sort
95
+ * @returns {Schema[]} the array ordered by the type each branch describes
96
+ */
97
+ function sortArrayByType(array) {
98
+ return array.toSorted((a, b) => {
99
+ const aType = a.type || a.instanceof || (a.enum && "enum");
100
+ const bType = b.type || b.instanceof || (b.enum && "enum");
101
+ const aPosition = TYPE_ORDER.indexOf(aType);
102
+ const bPosition = TYPE_ORDER.indexOf(bType);
103
+ if (aPosition === bPosition) {
104
+ return array.indexOf(a) - array.indexOf(b);
105
+ }
106
+ return aPosition - bPosition;
107
+ });
108
+ }
109
+
110
+ /**
111
+ * @param {Schema} object object to sort
112
+ * @param {string[]} order keys to place first, in this order
113
+ * @returns {Schema} object with its keys reordered
114
+ */
115
+ function sortObjectWithList(object, order) {
116
+ const rest = Object.keys(object)
117
+ .filter((key) => !order.includes(key))
118
+ .toSorted();
119
+ /** @type {Schema} */
120
+ const result = {};
121
+ for (const key of order) {
122
+ if (key in object) {
123
+ result[key] = object[key];
124
+ }
125
+ }
126
+ for (const key of rest) {
127
+ result[key] = object[key];
128
+ }
129
+ return result;
130
+ }
131
+
132
+ /**
133
+ * The base schemas are the ones sitting directly in the `schemas` directory;
134
+ * the plugin schemas below it carry synced copies of their definitions.
135
+ * @param {string} filename absolute path of the schema being linted
136
+ * @returns {{ directory: string, depth: number } | undefined} the schema root
137
+ */
138
+ function findSchemaRoot(filename) {
139
+ const segments = filename.split(/[\\/]/);
140
+ const index = segments.lastIndexOf("schemas");
141
+ if (index === -1) {
142
+ return undefined;
143
+ }
144
+ return {
145
+ directory: segments.slice(0, index + 1).join(path.sep),
146
+ depth: segments.length - index - 2,
147
+ };
148
+ }
149
+
150
+ /**
151
+ * @param {string} directory the `schemas` directory
152
+ * @returns {Map<string, Schema>} definitions declared by the base schemas
153
+ */
154
+ function readBaseDefinitions(directory) {
155
+ /** @type {Map<string, Schema>} */
156
+ const definitions = new Map();
157
+ /** @type {string[]} */
158
+ let entries;
159
+
160
+ try {
161
+ entries = fs.readdirSync(directory);
162
+ } catch {
163
+ return definitions;
164
+ }
165
+
166
+ for (const entry of entries) {
167
+ if (!entry.endsWith(".json")) {
168
+ continue;
169
+ }
170
+ try {
171
+ const json = JSON.parse(
172
+ fs.readFileSync(path.join(directory, entry), "utf8"),
173
+ );
174
+ for (const [name, schema] of Object.entries(json.definitions || {})) {
175
+ definitions.set(name, /** @type {Schema} */ (schema));
176
+ }
177
+ } catch {
178
+ continue;
179
+ }
180
+ }
181
+
182
+ return definitions;
183
+ }
184
+
185
+ /**
186
+ * @param {Schema} definition base definition
187
+ * @param {string} importPrefix prefix to add to its relative imports
188
+ * @returns {Schema} the definition as this schema's depth spells it
189
+ */
190
+ function rebaseDefinition(definition, importPrefix) {
191
+ return processSchema(
192
+ {
193
+ schema: (json) => {
194
+ const { tsType } = json;
195
+ if (!tsType) {
196
+ return json;
197
+ }
198
+ return {
199
+ ...json,
200
+ tsType: tsType.replaceAll("../", `${importPrefix}../`),
201
+ };
202
+ },
203
+ },
204
+ definition,
205
+ /** @type {VisitContext} */ ({}),
206
+ );
207
+ }
208
+
209
+ /**
210
+ * @type {import("eslint").Rule.RuleModule} rule rule
211
+ */
212
+ export const rule = {
213
+ create(context) {
214
+ const root = findSchemaRoot(context.filename);
215
+
216
+ if (!root) {
217
+ return {};
218
+ }
219
+
220
+ return {
221
+ "Program:exit"() {
222
+ const { ast, text } = context.sourceCode;
223
+
224
+ /** @type {Schema} */
225
+ let json;
226
+ /** @type {Schema} */
227
+ let original;
228
+
229
+ try {
230
+ json = JSON.parse(text);
231
+ original = JSON.parse(text);
232
+ } catch {
233
+ return;
234
+ }
235
+
236
+ const baseDefinitions = readBaseDefinitions(root.directory);
237
+ const importPrefix = "../".repeat(root.depth);
238
+ /** @type {(json: Schema, context: VisitContext) => Schema} */
239
+ const format = (node, visitContext) => {
240
+ node = sortObjectWithList(node, KEYWORD_ORDER);
241
+
242
+ if (node.definitions) {
243
+ node.definitions = { ...node.definitions };
244
+ for (const key of Object.keys(node.definitions)) {
245
+ const baseDefinition = baseDefinitions.get(key);
246
+ if (baseDefinition) {
247
+ node.definitions[key] = rebaseDefinition(
248
+ baseDefinition,
249
+ importPrefix,
250
+ );
251
+ }
252
+ }
253
+ }
254
+
255
+ if (node.implements) {
256
+ for (const implemented of [node.implements].flat()) {
257
+ const name = implemented.startsWith(IMPLEMENTS_PREFIX)
258
+ ? implemented.slice(IMPLEMENTS_PREFIX.length)
259
+ : undefined;
260
+ const referenced = name
261
+ ? visitContext.definitions[name]
262
+ : undefined;
263
+ if (!referenced || typeof referenced.properties !== "object") {
264
+ context.report({
265
+ data: { implemented },
266
+ loc: ast.loc,
267
+ messageId: "unresolvedImplements",
268
+ });
269
+ continue;
270
+ }
271
+ node.properties = {
272
+ ...node.properties,
273
+ ...referenced.properties,
274
+ };
275
+ }
276
+ }
277
+
278
+ return node;
279
+ };
280
+
281
+ const formatted = processSchema(
282
+ {
283
+ array: sortArrayByType,
284
+ object: sortObjectAlphabetically,
285
+ schema: format,
286
+ },
287
+ json,
288
+ {
289
+ definitions: json.definitions,
290
+ importPrefix,
291
+ schema: json,
292
+ },
293
+ );
294
+ // Compared by value, not by text: `prettier/prettier` owns the
295
+ // whitespace and collapses what this fix writes expanded.
296
+ if (JSON.stringify(formatted) === JSON.stringify(original)) {
297
+ return;
298
+ }
299
+
300
+ const expected = `${JSON.stringify(formatted, null, 2)}\n`;
301
+
302
+ context.report({
303
+ fix(fixer) {
304
+ return fixer.replaceText(ast, expected);
305
+ },
306
+ loc: ast.loc,
307
+ messageId: "unformatted",
308
+ });
309
+ },
310
+ };
311
+ },
312
+ meta: {
313
+ docs: {
314
+ category: "Stylistic Issues",
315
+ description:
316
+ "Keep schema keys ordered and shared definitions in sync with the base schema",
317
+ recommended: false,
318
+ },
319
+ fixable: "code",
320
+ messages: {
321
+ unformatted:
322
+ "Schema is not formatted. Run the ESLint auto-fixer to correct.",
323
+ unresolvedImplements:
324
+ '"implements": "{{implemented}}" does not name a definition with properties.',
325
+ },
326
+ schema: [],
327
+ type: "layout",
328
+ },
329
+ };
@@ -0,0 +1,49 @@
1
+ // The one vocabulary `webpack/valid-schema` and `webpack/format-schema` share:
2
+ // keeping them in separate lists is how the two drifted apart.
3
+
4
+ // Key order inside every schema object. A keyword absent from here sorts
5
+ // alphabetically after these.
6
+ export const KEYWORD_ORDER = [
7
+ "$ref",
8
+ "definitions",
9
+ "$id",
10
+ "id",
11
+ "title",
12
+ "description",
13
+ "type",
14
+ "cli",
15
+ "items",
16
+ "minItems",
17
+ "uniqueItems",
18
+ "implements",
19
+ "additionalProperties",
20
+ "properties",
21
+ "required",
22
+ "minProperties",
23
+ "oneOf",
24
+ "anyOf",
25
+ "allOf",
26
+ "enum",
27
+ "absolutePath",
28
+ "undefinedAsNull",
29
+ "minLength",
30
+ "minimum",
31
+ "instanceof",
32
+ "tsType",
33
+ "deprecated",
34
+ "experimental",
35
+ "added",
36
+ ];
37
+
38
+ // Valid keywords with no fixed position, so they sort alphabetically among
39
+ // themselves after the ordered ones.
40
+ const UNORDERED_KEYWORDS = ["link", "maximum", "not", "pattern"];
41
+
42
+ // The draft-04 spelling of `$id`, which the generators do not read. It keeps
43
+ // its slot in the order so a schema carrying it still formats predictably.
44
+ const REJECTED_KEYWORDS = new Set(["id"]);
45
+
46
+ export const DEFAULT_KEYWORDS = [
47
+ ...KEYWORD_ORDER.filter((keyword) => !REJECTED_KEYWORDS.has(keyword)),
48
+ ...UNORDERED_KEYWORDS,
49
+ ];
@@ -0,0 +1,336 @@
1
+ /** @typedef {import("jsonc-eslint-parser").AST.JSONExpression} JSONExpression */
2
+ /** @typedef {import("jsonc-eslint-parser").AST.JSONNode} JSONNode */
3
+ /** @typedef {import("jsonc-eslint-parser").AST.JSONObjectExpression} JSONObjectExpression */
4
+ /** @typedef {import("jsonc-eslint-parser").AST.JSONProgram} JSONProgram */
5
+ /** @typedef {import("jsonc-eslint-parser").AST.JSONProperty} JSONProperty */
6
+
7
+ import { DEFAULT_KEYWORDS } from "./schema-keywords.js";
8
+
9
+ const COMBINATOR_KEYWORDS = ["oneOf", "anyOf", "allOf"];
10
+
11
+ const DESCRIPTION_REGEXP = /^[A-Z`].*[^.]\.$/;
12
+
13
+ /**
14
+ * @param {JSONProperty} property property node
15
+ * @returns {string} name of the keyword the property declares
16
+ */
17
+ function getKeywordName(property) {
18
+ const { key } = property;
19
+
20
+ return key.type === "JSONIdentifier" ? key.name : String(key.value);
21
+ }
22
+
23
+ /**
24
+ * @param {JSONExpression | null} node schema node
25
+ * @param {string} name keyword name
26
+ * @returns {JSONProperty | undefined} property declaring the keyword
27
+ */
28
+ function getKeyword(node, name) {
29
+ if (!node || node.type !== "JSONObjectExpression") {
30
+ return undefined;
31
+ }
32
+
33
+ return node.properties.find((property) => getKeywordName(property) === name);
34
+ }
35
+
36
+ /**
37
+ * @param {JSONExpression | null | undefined} node schema node
38
+ * @param {string} expected expected string value
39
+ * @returns {boolean} whether the node is exactly that string literal
40
+ */
41
+ function isStringLiteral(node, expected) {
42
+ return Boolean(
43
+ node && node.type === "JSONLiteral" && node.value === expected,
44
+ );
45
+ }
46
+
47
+ /**
48
+ * A schema that only points at another one carries its description there.
49
+ * @param {JSONExpression | null} node schema node
50
+ * @returns {boolean} whether the node is a plain reference
51
+ */
52
+ function isReference(node) {
53
+ if (getKeyword(node, "$ref")) {
54
+ return true;
55
+ }
56
+
57
+ const oneOf = getKeyword(node, "oneOf");
58
+
59
+ return Boolean(
60
+ oneOf &&
61
+ oneOf.value.type === "JSONArrayExpression" &&
62
+ oneOf.value.elements.length === 1 &&
63
+ getKeyword(oneOf.value.elements[0], "$ref"),
64
+ );
65
+ }
66
+
67
+ /**
68
+ * @type {import("eslint").Rule.RuleModule} rule rule
69
+ */
70
+ export const rule = {
71
+ create(context) {
72
+ const {
73
+ allow = [],
74
+ disallow = [],
75
+ keywords = DEFAULT_KEYWORDS,
76
+ } = context.options[0] || {};
77
+ const allowedKeywords = new Set([...keywords, ...allow]);
78
+
79
+ for (const keyword of disallow) {
80
+ allowedKeywords.delete(keyword);
81
+ }
82
+
83
+ /**
84
+ * @param {JSONExpression | null} node schema node
85
+ * @param {JSONNode} target node the diagnostic points at
86
+ * @returns {void}
87
+ */
88
+ function validateDescription(node, target) {
89
+ if (isReference(node)) {
90
+ return;
91
+ }
92
+
93
+ const description = getKeyword(node, "description");
94
+ const value = description && description.value;
95
+
96
+ if (
97
+ !value ||
98
+ value.type !== "JSONLiteral" ||
99
+ typeof value.value !== "string" ||
100
+ value.value.length === 0
101
+ ) {
102
+ context.report({ loc: target.loc, messageId: "missingDescription" });
103
+
104
+ return;
105
+ }
106
+
107
+ if (!DESCRIPTION_REGEXP.test(value.value)) {
108
+ context.report({ loc: value.loc, messageId: "invalidDescription" });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * @param {JSONExpression | null} node schema node
114
+ * @returns {void}
115
+ */
116
+ function walk(node) {
117
+ if (!node || node.type !== "JSONObjectExpression") {
118
+ return;
119
+ }
120
+
121
+ const hasRef = Boolean(getKeyword(node, "$ref"));
122
+
123
+ for (const property of node.properties) {
124
+ const name = getKeywordName(property);
125
+
126
+ if (!allowedKeywords.has(name)) {
127
+ context.report({
128
+ data: { keyword: name },
129
+ loc: property.key.loc,
130
+ messageId: "unknownKeyword",
131
+ });
132
+ }
133
+
134
+ if (hasRef && name !== "$ref") {
135
+ context.report({
136
+ data: { keyword: name },
137
+ loc: property.key.loc,
138
+ messageId: "refWithOtherKeywords",
139
+ });
140
+ }
141
+ }
142
+
143
+ const type = getKeyword(node, "type");
144
+
145
+ if (
146
+ type &&
147
+ (type.value.type !== "JSONLiteral" ||
148
+ typeof type.value.value !== "string")
149
+ ) {
150
+ context.report({ loc: type.value.loc, messageId: "multipleTypes" });
151
+ }
152
+
153
+ const instanceOf = getKeyword(node, "instanceof");
154
+
155
+ if (instanceOf && !getKeyword(node, "tsType")) {
156
+ context.report({
157
+ loc: instanceOf.key.loc,
158
+ messageId: "instanceofRequiresTsType",
159
+ });
160
+ }
161
+
162
+ const absolutePath = getKeyword(node, "absolutePath");
163
+
164
+ if (absolutePath && !isStringLiteral(type && type.value, "string")) {
165
+ context.report({
166
+ loc: absolutePath.key.loc,
167
+ messageId: "absolutePathRequiresStringType",
168
+ });
169
+ }
170
+
171
+ const properties = getKeyword(node, "properties");
172
+ const additionalProperties = getKeyword(node, "additionalProperties");
173
+
174
+ for (const keyword of [properties, additionalProperties]) {
175
+ if (keyword && !isStringLiteral(type && type.value, "object")) {
176
+ context.report({
177
+ data: { keyword: getKeywordName(keyword) },
178
+ loc: keyword.key.loc,
179
+ messageId: "objectKeywordRequiresObjectType",
180
+ });
181
+ }
182
+ }
183
+
184
+ for (const name of COMBINATOR_KEYWORDS) {
185
+ const keyword = getKeyword(node, name);
186
+
187
+ if (!keyword || keyword.value.type !== "JSONArrayExpression") {
188
+ continue;
189
+ }
190
+
191
+ const { elements } = keyword.value;
192
+
193
+ if (elements.length === 0) {
194
+ context.report({
195
+ data: { keyword: name },
196
+ loc: keyword.key.loc,
197
+ messageId: "emptyCombinator",
198
+ });
199
+ } else if ((elements.length === 1) !== (name === "oneOf")) {
200
+ context.report({
201
+ data: { keyword: name },
202
+ loc: keyword.key.loc,
203
+ messageId:
204
+ name === "oneOf" ? "oneOfSingleItem" : "combinatorMultipleItems",
205
+ });
206
+ }
207
+
208
+ for (const element of elements) {
209
+ if (!element) {
210
+ continue;
211
+ }
212
+
213
+ if (COMBINATOR_KEYWORDS.some((other) => getKeyword(element, other))) {
214
+ context.report({
215
+ loc: element.loc,
216
+ messageId: "nestedCombinator",
217
+ });
218
+ }
219
+
220
+ walk(element);
221
+ }
222
+ }
223
+
224
+ const items = getKeyword(node, "items");
225
+
226
+ if (items) {
227
+ validateDescription(items.value, items.key);
228
+ walk(items.value);
229
+ }
230
+
231
+ const definitions = getKeyword(node, "definitions");
232
+
233
+ if (definitions && definitions.value.type === "JSONObjectExpression") {
234
+ for (const definition of definitions.value.properties) {
235
+ validateDescription(definition.value, definition.key);
236
+ walk(definition.value);
237
+ }
238
+ }
239
+
240
+ if (properties) {
241
+ if (!additionalProperties) {
242
+ context.report({
243
+ loc: properties.key.loc,
244
+ messageId: "missingAdditionalProperties",
245
+ });
246
+ }
247
+
248
+ if (properties.value.type === "JSONObjectExpression") {
249
+ for (const property of properties.value.properties) {
250
+ validateDescription(property.value, property.key);
251
+ walk(property.value);
252
+ }
253
+ }
254
+ }
255
+
256
+ if (
257
+ additionalProperties &&
258
+ additionalProperties.value.type === "JSONObjectExpression"
259
+ ) {
260
+ validateDescription(
261
+ additionalProperties.value,
262
+ additionalProperties.key,
263
+ );
264
+ walk(additionalProperties.value);
265
+ }
266
+ }
267
+
268
+ return {
269
+ "Program:exit"() {
270
+ const { ast } = context.sourceCode;
271
+ const program =
272
+ /** @type {JSONProgram} */
273
+ (/** @type {unknown} */ (ast));
274
+ const [statement] = program.body;
275
+
276
+ if (!statement || statement.type !== "JSONExpressionStatement") {
277
+ return;
278
+ }
279
+
280
+ walk(statement.expression);
281
+ },
282
+ };
283
+ },
284
+ meta: {
285
+ docs: {
286
+ category: "Possible Errors",
287
+ description: "Enforce webpack's conventions for JSON schema files",
288
+ recommended: false,
289
+ },
290
+ messages: {
291
+ absolutePathRequiresStringType:
292
+ 'When using "absolutePath", "type" must be "string".',
293
+ combinatorMultipleItems: '"{{keyword}}" must have more than one item.',
294
+ emptyCombinator: '"{{keyword}}" must not be empty.',
295
+ instanceofRequiresTsType:
296
+ 'When using "instanceof", "tsType" is required.',
297
+ invalidDescription:
298
+ "Description should start with an uppercase letter and end with a single dot.",
299
+ missingAdditionalProperties:
300
+ 'Should have "additionalProperties" set to some value when describing "properties".',
301
+ missingDescription: "Should have a description set.",
302
+ multipleTypes: 'Should have a single "type".',
303
+ nestedCombinator: 'Should not double nest "oneOf"/"anyOf"/"allOf".',
304
+ objectKeywordRequiresObjectType:
305
+ 'When using "{{keyword}}", "type" must be "object".',
306
+ oneOfSingleItem: '"oneOf" must have exactly one item.',
307
+ refWithOtherKeywords:
308
+ 'When using "$ref" no other properties are possible, but found "{{keyword}}".',
309
+ unknownKeyword: 'Unexpected keyword "{{keyword}}".',
310
+ },
311
+ schema: [
312
+ {
313
+ additionalProperties: false,
314
+ properties: {
315
+ allow: {
316
+ items: { type: "string" },
317
+ type: "array",
318
+ uniqueItems: true,
319
+ },
320
+ disallow: {
321
+ items: { type: "string" },
322
+ type: "array",
323
+ uniqueItems: true,
324
+ },
325
+ keywords: {
326
+ items: { type: "string" },
327
+ type: "array",
328
+ uniqueItems: true,
329
+ },
330
+ },
331
+ type: "object",
332
+ },
333
+ ],
334
+ type: "problem",
335
+ },
336
+ };