@virmator/lint 14.33.0 → 14.35.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.
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Matches a cspell word allow-list directive and captures everything after it. Only `word` and
3
+ * `words` directives are matched: other cspell directives (`ignore`, `disable`, `locale`, etc.) are
4
+ * position sensitive within a file and cannot be combined.
5
+ */
6
+ const wordsDirectiveRegExp = /\bcspell:words?\b[\t :]*(.*)/i;
7
+ function parseWordsComment(comment) {
8
+ const range = comment.range;
9
+ const directiveMatch = wordsDirectiveRegExp.exec(comment.value);
10
+ if (!range || !directiveMatch) {
11
+ return undefined;
12
+ }
13
+ const words = (directiveMatch[1] ?? '')
14
+ .trim()
15
+ .split(/[\s,]+/)
16
+ .filter((word) => word !== '');
17
+ return {
18
+ comment,
19
+ range,
20
+ words,
21
+ };
22
+ }
23
+ function createCombinedCommentText({ comment, words, }) {
24
+ const directiveText = `cspell:words ${words.join(' ')}`;
25
+ return comment.type === 'Line' ? `// ${directiveText}` : `/* ${directiveText} */`;
26
+ }
27
+ /**
28
+ * The range covering the whole line that the given comment sits on, including its trailing new
29
+ * line, or `undefined` when anything else shares the line and only the comment itself can be
30
+ * removed.
31
+ */
32
+ function getRemovalRange({ range, sourceCode, }) {
33
+ const lineStart = sourceCode.text.lastIndexOf('\n', range[0]) + 1;
34
+ const nextNewLine = sourceCode.text.indexOf('\n', range[1]);
35
+ const lineEnd = nextNewLine === -1 ? sourceCode.text.length : nextNewLine + 1;
36
+ const isAloneOnItsLine = sourceCode.text.slice(lineStart, range[0]).trim() === '' &&
37
+ sourceCode.text.slice(range[1], lineEnd).trim() === '';
38
+ return isAloneOnItsLine
39
+ ? [
40
+ lineStart,
41
+ lineEnd,
42
+ ]
43
+ : [
44
+ range[0],
45
+ range[1],
46
+ ];
47
+ }
48
+ const rule = {
49
+ meta: {
50
+ type: 'suggestion',
51
+ fixable: 'code',
52
+ docs: {
53
+ description: 'Require all cspell word allow-list comments in a file to be combined.',
54
+ },
55
+ messages: {
56
+ singleWordsComment: 'Combine all `cspell:words` comments in a file into a single comment.',
57
+ },
58
+ schema: [],
59
+ },
60
+ create(context) {
61
+ const sourceCode = context.sourceCode;
62
+ return {
63
+ Program() {
64
+ const wordsComments = sourceCode
65
+ .getAllComments()
66
+ .map((comment) => parseWordsComment(comment))
67
+ .filter((wordsComment) => wordsComment != undefined);
68
+ const [firstWordsComment, ...extraWordsComments] = wordsComments;
69
+ if (!firstWordsComment || !extraWordsComments.length) {
70
+ return;
71
+ }
72
+ const combinedWords = wordsComments.flatMap((wordsComment) => {
73
+ return wordsComment.words;
74
+ });
75
+ const uniqueWords = combinedWords.filter((word, wordIndex) => {
76
+ return combinedWords.indexOf(word) === wordIndex;
77
+ });
78
+ extraWordsComments.forEach((extraWordsComment, extraIndex) => {
79
+ context.report({
80
+ loc: extraWordsComment.comment.loc ?? {
81
+ start: sourceCode.getLocFromIndex(extraWordsComment.range[0]),
82
+ end: sourceCode.getLocFromIndex(extraWordsComment.range[1]),
83
+ },
84
+ messageId: 'singleWordsComment',
85
+ /**
86
+ * Only the first extra comment carries the fix: it rewrites the kept
87
+ * comment and removes every extra comment at once, so a single pass
88
+ * combines them all without overlapping fixes.
89
+ */
90
+ fix: extraIndex === 0
91
+ ? (fixer) => {
92
+ return [
93
+ fixer.replaceTextRange(firstWordsComment.range, createCombinedCommentText({
94
+ comment: firstWordsComment.comment,
95
+ words: uniqueWords,
96
+ })),
97
+ ...extraWordsComments.map((removedWordsComment) => {
98
+ return fixer.removeRange(getRemovalRange({
99
+ range: removedWordsComment.range,
100
+ sourceCode,
101
+ }));
102
+ }),
103
+ ];
104
+ }
105
+ : undefined,
106
+ });
107
+ });
108
+ },
109
+ };
110
+ },
111
+ };
112
+ export default rule;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@virmator/lint",
3
- "version": "14.33.0",
3
+ "version": "14.35.0",
4
4
  "description": "Default ESLint linting plugin for virmator.",
