eslint-config-webpack 4.11.0 → 4.13.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
@@ -40,8 +40,8 @@ export default defineConfig([
40
40
 
41
41
  ### Webpack-specific configs
42
42
 
43
- Two opt-in configs cover conventions only webpack's own repositories need. They
44
- are not part of `recommended` — extend them explicitly:
43
+ Three opt-in configs cover conventions only webpack's own repositories need.
44
+ They are not part of `recommended` — extend them explicitly:
45
45
 
46
46
  ```js
47
47
  import { defineConfig } from "eslint/config";
@@ -50,7 +50,12 @@ import configs from "eslint-config-webpack/configs.js";
50
50
 
51
51
  export default defineConfig([
52
52
  {
53
- extends: [config, configs["webpack/special"], configs["webpack/schemas"]],
53
+ extends: [
54
+ config,
55
+ configs["webpack/special"],
56
+ configs["webpack/schemas"],
57
+ configs["webpack/types"],
58
+ ],
54
59
  },
55
60
  ]);
56
61
  ```
@@ -59,6 +64,7 @@ export default defineConfig([
59
64
  | ----------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
60
65
  | `webpack/special` | source files | `webpack/require-license-comment` — every file opens with the MIT license header. |
61
66
  | `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). |
67
+ | `webpack/types` | `**/lib/**/*.{js,mjs,cjs}` | `webpack/inherit-jsdoc` — an overriding method carries the JSDoc of the method it overrides (autofixable). |
62
68
 
63
69
  `webpack/valid-schema` accepts options for which keywords a schema may use.
64
70
  `keywords` replaces the default set — webpack's own — outright, `allow` adds to
@@ -85,6 +91,30 @@ value, uses `instanceof` without `tsType`, `absolutePath` off a string or
85
91
  `additionalProperties`, nests or mis-sizes `oneOf`/`anyOf`/`allOf`, or leaves a
86
92
  property without a description starting in uppercase and ending in a single dot.
87
93
 
94
+ `webpack/inherit-jsdoc` needs type information, so `webpack/types` sets up
95
+ `@typescript-eslint/parser` with `projectService` — the project therefore needs
96
+ a `tsconfig.json` covering the linted files, and `typescript` installed. The
97
+ rule copies the base class method's JSDoc onto every override that is missing
98
+ it or has drifted from it, dropping `@abstract`. `stripTags` chooses which tags
99
+ are dropped:
100
+
101
+ ```js
102
+ export default defineConfig([
103
+ {
104
+ extends: [configs["webpack/types"]],
105
+ rules: {
106
+ "webpack/inherit-jsdoc": ["error", { stripTags: ["abstract", "virtual"] }],
107
+ },
108
+ },
109
+ ]);
110
+ ```
111
+
112
+ Getters, setters, static methods and methods overriding a declaration file (so
113
+ `Object.toString` or `Set.add`) are left alone. Inheritance is resolved through
114
+ the whole chain, so restoring a JSDoc that several classes deep an override
115
+ inherits takes more than one `--fix` run — repeat it until the tree stops
116
+ changing.
117
+
88
118
  [npm]: https://img.shields.io/npm/v/eslint-config-webpack.svg
89
119
  [npm-url]: https://npmjs.com/package/eslint-config-webpack
90
120
  [test]: https://github.com/webpack/eslint-config-webpack/actions/workflows/test.yml/badge.svg
@@ -6,7 +6,11 @@ const recommendedWebpackSpecialConfig = configs.recommended;
6
6
  /** @type {import("eslint").Linter.Config} */
7
7
  const webpackSchemasConfig = configs.schemas;
8
8
 
9
+ /** @type {import("eslint").Linter.Config} */
10
+ const webpackTypesConfig = configs.types;
11
+
9
12
  export default {
10
13
  "webpack/special": recommendedWebpackSpecialConfig,
11
14
  "webpack/schemas": webpackSchemasConfig,
15
+ "webpack/types": webpackTypesConfig,
12
16
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-config-webpack",
3
- "version": "4.11.0",
3
+ "version": "4.13.0",
4
4
  "description": "Provides Webpack's eslint rules as an extensible shared config",
5
5
  "keywords": [
6
6
  "eslint",
@@ -3,6 +3,10 @@ import { createRequire } from "node:module";
3
3
  import * as parserJsonc from "jsonc-eslint-parser";
4
4
  import { allExtensions } from "../../configs/utils/extensions.js";
5
5
  import { rule as formatSchema } from "./rules/format-schema.js";
6
+ import { rule as inheritJsdoc } from "./rules/inherit-jsdoc.js";
7
+ import { rule as noDuplicateImportTag } from "./rules/no-duplicate-import-tag.js";
8
+ import { rule as noUnusedImportTag } from "./rules/no-unused-import-tag.js";
9
+ import { rule as preferImportTag } from "./rules/prefer-import-tag.js";
6
10
  import { rule as requireLicenseComment } from "./rules/require-license-comment.js";
7
11
  import { rule as validSchema } from "./rules/valid-schema.js";
8
12
 
@@ -12,6 +16,10 @@ const { version } = require("../../package.json");
12
16
 
13
17
  const rules = {
14
18
  "format-schema": formatSchema,
19
+ "inherit-jsdoc": inheritJsdoc,
20
+ "no-duplicate-import-tag": noDuplicateImportTag,
21
+ "no-unused-import-tag": noUnusedImportTag,
22
+ "prefer-import-tag": preferImportTag,
15
23
  "require-license-comment": requireLicenseComment,
16
24
  "valid-schema": validSchema,
17
25
  };
@@ -25,7 +33,7 @@ const recommendedRules = {
25
33
  ),
26
34
  };
27
35
 
28
- /** @type {Record<"recommended" | "schemas", import("eslint").Linter.Config>} */
36
+ /** @type {Record<"recommended" | "schemas" | "types", import("eslint").Linter.Config>} */
29
37
  const configs = {
30
38
  recommended: {
31
39
  name: "webpack/recommended",
@@ -55,6 +63,29 @@ const configs = {
55
63
  "webpack/valid-schema": "error",
56
64
  },
57
65
  },
66
+ types: {
67
+ name: "webpack/types",
68
+ files: ["**/lib/**/*.{js,mjs,cjs}"],
69
+ languageOptions: {
70
+ // `typescript` is an optional peer dependency, so the parser that needs
71
+ // it is only resolved when this config is actually used.
72
+ get parser() {
73
+ return require("typescript-eslint").parser;
74
+ },
75
+ parserOptions: {
76
+ projectService: true,
77
+ },
78
+ },
79
+ plugins: {
80
+ get webpack() {
81
+ // eslint-disable-next-line no-use-before-define
82
+ return plugin;
83
+ },
84
+ },
85
+ rules: {
86
+ "webpack/inherit-jsdoc": "error",
87
+ },
88
+ },
58
89
  };
59
90
 
60
91
  const plugin = {
@@ -0,0 +1,203 @@
1
+ /** @typedef {import("eslint").Rule.RuleFixer} RuleFixer */
2
+ /** @typedef {import("eslint").Rule.Fix} Fix */
3
+ /** @typedef {import("estree").MethodDefinition} MethodDefinition */
4
+
5
+ // The TypeScript AST is reached through the parser services, which type them as
6
+ // `unknown` outside a TypeScript-aware parser.
7
+ // eslint-disable-next-line jsdoc/reject-any-type
8
+ /** @typedef {any} TSNode */
9
+
10
+ /**
11
+ * Reads the first JSDoc block attached to a TypeScript node.
12
+ * @param {TSNode} node the TypeScript node
13
+ * @returns {TSNode | undefined} the JSDoc node when the node carries one
14
+ */
15
+ function getJSDoc(node) {
16
+ const { jsDoc } = node;
17
+
18
+ return jsDoc && jsDoc.length > 0 ? jsDoc[0] : undefined;
19
+ }
20
+
21
+ /**
22
+ * Drops the lines carrying one of the stripped tags and re-indents the block.
23
+ * @param {string} text the JSDoc text of the base class method
24
+ * @param {string} indent the indentation of the overriding method
25
+ * @param {string[]} stripTags tag names to drop, without the leading `@`
26
+ * @returns {string} the JSDoc text as it must appear on the overriding method
27
+ */
28
+ function rewriteJSDoc(text, indent, stripTags) {
29
+ const stripped = new Set(
30
+ stripTags.map((tag) => new RegExp(`^\\s*\\*\\s*@${tag}\\b`)),
31
+ );
32
+ const lines = text.replaceAll(/\r\n?/g, "\n").split("\n");
33
+
34
+ return lines
35
+ .filter(
36
+ (line, index) =>
37
+ index === 0 || ![...stripped].some((regexp) => regexp.test(line)),
38
+ )
39
+ .map((line, index) =>
40
+ index === 0 ? line : `${indent} ${line.trimStart()}`,
41
+ )
42
+ .join("\n");
43
+ }
44
+
45
+ /**
46
+ * Finds the method of the same name on a base class of the given class.
47
+ * @param {TSNode} typeChecker the TypeScript type checker
48
+ * @param {TSNode} classNode the TypeScript class declaration or expression
49
+ * @param {string} memberName the name of the overriding method
50
+ * @param {number} memberKind the syntax kind a base declaration must share
51
+ * @returns {TSNode | undefined} the base class method declaration when found
52
+ */
53
+ function findInBaseClass(typeChecker, classNode, memberName, memberKind) {
54
+ const classSymbol = classNode.name
55
+ ? typeChecker.getSymbolAtLocation(classNode.name)
56
+ : classNode.symbol;
57
+
58
+ if (!classSymbol) {
59
+ return undefined;
60
+ }
61
+
62
+ const baseTypes =
63
+ typeChecker.getDeclaredTypeOfSymbol(classSymbol).getBaseTypes() || [];
64
+
65
+ for (const baseType of baseTypes) {
66
+ // `getProperty` walks the whole base chain, so an override three classes
67
+ // down from the documented method still resolves.
68
+ const property = baseType.getProperty(memberName);
69
+ const declaration =
70
+ property && property.declarations && property.declarations[0];
71
+
72
+ // A method declared in a `.d.ts` is `Object.toString` or `Set.add`, whose
73
+ // JSDoc documents the standard library rather than this class hierarchy.
74
+ if (
75
+ declaration &&
76
+ declaration.kind === memberKind &&
77
+ !declaration.getSourceFile().isDeclarationFile &&
78
+ getJSDoc(declaration)
79
+ ) {
80
+ return declaration;
81
+ }
82
+ }
83
+
84
+ return undefined;
85
+ }
86
+
87
+ /**
88
+ * @type {import("eslint").Rule.RuleModule} rule rule
89
+ */
90
+ export const rule = {
91
+ create(context) {
92
+ const { sourceCode } = context;
93
+ const services = sourceCode.parserServices;
94
+
95
+ if (!services || !services.program || !services.esTreeNodeToTSNodeMap) {
96
+ return {};
97
+ }
98
+
99
+ const { stripTags = ["abstract"] } = context.options[0] || {};
100
+ const typeChecker = services.program.getTypeChecker();
101
+
102
+ return {
103
+ MethodDefinition(node) {
104
+ // Getters and setters are left alone: their JSDoc documents the
105
+ // value, which an override is free to describe differently.
106
+ if (node.static || node.computed || node.kind !== "method") {
107
+ return;
108
+ }
109
+
110
+ const member = services.esTreeNodeToTSNodeMap.get(node);
111
+
112
+ if (!member || !member.parent) {
113
+ return;
114
+ }
115
+
116
+ const memberName = member.name.getText();
117
+ const baseMember = findInBaseClass(
118
+ typeChecker,
119
+ member.parent,
120
+ memberName,
121
+ member.kind,
122
+ );
123
+
124
+ if (!baseMember) {
125
+ return;
126
+ }
127
+
128
+ const start = member.getStart();
129
+ const [indent] = /** @type {RegExpMatchArray} */ (
130
+ sourceCode.lines[sourceCode.getLocFromIndex(start).line - 1].match(
131
+ /^\s*/,
132
+ )
133
+ );
134
+ const expected = rewriteJSDoc(
135
+ getJSDoc(baseMember).getText(),
136
+ indent,
137
+ stripTags,
138
+ );
139
+ const currentJSDoc = getJSDoc(member);
140
+
141
+ if (!currentJSDoc) {
142
+ context.report({
143
+ /** @type {(fixer: RuleFixer) => Fix} */
144
+ fix: (fixer) =>
145
+ fixer.insertTextBeforeRange(
146
+ [start, start],
147
+ `${expected}\n${indent}`,
148
+ ),
149
+ messageId: "missing",
150
+ node: /** @type {MethodDefinition} */ (node).key,
151
+ });
152
+
153
+ return;
154
+ }
155
+
156
+ const current = currentJSDoc.getText().replaceAll(/\r\n?/g, "\n");
157
+
158
+ if (current === expected) {
159
+ return;
160
+ }
161
+
162
+ context.report({
163
+ /** @type {(fixer: RuleFixer) => Fix} */
164
+ fix: (fixer) =>
165
+ fixer.replaceTextRange(
166
+ [currentJSDoc.getStart(), currentJSDoc.getEnd()],
167
+ expected,
168
+ ),
169
+ messageId: "outdated",
170
+ node: /** @type {MethodDefinition} */ (node).key,
171
+ });
172
+ },
173
+ };
174
+ },
175
+ meta: {
176
+ docs: {
177
+ category: "Best Practices",
178
+ description:
179
+ "Require a method to carry the JSDoc of the method it overrides",
180
+ recommended: false,
181
+ },
182
+ fixable: "code",
183
+ messages: {
184
+ missing:
185
+ "Expected the JSDoc of the base class method, this method overrides it.",
186
+ outdated:
187
+ "Expected this JSDoc to match the base class method it overrides.",
188
+ },
189
+ schema: [
190
+ {
191
+ additionalProperties: false,
192
+ properties: {
193
+ stripTags: {
194
+ items: { type: "string" },
195
+ type: "array",
196
+ },
197
+ },
198
+ type: "object",
199
+ },
200
+ ],
201
+ type: "suggestion",
202
+ },
203
+ };
@@ -0,0 +1,83 @@
1
+ import { collectImportTags } from "../utils/import-tags.js";
2
+
3
+ /** @typedef {import("../utils/import-tags.js").ImportTag} ImportTag */
4
+
5
+ /**
6
+ * Whether two tags could be written as one import statement. A namespace binding
7
+ * cannot sit next to named bindings, and one statement carries at most one head.
8
+ * @param {ImportTag} first the earlier tag
9
+ * @param {ImportTag} second the later tag
10
+ * @returns {boolean} true when they can be folded together
11
+ */
12
+ const isMergeable = (first, second) => {
13
+ const heads = /** @type {ImportTag[]} */ (
14
+ [first, second].filter((tag) => tag.head !== undefined)
15
+ );
16
+
17
+ if (
18
+ heads.length === 2 &&
19
+ /** @type {NonNullable<ImportTag["head"]>} */ (heads[0].head).local !==
20
+ /** @type {NonNullable<ImportTag["head"]>} */ (heads[1].head).local
21
+ ) {
22
+ return false;
23
+ }
24
+
25
+ return (
26
+ !heads.some((tag) => tag.namespace) ||
27
+ first.named.length + second.named.length === 0
28
+ );
29
+ };
30
+
31
+ /**
32
+ * @type {import("eslint").Rule.RuleModule} rule rule
33
+ */
34
+ export const rule = {
35
+ create(context) {
36
+ const { sourceCode } = context;
37
+
38
+ return {
39
+ "Program:exit"() {
40
+ /** @type {Map<string, ImportTag>} */
41
+ const seen = new Map();
42
+
43
+ for (const tag of collectImportTags(sourceCode)) {
44
+ const first = seen.get(tag.moduleRequest);
45
+
46
+ if (first === undefined) {
47
+ seen.set(tag.moduleRequest, tag);
48
+ continue;
49
+ }
50
+
51
+ if (!isMergeable(first, tag)) {
52
+ continue;
53
+ }
54
+
55
+ context.report({
56
+ loc: {
57
+ start: sourceCode.getLocFromIndex(tag.start),
58
+ end: sourceCode.getLocFromIndex(tag.end),
59
+ },
60
+ messageId: "duplicateImportTag",
61
+ data: {
62
+ module: tag.moduleRequest,
63
+ line: String(sourceCode.getLocFromIndex(first.start).line),
64
+ },
65
+ });
66
+ }
67
+ },
68
+ };
69
+ },
70
+ meta: {
71
+ docs: {
72
+ category: "Stylistic Issues",
73
+ description: "Require one `@import` per module in a file",
74
+ recommended: true,
75
+ },
76
+ messages: {
77
+ duplicateImportTag:
78
+ '"{{module}}" is already imported on line {{line}}; fold this `@import` into that one.',
79
+ },
80
+ schema: [],
81
+ type: "suggestion",
82
+ },
83
+ };
@@ -0,0 +1,192 @@
1
+ import { collectImportTags } from "../utils/import-tags.js";
2
+
3
+ /** @typedef {import("eslint").Rule.ReportFixer} ReportFixer */
4
+ /** @typedef {import("eslint").SourceCode} SourceCode */
5
+ /** @typedef {import("../utils/import-tags.js").ImportBinding} ImportBinding */
6
+ /** @typedef {import("../utils/import-tags.js").ImportTag} ImportTag */
7
+
8
+ /**
9
+ * The source with every `@import` tag blanked out, so one import can never keep
10
+ * another alive. Blanks keep the length, so offsets still address the original.
11
+ * @param {string} text the whole source
12
+ * @param {ImportTag[]} tags every `@import` tag in it
13
+ * @returns {string} the haystack a binding's uses are looked for in
14
+ */
15
+ const buildHaystack = (text, tags) => {
16
+ let haystack = text;
17
+
18
+ for (const tag of tags) {
19
+ haystack =
20
+ haystack.slice(0, tag.start) +
21
+ " ".repeat(tag.end - tag.start) +
22
+ haystack.slice(tag.end);
23
+ }
24
+
25
+ return haystack;
26
+ };
27
+
28
+ /**
29
+ * @param {string} text the whole source
30
+ * @param {number} index an offset inside the line
31
+ * @returns {[number, number]} the line's range, the line break included
32
+ */
33
+ const lineRangeAt = (text, index) => {
34
+ const start = text.lastIndexOf("\n", index - 1) + 1;
35
+ const lineBreak = text.indexOf("\n", index);
36
+
37
+ return [start, lineBreak === -1 ? text.length : lineBreak + 1];
38
+ };
39
+
40
+ /**
41
+ * Whether the tag is the only tag of a comment that owns its line — the one shape
42
+ * that can be removed outright.
43
+ * @param {string} text the whole source
44
+ * @param {ImportTag} tag the tag to test
45
+ * @returns {[number, number] | null} the range to remove, or null when unsure
46
+ */
47
+ const removableCommentRange = (text, tag) => {
48
+ const commentRange = /** @type {[number, number]} */ (tag.comment.range);
49
+
50
+ if (text.slice(commentRange[0], tag.start).replaceAll(/[/*\s]/g, "") !== "") {
51
+ return null;
52
+ }
53
+
54
+ if (/@\w/.test(text.slice(tag.end, commentRange[1]))) {
55
+ return null;
56
+ }
57
+
58
+ const [start, end] = lineRangeAt(text, commentRange[0]);
59
+ const outside =
60
+ text.slice(start, commentRange[0]) +
61
+ text.slice(commentRange[1], end).replace(/\r?\n$/, "");
62
+
63
+ return outside.trim() === "" ? [start, end] : null;
64
+ };
65
+
66
+ /**
67
+ * @param {SourceCode} sourceCode source being linted
68
+ * @param {ImportTag} tag the tag the binding belongs to
69
+ * @param {ImportBinding} binding the unused binding
70
+ * @param {number} bindingCount how many bindings the tag declares
71
+ * @returns {ReportFixer | null} a fixer, or null when the edit is not obvious
72
+ */
73
+ const buildFixer = (sourceCode, tag, binding, bindingCount) => {
74
+ const text = sourceCode.getText();
75
+
76
+ if (bindingCount === 1) {
77
+ const range = removableCommentRange(text, tag);
78
+
79
+ return range === null ? null : (fixer) => fixer.removeRange(range);
80
+ }
81
+
82
+ // Only a named binding can be taken out on its own; dropping the head would
83
+ // leave a dangling comma the shapes below do not cover
84
+ if (binding === tag.head) {
85
+ return null;
86
+ }
87
+
88
+ if (text.slice(tag.start, tag.end).includes("\n")) {
89
+ // The wrapped form puts one binding per line, so the line goes with it
90
+ const range = lineRangeAt(text, binding.start);
91
+ const rest =
92
+ text.slice(range[0], binding.start) + text.slice(binding.end, range[1]);
93
+
94
+ if (!/^[\s*,]*$/.test(rest)) {
95
+ return null;
96
+ }
97
+
98
+ // Taking the last binding away would strand the comma the one before it ends
99
+ // with, which `trailingComma: "none"` does not allow
100
+ const [previous] = tag.named
101
+ .filter((other) => other.end <= binding.start)
102
+ .toSorted((one, another) => another.end - one.end);
103
+ const strandedComma =
104
+ previous !== undefined &&
105
+ !tag.named.some((other) => other.start >= binding.end)
106
+ ? text.indexOf(",", previous.end)
107
+ : -1;
108
+
109
+ return strandedComma === -1 || strandedComma >= binding.start
110
+ ? (fixer) => fixer.removeRange(range)
111
+ : (fixer) => [
112
+ fixer.removeRange([strandedComma, strandedComma + 1]),
113
+ fixer.removeRange(range),
114
+ ];
115
+ }
116
+
117
+ // `{ A, B }` on one line: the binding leaves with the comma that separates it
118
+ const after = /^[ \t]*,[ \t]*/.exec(text.slice(binding.end));
119
+
120
+ if (after !== null) {
121
+ return (fixer) =>
122
+ fixer.removeRange([binding.start, binding.end + after[0].length]);
123
+ }
124
+
125
+ const before = /[ \t]*,[ \t]*$/.exec(text.slice(tag.start, binding.start));
126
+
127
+ return before === null
128
+ ? null
129
+ : (fixer) =>
130
+ fixer.removeRange([binding.start - before[0].length, binding.end]);
131
+ };
132
+
133
+ /**
134
+ * @type {import("eslint").Rule.RuleModule} rule rule
135
+ */
136
+ export const rule = {
137
+ create(context) {
138
+ const { sourceCode } = context;
139
+
140
+ return {
141
+ "Program:exit"() {
142
+ const tags = collectImportTags(sourceCode);
143
+
144
+ if (tags.length === 0) {
145
+ return;
146
+ }
147
+
148
+ const haystack = buildHaystack(sourceCode.getText(), tags);
149
+
150
+ for (const tag of tags) {
151
+ const bindings = [
152
+ ...(tag.head === undefined ? [] : [tag.head]),
153
+ ...tag.named,
154
+ ];
155
+
156
+ for (const binding of bindings) {
157
+ const used = new RegExp(
158
+ `(?<![\\w$])${binding.local.replaceAll("$", "\\$")}(?![\\w$])`,
159
+ ).test(haystack);
160
+
161
+ if (used) {
162
+ continue;
163
+ }
164
+
165
+ context.report({
166
+ loc: {
167
+ start: sourceCode.getLocFromIndex(binding.start),
168
+ end: sourceCode.getLocFromIndex(binding.end),
169
+ },
170
+ messageId: "unusedImportTag",
171
+ data: { name: binding.local },
172
+ fix: buildFixer(sourceCode, tag, binding, bindings.length),
173
+ });
174
+ }
175
+ }
176
+ },
177
+ };
178
+ },
179
+ meta: {
180
+ docs: {
181
+ category: "Stylistic Issues",
182
+ description: "Require every `@import` binding to be referenced",
183
+ recommended: true,
184
+ },
185
+ fixable: "code",
186
+ messages: {
187
+ unusedImportTag: "`{{name}}` is imported but never referenced.",
188
+ },
189
+ schema: [],
190
+ type: "suggestion",
191
+ },
192
+ };
@@ -0,0 +1,88 @@
1
+ import { stripLineMarkers } from "../utils/import-tags.js";
2
+
3
+ // A `@typedef` that is nothing but an import — `{import("m")}` or `{import("m").Name}`
4
+ // — and carries no description. Anything richer (a generic instantiation, an indexed
5
+ // access, an intersection) cannot be written as `@import`, so it is left alone.
6
+ const PLAIN_IMPORT_TYPEDEF =
7
+ /@typedef[ \t]*\{[ \t]*import\((["'])([^"']+)\1\)(?:\.([A-Za-z_$][\w$]*))?[ \t]*\}[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?=\r?\n|$)/g;
8
+
9
+ /**
10
+ * @param {string} moduleRequest module the type comes from
11
+ * @param {string | undefined} exportName named export, or undefined for the whole module
12
+ * @param {string} alias local name the type is bound to
13
+ * @returns {string} the equivalent `@import` comment
14
+ */
15
+ const buildImportComment = (moduleRequest, exportName, alias) => {
16
+ const binding =
17
+ exportName === undefined
18
+ ? alias
19
+ : `{ ${exportName === alias ? alias : `${exportName} as ${alias}`} }`;
20
+
21
+ return `/** @import ${binding} from ${JSON.stringify(moduleRequest)} */`;
22
+ };
23
+
24
+ /**
25
+ * @type {import("eslint").Rule.RuleModule} rule rule
26
+ */
27
+ export const rule = {
28
+ create(context) {
29
+ const { sourceCode } = context;
30
+
31
+ return {
32
+ "Program:exit"() {
33
+ for (const comment of sourceCode.getAllComments()) {
34
+ if (comment.type !== "Block" || !comment.value.startsWith("*")) {
35
+ continue;
36
+ }
37
+
38
+ const commentRange = /** @type {[number, number]} */ (comment.range);
39
+ const body = stripLineMarkers(comment.value);
40
+
41
+ PLAIN_IMPORT_TYPEDEF.lastIndex = 0;
42
+
43
+ let match;
44
+
45
+ while ((match = PLAIN_IMPORT_TYPEDEF.exec(body)) !== null) {
46
+ const [text, , moduleRequest, exportName, alias] = match;
47
+ const start = commentRange[0] + 2 + match.index;
48
+ // Only a comment holding this tag and nothing else can be swapped
49
+ // in place; lifting one tag out of a block is left to the author
50
+ const isWholeComment =
51
+ !comment.value.includes("\n") && body.trim() === text.trim();
52
+
53
+ context.report({
54
+ loc: {
55
+ start: sourceCode.getLocFromIndex(start),
56
+ end: sourceCode.getLocFromIndex(start + text.length),
57
+ },
58
+ messageId: "preferImportTag",
59
+ data: { alias },
60
+ fix: isWholeComment
61
+ ? (fixer) =>
62
+ fixer.replaceTextRange(
63
+ commentRange,
64
+ buildImportComment(moduleRequest, exportName, alias),
65
+ )
66
+ : null,
67
+ });
68
+ }
69
+ }
70
+ },
71
+ };
72
+ },
73
+ meta: {
74
+ docs: {
75
+ category: "Stylistic Issues",
76
+ description:
77
+ "Require `@import` rather than a `@typedef` that only aliases an `import()`",
78
+ recommended: true,
79
+ },
80
+ fixable: "code",
81
+ messages: {
82
+ preferImportTag:
83
+ "`{{alias}}` aliases an `import()`; declare it with `@import` instead of `@typedef`.",
84
+ },
85
+ schema: [],
86
+ type: "suggestion",
87
+ },
88
+ };
@@ -12,7 +12,7 @@ export const rule = {
12
12
  "Program:exit"(program) {
13
13
  const comments = sourceCode.getAllComments();
14
14
  const licenseComment =
15
- /** @type {(Comment & { start: number, end: number }) | undefined} */
15
+ /** @type {(Comment & { range: [number, number] }) | undefined} */
16
16
  (
17
17
  comments.find(
18
18
  (comment) =>
@@ -32,7 +32,8 @@ export const rule = {
32
32
  return;
33
33
  }
34
34
 
35
- const afterComment = sourceCode.text[licenseComment.end];
35
+ const [, end] = licenseComment.range;
36
+ const afterComment = sourceCode.text[end];
36
37
 
37
38
  if (afterComment !== "\n") {
38
39
  context.report({
@@ -43,7 +44,7 @@ export const rule = {
43
44
  return;
44
45
  }
45
46
 
46
- const afterAfterComment = sourceCode.text[licenseComment.end + 1];
47
+ const afterAfterComment = sourceCode.text[end + 1];
47
48
 
48
49
  if (afterAfterComment !== "\n") {
49
50
  context.report({
@@ -159,6 +159,31 @@ export const rule = {
159
159
  });
160
160
  }
161
161
 
162
+ const minLength = getKeyword(node, "minLength");
163
+
164
+ if (
165
+ minLength &&
166
+ !(minLength.value.type === "JSONLiteral" && minLength.value.value === 1)
167
+ ) {
168
+ context.report({
169
+ loc: minLength.key.loc,
170
+ messageId: "minLengthMustBeOne",
171
+ });
172
+ }
173
+
174
+ const enumKeyword = getKeyword(node, "enum");
175
+
176
+ if (enumKeyword && enumKeyword.value.type === "JSONArrayExpression") {
177
+ for (const element of enumKeyword.value.elements) {
178
+ if (element && element.type !== "JSONLiteral") {
179
+ context.report({
180
+ loc: element.loc,
181
+ messageId: "enumRequiresPrimitive",
182
+ });
183
+ }
184
+ }
185
+ }
186
+
162
187
  const absolutePath = getKeyword(node, "absolutePath");
163
188
 
164
189
  if (absolutePath && !isStringLiteral(type && type.value, "string")) {
@@ -292,8 +317,12 @@ export const rule = {
292
317
  'When using "absolutePath", "type" must be "string".',
293
318
  combinatorMultipleItems: '"{{keyword}}" must have more than one item.',
294
319
  emptyCombinator: '"{{keyword}}" must not be empty.',
320
+ enumRequiresPrimitive:
321
+ '"enum" must only hold primitive values, the precompiled validator cannot compare anything else.',
295
322
  instanceofRequiresTsType:
296
323
  'When using "instanceof", "tsType" is required.',
324
+ minLengthMustBeOne:
325
+ '"minLength" must be 1, the precompiled validator emits no other length check.',
297
326
  invalidDescription:
298
327
  "Description should start with an uppercase letter and end with a single dot.",
299
328
  missingAdditionalProperties:
@@ -0,0 +1,135 @@
1
+ /** @typedef {import("eslint").SourceCode} SourceCode */
2
+ /** @typedef {import("estree").Comment} Comment */
3
+
4
+ /**
5
+ * @typedef {object} ImportBinding
6
+ * @property {string} text binding as written, e.g. `Foo` or `Foo as Bar`
7
+ * @property {string} local name the binding introduces in the file
8
+ * @property {number} start absolute offset of the binding in the source
9
+ * @property {number} end absolute offset just past the binding
10
+ */
11
+
12
+ /**
13
+ * @typedef {object} ImportTag
14
+ * @property {Comment} comment JSDoc comment the tag is written in
15
+ * @property {string} moduleRequest module the types are imported from
16
+ * @property {ImportBinding | undefined} head default or `* as ns` binding, when present
17
+ * @property {boolean} namespace whether `head` is a `* as ns` binding
18
+ * @property {ImportBinding[]} named bindings inside the braces
19
+ * @property {number} start absolute offset of `@import`
20
+ * @property {number} end absolute offset just past the module string
21
+ */
22
+
23
+ const IMPORT_TAG = /@import[ \t]+([\s\S]*?)[ \t]+from[ \t]+(["'])([^"']+)\2/g;
24
+ const NAMESPACE_BINDING = /\*[ \t\n]*as[ \t\n]+([A-Za-z_$][\w$]*)/;
25
+ const DEFAULT_BINDING = /[A-Za-z_$][\w$]*/;
26
+
27
+ /**
28
+ * Blanks out the `*` opening each JSDoc line, keeping every offset intact so
29
+ * matches on the result still address the original source.
30
+ * @param {string} text raw comment body
31
+ * @returns {string} the body with its line markers replaced by spaces
32
+ */
33
+ export const stripLineMarkers = (text) =>
34
+ text.replaceAll(/^[ \t]*\*/gm, (marker) => " ".repeat(marker.length));
35
+
36
+ /**
37
+ * @param {string} binding binding as written, `Name` or `Name as Alias`
38
+ * @returns {string} the local name it introduces
39
+ */
40
+ export const localNameOf = (binding) => {
41
+ const parts = binding.split(/[ \t\n]+as[ \t\n]+/);
42
+ return parts[parts.length - 1].trim();
43
+ };
44
+
45
+ /**
46
+ * @param {string} inner text between the braces of a named-import clause
47
+ * @param {number} innerStart absolute offset of that text
48
+ * @returns {ImportBinding[]} one entry per binding
49
+ */
50
+ const parseNamedBindings = (inner, innerStart) => {
51
+ /** @type {ImportBinding[]} */
52
+ const bindings = [];
53
+ let offset = 0;
54
+
55
+ for (const part of inner.split(",")) {
56
+ const text = part.trim();
57
+
58
+ if (text !== "") {
59
+ const start = innerStart + offset + part.indexOf(text);
60
+
61
+ bindings.push({
62
+ text,
63
+ local: localNameOf(text),
64
+ start,
65
+ end: start + text.length,
66
+ });
67
+ }
68
+
69
+ offset += part.length + 1;
70
+ }
71
+
72
+ return bindings;
73
+ };
74
+
75
+ /**
76
+ * Reads every `@import` tag of one JSDoc comment.
77
+ * @param {Comment} comment the comment to read
78
+ * @returns {ImportTag[]} the tags it holds, in source order
79
+ */
80
+ export const parseImportTags = (comment) => {
81
+ if (comment.type !== "Block" || !comment.value.startsWith("*")) {
82
+ return [];
83
+ }
84
+
85
+ const commentRange = /** @type {[number, number]} */ (comment.range);
86
+ // `/*` sits before the value, so an index into it is its start plus 2 in the source
87
+ const base = commentRange[0] + 2;
88
+ const body = stripLineMarkers(comment.value);
89
+ /** @type {ImportTag[]} */
90
+ const tags = [];
91
+
92
+ IMPORT_TAG.lastIndex = 0;
93
+
94
+ let match;
95
+
96
+ while ((match = IMPORT_TAG.exec(body)) !== null) {
97
+ const [text, clause, , moduleRequest] = match;
98
+ const clauseStart = base + match.index + text.indexOf(clause);
99
+ const braced = /\{([^}]*)\}/.exec(clause);
100
+ const named =
101
+ braced === null
102
+ ? []
103
+ : parseNamedBindings(braced[1], clauseStart + braced.index + 1);
104
+ const outer = braced === null ? clause : clause.slice(0, braced.index);
105
+ const namespaced = NAMESPACE_BINDING.exec(outer);
106
+ const head = namespaced === null ? DEFAULT_BINDING.exec(outer) : namespaced;
107
+
108
+ tags.push({
109
+ comment,
110
+ moduleRequest,
111
+ head:
112
+ head === null
113
+ ? undefined
114
+ : {
115
+ text: head[0],
116
+ local: namespaced === null ? head[0] : head[1],
117
+ start: clauseStart + head.index,
118
+ end: clauseStart + head.index + head[0].length,
119
+ },
120
+ namespace: namespaced !== null,
121
+ named,
122
+ start: base + match.index,
123
+ end: base + match.index + text.length,
124
+ });
125
+ }
126
+
127
+ return tags;
128
+ };
129
+
130
+ /**
131
+ * @param {SourceCode} sourceCode source being linted
132
+ * @returns {ImportTag[]} every `@import` tag in the file, in source order
133
+ */
134
+ export const collectImportTags = (sourceCode) =>
135
+ sourceCode.getAllComments().flatMap((comment) => parseImportTags(comment));