eslint-config-webpack 4.10.0 → 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
@@ -55,10 +55,10 @@ export default defineConfig([
55
55
  ]);
56
56
  ```
57
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. |
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
62
 
63
63
  `webpack/valid-schema` accepts options for which keywords a schema may use.
64
64
  `keywords` replaces the default set — webpack's own — outright, `allow` adds to
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-config-webpack",
3
- "version": "4.10.0",
3
+ "version": "4.11.0",
4
4
  "description": "Provides Webpack's eslint rules as an extensible shared config",
5
5
  "keywords": [
6
6
  "eslint",
@@ -59,7 +59,7 @@
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",
@@ -2,6 +2,7 @@ import { createRequire } from "node:module";
2
2
  // eslint-disable-next-line import/no-unresolved
3
3
  import * as parserJsonc from "jsonc-eslint-parser";
4
4
  import { allExtensions } from "../../configs/utils/extensions.js";
5
+ import { rule as formatSchema } from "./rules/format-schema.js";
5
6
  import { rule as requireLicenseComment } from "./rules/require-license-comment.js";
6
7
  import { rule as validSchema } from "./rules/valid-schema.js";
7
8
 
@@ -10,6 +11,7 @@ const require = createRequire(import.meta.url);
10
11
  const { version } = require("../../package.json");
11
12
 
12
13
  const rules = {
14
+ "format-schema": formatSchema,
13
15
  "require-license-comment": requireLicenseComment,
14
16
  "valid-schema": validSchema,
15
17
  };
@@ -49,6 +51,7 @@ const configs = {
49
51
  },
50
52
  },
51
53
  rules: {
54
+ "webpack/format-schema": "error",
52
55
  "webpack/valid-schema": "error",
53
56
  },
54
57
  },
@@ -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
+ ];
@@ -4,41 +4,7 @@
4
4
  /** @typedef {import("jsonc-eslint-parser").AST.JSONProgram} JSONProgram */
5
5
  /** @typedef {import("jsonc-eslint-parser").AST.JSONProperty} JSONProperty */
6
6
 
7
- // Keep in sync with the keywords `webpack/tooling` knows how to compile into
8
- // declarations and validators - an unknown one is silently dropped there.
9
- const DEFAULT_KEYWORDS = [
10
- "definitions",
11
- "$ref",
12
- "$id",
13
- "title",
14
- "cli",
15
- "items",
16
- "implements",
17
- "properties",
18
- "additionalProperties",
19
- "type",
20
- "oneOf",
21
- "anyOf",
22
- "absolutePath",
23
- "undefinedAsNull",
24
- "description",
25
- "enum",
26
- "minLength",
27
- "pattern",
28
- "minimum",
29
- "maximum",
30
- "required",
31
- "uniqueItems",
32
- "minItems",
33
- "minProperties",
34
- "instanceof",
35
- "tsType",
36
- "not",
37
- "link",
38
- "deprecated",
39
- "experimental",
40
- "added",
41
- ];
7
+ import { DEFAULT_KEYWORDS } from "./schema-keywords.js";
42
8
 
43
9
  const COMBINATOR_KEYWORDS = ["oneOf", "anyOf", "allOf"];
44
10