5
5
  "keywords": [
6
6
  "virmator",
@@ -32,32 +32,32 @@
32
32
  "test:update": "npm test update"
33
33
  },
34
34
  "dependencies": {
35
- "@augment-vir/assert": "^32.2.3",
36
- "@augment-vir/common": "^32.2.3",
37
- "@augment-vir/node": "^32.2.3",
38
- "@virmator/core": "^14.33.0",
35
+ "@augment-vir/assert": "^32.2.4",
36
+ "@augment-vir/common": "^32.2.4",
37
+ "@augment-vir/node": "^32.2.4",
38
+ "@virmator/core": "^14.35.0",
39
39
  "globals": "^17.11.0",
40
40
  "jiti": "^2.7.0",
41
41
  "mri": "^1.2.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@augment-vir/test": "^32.2.3",
44
+ "@augment-vir/test": "^32.2.4",
45
45
  "@eslint/js": "10.0.1",
46
46
  "@stylistic/eslint-plugin": "^5.10.0",
47
47
  "@stylistic/eslint-plugin-ts": "^4.4.1",
48
48
  "@types/estree": "^1.0.9",
49
- "@types/node": "^26.2.0",
50
- "@typescript-eslint/eslint-plugin": "^8.67.0",
49
+ "@types/node": "^26.4.0",
50
+ "@typescript-eslint/eslint-plugin": "^8.68.0",
51
51
  "c8": "^12.0.0",
52
- "eslint": "^10.9.0",
52
+ "eslint": "^10.9.1",
53
53
  "eslint-config-prettier": "^10.1.8",
54
- "eslint-plugin-jsdoc": "^64.2.1",
54
+ "eslint-plugin-jsdoc": "^64.3.2",
55
55
  "eslint-plugin-playwright": "^2.11.0",
56
56
  "eslint-plugin-prettier": "^5.5.6",
57
57
  "eslint-plugin-sonarjs": "^4.2.0",
58
- "eslint-plugin-unicorn": "^73.0.0",
58
+ "eslint-plugin-unicorn": "^74.0.0",
59
59
  "istanbul-smart-text-reporter": "^1.1.5",
60
- "typescript-eslint": "^8.67.0"
60
+ "typescript-eslint": "^8.68.0"
61
61
  },
62
62
  "engines": {
63
63
  "node": ">=22"
@@ -0,0 +1,119 @@
1
+ import {type Rule} from 'eslint';
2
+ import {basename} from 'node:path';
3
+
4
+ const numberedSuffixRegExp = /-\d+$/;
5
+
6
+ /**
7
+ * The suffix segments of a file name: everything between its first segment (the name itself) and
8
+ * its extension. A leading dot is part of the name rather than a segment separator, so
9
+ * `.eslintrc.ts` has no suffixes.
10
+ */
11
+ function extractSuffixes(filePath: string) {
12
+ const fileName = basename(filePath).replace(/^\.+/, '');
13
+
14
+ return fileName.split('.').slice(1, -1);
15
+ }
16
+
17
+ /**
18
+ * Every chain of suffixes that ends at the given index, longest first: `['config', 'base']` at
19
+ * index `1` produces `'config.base'` then `'base'`. A dotted entry in the `suffixes` option
20
+ * therefore allows its last suffix only directly after the ones before it, so listing `config.base`
21
+ * allows `thing.config.base.ts` while still rejecting `thing.base.ts`.
22
+ */
23
+ function listSuffixChains({
24
+ suffixes,
25
+ suffixIndex,
26
+ }: Readonly<{
27
+ suffixes: ReadonlyArray<string>;
28
+ suffixIndex: number;
29
+ }>) {
30
+ return suffixes.slice(0, suffixIndex + 1).map((currentSuffix, startIndex) => {
31
+ return suffixes.slice(startIndex, suffixIndex + 1).join('.');
32
+ });
33
+ }
34
+
35
+ const rule: Rule.RuleModule = {
36
+ meta: {
37
+ type: 'suggestion',
38
+ docs: {
39
+ description: 'Require file name suffixes to come from a known list.',
40
+ },
41
+ messages: {
42
+ unknownSuffix:
43
+ "Unknown file name suffix `.{{suffix}}`. Known suffixes: {{knownSuffixes}}. Add this suffix to the rule's `suffixes` option if it is intentional.",
44
+ },
45
+ schema: [
46
+ {
47
+ type: 'object',
48
+ required: [
49
+ 'suffixes',
50
+ ],
51
+ properties: {
52
+ suffixes: {
53
+ type: 'array',
54
+ items: {
55
+ type: 'string',
56
+ },
57
+ },
58
+ /**
59
+ * Allows a `-<number>` counter on a suffix, for splitting a single slow test
60
+ * file into numbered companions (`my-thing.element-2.test.ts`).
61
+ */
62
+ allowNumberedSuffixes: {
63
+ type: 'boolean',
64
+ },
65
+ },
66
+ additionalProperties: false,
67
+ },
68
+ ],
69
+ },
70
+ create(context) {
71
+ const options = context.options[0] ?? {};
72
+ const knownSuffixes: string[] = options.suffixes ?? [];
73
+
74
+ return {
75
+ Program() {
76
+ const suffixes = extractSuffixes(context.filename).map((suffix) => {
77
+ return options.allowNumberedSuffixes
78
+ ? suffix.replace(numberedSuffixRegExp, '')
79
+ : suffix;
80
+ });
81
+
82
+ suffixes.forEach((suffix, suffixIndex) => {
83
+ const isKnown = listSuffixChains({
84
+ suffixes,
85
+ suffixIndex,
86
+ }).some((suffixChain) => {
87
+ return knownSuffixes.includes(suffixChain);
88
+ });
89
+
90
+ if (isKnown) {
91
+ return;
92
+ }
93
+
94
+ context.report({
95
+ /**
96
+ * The file name is the problem, so the report is anchored to its first
97
+ * line.
98
+ */
99
+ loc: {
100
+ line: 1,
101
+ column: 0,
102
+ },
103
+ messageId: 'unknownSuffix',
104
+ data: {
105
+ suffix,
106
+ knownSuffixes: knownSuffixes
107
+ .map((knownSuffix) => {
108
+ return `.${knownSuffix}`;
109
+ })
110
+ .join(', '),
111
+ },
112
+ });
113
+ });
114
+ },
115
+ };
116
+ },
117
+ };
118
+
119
+ export default rule;
@@ -0,0 +1,209 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {Comment} from 'estree';
3
+
4
+ const categoryTagRegExp = /@category\b/;
5
+ /**
6
+ * A whole JSDoc comment holding nothing but the tag, and a comment line holding nothing but the
7
+ * tag. The tag value is limited to a single word so that a line with a second tag or a description
8
+ * on it is never matched (and so never deleted).
9
+ */
10
+ const tagOnlyCommentRegExp = /^\/\*\*[\t ]*@category(?:[\t ]+[\w-]+)?[\t ]*\*\/$/;
11
+ const tagOnlyLineRegExp = /^[\t ]*(?:\*[\t ]*)?@category(?:[\t ]+[\w-]+)?[\t ]*$/;
12
+
13
+ function findCategoryTagLines({
14
+ commentText,
15
+ commentStart,
16
+ }: Readonly<{
17
+ commentText: string;
18
+ commentStart: number;
19
+ }>) {
20
+ return commentText.split('\n').reduce<
21
+ {
22
+ lineStart: number;
23
+ lineEnd: number;
24
+ tagStart: number;
25
+ }[]
26
+ >((tagLines, lineText, lineIndex, allLines) => {
27
+ const lineStart =
28
+ commentStart +
29
+ allLines.slice(0, lineIndex).reduce((total, previousLine) => {
30
+ return total + previousLine.length + 1;
31
+ }, 0);
32
+ const tagIndex = lineText.search(categoryTagRegExp);
33
+
34
+ if (tagIndex === -1) {
35
+ return tagLines;
36
+ }
37
+
38
+ return [
39
+ ...tagLines,
40
+ {
41
+ lineStart,
42
+ lineEnd: lineStart + lineText.length,
43
+ tagStart: lineStart + tagIndex,
44
+ },
45
+ ];
46
+ }, []);
47
+ }
48
+
49
+ /**
50
+ * Whether the given comment is the only thing on its line, meaning the whole line can be removed
51
+ * along with the comment.
52
+ */
53
+ function isAloneOnItsLine({
54
+ comment,
55
+ sourceCode,
56
+ }: Readonly<{
57
+ comment: Comment;
58
+ sourceCode: Rule.RuleContext['sourceCode'];
59
+ }>) {
60
+ const range = comment.range;
61
+
62
+ if (!range) {
63
+ return false;
64
+ }
65
+
66
+ const lineStart = sourceCode.text.lastIndexOf('\n', range[0]) + 1;
67
+ const nextNewLine = sourceCode.text.indexOf('\n', range[1]);
68
+ const lineEnd = nextNewLine === -1 ? sourceCode.text.length : nextNewLine;
69
+
70
+ return (
71
+ sourceCode.text.slice(lineStart, range[0]).trim() === '' &&
72
+ sourceCode.text.slice(range[1], lineEnd).trim() === ''
73
+ );
74
+ }
75
+
76
+ function getWholeLineRange({
77
+ comment,
78
+ sourceCode,
79
+ }: Readonly<{
80
+ comment: Comment;
81
+ sourceCode: Rule.RuleContext['sourceCode'];
82
+ }>):
83
+ | [
84
+ number,
85
+ number,
86
+ ]
87
+ | undefined {
88
+ const range = comment.range;
89
+
90
+ if (!range) {
91
+ return undefined;
92
+ }
93
+
94
+ const lineStart = sourceCode.text.lastIndexOf('\n', range[0]) + 1;
95
+ const nextNewLine = sourceCode.text.indexOf('\n', range[1]);
96
+
97
+ return [
98
+ lineStart,
99
+ nextNewLine === -1 ? sourceCode.text.length : nextNewLine + 1,
100
+ ];
101
+ }
102
+
103
+ /**
104
+ * Only a comment or line holding nothing but the tag can be deleted outright. Anything else (a
105
+ * description sharing the line, a tag value spanning lines) is reported without a fix so the author
106
+ * decides what the remaining comment should say.
107
+ */
108
+ function createFix({
109
+ comment,
110
+ commentText,
111
+ sourceCode,
112
+ tagLine,
113
+ }: Readonly<{
114
+ comment: Comment;
115
+ commentText: string;
116
+ sourceCode: Rule.RuleContext['sourceCode'];
117
+ tagLine: Readonly<{lineStart: number; lineEnd: number}>;
118
+ }>): Rule.ReportFixer | undefined {
119
+ const range = comment.range;
120
+
121
+ if (range == undefined) {
122
+ return undefined;
123
+ } else if (commentText.includes('\n')) {
124
+ const tagLineText = sourceCode.text.slice(tagLine.lineStart, tagLine.lineEnd);
125
+
126
+ if (!tagOnlyLineRegExp.test(tagLineText)) {
127
+ return undefined;
128
+ }
129
+
130
+ return (fixer) => {
131
+ return fixer.removeRange([
132
+ tagLine.lineStart,
133
+ tagLine.lineEnd + 1,
134
+ ]);
135
+ };
136
+ } else if (tagOnlyCommentRegExp.test(commentText.trim())) {
137
+ const wholeLineRange = getWholeLineRange({
138
+ comment,
139
+ sourceCode,
140
+ });
141
+
142
+ return (fixer) => {
143
+ return wholeLineRange &&
144
+ isAloneOnItsLine({
145
+ comment,
146
+ sourceCode,
147
+ })
148
+ ? fixer.removeRange(wholeLineRange)
149
+ : fixer.removeRange(range);
150
+ };
151
+ } else {
152
+ return undefined;
153
+ }
154
+ }
155
+
156
+ const rule: Rule.RuleModule = {
157
+ meta: {
158
+ type: 'suggestion',
159
+ fixable: 'code',
160
+ docs: {
161
+ description: 'Disallow `@category` tags in JSDoc comments.',
162
+ },
163
+ messages: {
164
+ noCategory: 'Do not use `@category` JSDoc tags.',
165
+ },
166
+ schema: [],
167
+ },
168
+ create(context) {
169
+ const sourceCode = context.sourceCode;
170
+
171
+ return {
172
+ Program() {
173
+ sourceCode.getAllComments().forEach((comment) => {
174
+ const range = comment.range;
175
+
176
+ if (comment.type !== 'Block' || !range || !comment.value.startsWith('*')) {
177
+ return;
178
+ }
179
+
180
+ const commentText = sourceCode.text.slice(range[0], range[1]);
181
+ const tagLines = findCategoryTagLines({
182
+ commentText,
183
+ commentStart: range[0],
184
+ });
185
+
186
+ tagLines.forEach((tagLine) => {
187
+ const fix = createFix({
188
+ comment,
189
+ commentText,
190
+ sourceCode,
191
+ tagLine,
192
+ });
193
+
194
+ context.report({
195
+ loc: {
196
+ start: sourceCode.getLocFromIndex(tagLine.tagStart),
197
+ end: sourceCode.getLocFromIndex(tagLine.lineEnd),
198
+ },
199
+ messageId: 'noCategory',
200
+ fix,
201
+ });
202
+ });
203
+ });
204
+ },
205
+ };
206
+ },
207
+ };
208
+
209
+ export default rule;