@virmator/lint 14.28.1 → 14.29.1

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.
@@ -23,6 +23,7 @@ import preferProtectedOverPrivateRule from '../src/rules/prefer-protected-over-p
23
23
  import preferRemoveDuplicatesRule from '../src/rules/prefer-remove-duplicates.lint.js';
24
24
  import preferSingleQuotesRule from '../src/rules/prefer-single-quotes.lint.js';
25
25
  import preferToSortedRule from '../src/rules/prefer-to-sorted.lint.js';
26
+ import requireElseForTerminalBranchRule from '../src/rules/require-else-for-terminal-branch.lint.js';
26
27
  import requireImportExtensionsRule from '../src/rules/require-import-extensions.lint.js';
27
28
 
28
29
  export const globalVars = {
@@ -90,6 +91,7 @@ export function defineEslintConfig(repoDir: string) {
90
91
  'prefer-remove-duplicates': preferRemoveDuplicatesRule,
91
92
  'prefer-single-quotes': preferSingleQuotesRule,
92
93
  'prefer-to-sorted': preferToSortedRule,
94
+ 'require-else-for-terminal-branch': requireElseForTerminalBranchRule,
93
95
  'require-import-extensions': requireImportExtensionsRule,
94
96
  },
95
97
  },
@@ -211,6 +213,7 @@ export function defineEslintConfig(repoDir: string) {
211
213
  '@virmator/prefer-remove-duplicates': 'error',
212
214
  '@virmator/prefer-single-quotes': 'error',
213
215
  '@virmator/prefer-to-sorted': 'error',
216
+ '@virmator/require-else-for-terminal-branch': 'error',
214
217
  '@virmator/require-import-extensions': 'error',
215
218
  'no-lonely-if': 'error',
216
219
  curly: 'error',
@@ -81,7 +81,9 @@ function getRootIdentifier(node) {
81
81
  else if (node.type === 'ChainExpression') {
82
82
  return getRootIdentifier(node.expression);
83
83
  }
84
- return undefined;
84
+ else {
85
+ return undefined;
86
+ }
85
87
  }
86
88
  function isAssertionCall(node, assertionIdentifiers) {
87
89
  const root = getRootIdentifier(node.callee);
@@ -97,7 +99,9 @@ function childrenOf(node, visitorKeys) {
97
99
  else if (value != undefined && typeof value.type === 'string') {
98
100
  return [value];
99
101
  }
100
- return [];
102
+ else {
103
+ return [];
104
+ }
101
105
  });
102
106
  }
103
107
  /**
@@ -151,7 +155,9 @@ function isTestCall(node) {
151
155
  /** Catches `it.only(...)`, `it.skip(...)`, `test.only(...)`, etc. */
152
156
  return testFunctionNames.includes(callee.object.name);
153
157
  }
154
- return false;
158
+ else {
159
+ return false;
160
+ }
155
161
  }
156
162
  function getTestCallback(node) {
157
163
  return node.arguments.find((argument) => argument.type === 'FunctionExpression' || argument.type === 'ArrowFunctionExpression');
@@ -14,7 +14,9 @@ function getCalleeBaseName(callee) {
14
14
  else if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier') {
15
15
  return callee.object.name;
16
16
  }
17
- return undefined;
17
+ else {
18
+ return undefined;
19
+ }
18
20
  }
19
21
  /**
20
22
  * Reads a statically-known string from a node, supporting both string literals and template
@@ -29,7 +31,9 @@ function getStaticStringValue(node) {
29
31
  node.quasis[0]) {
30
32
  return node.quasis[0].value.cooked ?? undefined;
31
33
  }
32
- return undefined;
34
+ else {
35
+ return undefined;
36
+ }
33
37
  }
34
38
  function startsWithShould(value) {
35
39
  return value != undefined && /^should\b/i.test(value);
@@ -14,13 +14,13 @@ function isInlineCallbackArgument(node) {
14
14
  return parent.arguments.includes(node);
15
15
  }
16
16
  /**
17
- * The typescript-eslint parser emits `TSParameterProperty` nodes for constructor parameters that
18
- * use an accessibility (`public`/`private`/`protected`) or `readonly` modifier. These are absent
19
- * from the base estree `Pattern` union. Such parameters declare class fields rather than plain
20
- * positional arguments, so the rule ignores them when counting/comparing parameters.
17
+ * Class constructors are exempt: they can declare class fields through parameter properties and
18
+ * their signatures are constrained by `super()` calls in subclasses, so a params object is not
19
+ * always an available refactor.
21
20
  */
22
- function isParameterProperty(param) {
23
- return param.type === 'TSParameterProperty';
21
+ function isClassConstructor(node) {
22
+ const parent = node.parent;
23
+ return parent?.type === 'MethodDefinition' && parent.kind === 'constructor';
24
24
  }
25
25
  /**
26
26
  * Excludes a leading `this` parameter (which is a type-only annotation in TypeScript, not a real
@@ -115,36 +115,22 @@ const rule = {
115
115
  create(context) {
116
116
  const sourceCode = context.sourceCode;
117
117
  function check(node) {
118
- if (isInlineCallbackArgument(node)) {
118
+ if (isInlineCallbackArgument(node) || isClassConstructor(node)) {
119
119
  return;
120
120
  }
121
121
  const realParams = getRealParams(node.params);
122
- /**
123
- * Constructor parameter properties (those with an access modifier) declare class fields
124
- * rather than plain positional arguments, so they are excluded from the count and
125
- * duplicate-type comparison.
126
- */
127
- const consideredParams = realParams.filter((param) => !isParameterProperty(param));
128
- const messageId = consideredParams.length > 3
122
+ const messageId = realParams.length > 3
129
123
  ? 'tooManyPositionalParams'
130
- : hasDuplicateType(consideredParams, sourceCode)
124
+ : hasDuplicateType(realParams, sourceCode)
131
125
  ? 'duplicateParamType'
132
126
  : undefined;
133
127
  if (!messageId) {
134
128
  return;
135
129
  }
136
- /**
137
- * A params object can only wrap the plain parameters. When parameter properties are
138
- * interspersed there is no safe single-range replacement, so the fix is omitted and the
139
- * developer resolves it manually.
140
- */
141
- const fix = consideredParams.length === realParams.length
142
- ? buildParamsObjectFix(consideredParams, sourceCode)
143
- : undefined;
144
130
  context.report({
145
131
  node,
146
132
  messageId,
147
- fix: fix ?? null,
133
+ fix: buildParamsObjectFix(realParams, sourceCode) ?? null,
148
134
  });
149
135
  }
150
136
  return {
@@ -9,7 +9,9 @@ function templateRawToSingleQuoted(raw) {
9
9
  else if (match === "'") {
10
10
  return String.raw `\'`;
11
11
  }
12
- return match;
12
+ else {
13
+ return match;
14
+ }
13
15
  });
14
16
  return "'" + escaped + "'";
15
17
  }
@@ -0,0 +1,3 @@
1
+ import { type Rule } from 'eslint';
2
+ declare const rule: Rule.RuleModule;
3
+ export default rule;
@@ -0,0 +1,109 @@
1
+ const terminalStatementTypes = [
2
+ 'BreakStatement',
3
+ 'ContinueStatement',
4
+ 'ReturnStatement',
5
+ 'ThrowStatement',
6
+ ];
7
+ function isTerminalStatement(statement) {
8
+ return statement != undefined && terminalStatementTypes.includes(statement.type);
9
+ }
10
+ /** The statements that make up a branch, unwrapping a block body so its braces are ignored. */
11
+ function getBranchStatements(branch) {
12
+ return branch.type === 'BlockStatement' ? branch.body : [branch];
13
+ }
14
+ /** A branch is terminal when its final statement exits the enclosing block (return/throw/etc). */
15
+ function isTerminalBranch(branch) {
16
+ return isTerminalStatement(getBranchStatements(branch).at(-1));
17
+ }
18
+ /**
19
+ * Walks the `alternate` links of an if statement to collect every branch consequent and to
20
+ * determine whether the chain already ends with a plain `else`.
21
+ */
22
+ function collectChain(ifStatement) {
23
+ const alternate = ifStatement.alternate;
24
+ if (alternate == undefined) {
25
+ return {
26
+ branches: [ifStatement.consequent],
27
+ hasFinalElse: false,
28
+ };
29
+ }
30
+ else if (alternate.type === 'IfStatement') {
31
+ const rest = collectChain(alternate);
32
+ return {
33
+ branches: [
34
+ ifStatement.consequent,
35
+ ...rest.branches,
36
+ ],
37
+ hasFinalElse: rest.hasFinalElse,
38
+ };
39
+ }
40
+ else {
41
+ return {
42
+ branches: [ifStatement.consequent],
43
+ hasFinalElse: true,
44
+ };
45
+ }
46
+ }
47
+ function checkBlock(statements, context) {
48
+ statements.forEach((statement, index) => {
49
+ if (statement.type !== 'IfStatement') {
50
+ return;
51
+ }
52
+ const chain = collectChain(statement);
53
+ /**
54
+ * Only chains with at least one `else if`, no existing final `else`, and terminal branches
55
+ * throughout are candidates: in that shape everything after the chain is already reachable
56
+ * only when no branch matched, so it is effectively the missing `else`.
57
+ */
58
+ if (chain.hasFinalElse ||
59
+ chain.branches.length < 2 ||
60
+ !chain.branches.every((branch) => isTerminalBranch(branch))) {
61
+ return;
62
+ }
63
+ const dangling = statements.slice(index + 1);
64
+ const firstDangling = dangling[0];
65
+ const lastDangling = dangling.at(-1);
66
+ if (!firstDangling || !lastDangling || !isTerminalStatement(lastDangling)) {
67
+ return;
68
+ }
69
+ const maxBranchStatementCount = Math.max(...chain.branches.map((branch) => getBranchStatements(branch).length));
70
+ /**
71
+ * A dangling branch with at least twice as many statements as the longest chain branch
72
+ * stays an early-return style tail rather than being forced into an else.
73
+ */
74
+ if (dangling.length >= maxBranchStatementCount * 2) {
75
+ return;
76
+ }
77
+ context.report({
78
+ node: firstDangling,
79
+ messageId: 'requireElse',
80
+ fix(fixer) {
81
+ return [
82
+ fixer.insertTextAfter(statement, ' else {'),
83
+ fixer.insertTextAfter(lastDangling, '\n}'),
84
+ ];
85
+ },
86
+ });
87
+ });
88
+ }
89
+ const rule = {
90
+ meta: {
91
+ type: 'suggestion',
92
+ fixable: 'code',
93
+ messages: {
94
+ requireElse: 'A dangling terminal statement following an if-chain whose branches all terminate should be wrapped in an else block.',
95
+ },
96
+ schema: [],
97
+ },
98
+ create(context) {
99
+ return {
100
+ BlockStatement(node) {
101
+ checkBlock(node.body, context);
102
+ },
103
+ Program(node) {
104
+ checkBlock(node.body, context);
105
+ },
106
+ };
107
+ },
108
+ };
109
+ export default rule;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@virmator/lint",
3
- "version": "14.28.1",
3
+ "version": "14.29.1",
4
4
  "description": "Default ESLint linting plugin for virmator.",
5
5
  "keywords": [
6
6
  "virmator",
@@ -35,7 +35,7 @@
35
35
  "@augment-vir/assert": "^32.1.0",
36
36
  "@augment-vir/common": "^32.1.0",
37
37
  "@augment-vir/node": "^32.1.0",
38
- "@virmator/core": "^14.28.1",
38
+ "@virmator/core": "^14.29.1",
39
39
  "globals": "^17.7.0",
40
40
  "jiti": "^2.7.0",
41
41
  "mri": "^1.2.0"
@@ -47,17 +47,17 @@
47
47
  "@stylistic/eslint-plugin-ts": "^4.4.1",
48
48
  "@types/estree": "^1.0.9",
49
49
  "@types/node": "^26.1.1",
50
- "@typescript-eslint/eslint-plugin": "^8.63.0",
51
- "c8": "^11.0.0",
52
- "eslint": "^10.6.0",
50
+ "@typescript-eslint/eslint-plugin": "^8.64.0",
51
+ "c8": "^12.0.0",
52
+ "eslint": "^10.7.0",
53
53
  "eslint-config-prettier": "^10.1.8",
54
- "eslint-plugin-jsdoc": "^63.0.12",
54
+ "eslint-plugin-jsdoc": "^63.2.0",
55
55
  "eslint-plugin-playwright": "^2.10.5",
56
56
  "eslint-plugin-prettier": "^5.5.6",
57
- "eslint-plugin-sonarjs": "^4.1.0",
58
- "eslint-plugin-unicorn": "^71.1.0",
57
+ "eslint-plugin-sonarjs": "^4.2.0",
58
+ "eslint-plugin-unicorn": "^72.0.0",
59
59
  "istanbul-smart-text-reporter": "^1.1.5",
60
- "typescript-eslint": "^8.63.0"
60
+ "typescript-eslint": "^8.64.0"
61
61
  },
62
62
  "engines": {
63
63
  "node": ">=22"
@@ -121,9 +121,9 @@ function getRootIdentifier(node: Node): Identifier | undefined {
121
121
  return getRootIdentifier(node.callee);
122
122
  } else if (node.type === 'ChainExpression') {
123
123
  return getRootIdentifier(node.expression);
124
+ } else {
125
+ return undefined;
124
126
  }
125
-
126
- return undefined;
127
127
  }
128
128
 
129
129
  function isAssertionCall(node: CallExpression, assertionIdentifiers: ReadonlySet<string>): boolean {
@@ -148,9 +148,9 @@ function childrenOf(
148
148
  );
149
149
  } else if (value != undefined && typeof (value as Node).type === 'string') {
150
150
  return [value as Node];
151
+ } else {
152
+ return [];
151
153
  }
152
-
153
- return [];
154
154
  });
155
155
  }
156
156
 
@@ -229,9 +229,9 @@ function isTestCall(node: CallExpression): boolean {
229
229
  } else if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier') {
230
230
  /** Catches `it.only(...)`, `it.skip(...)`, `test.only(...)`, etc. */
231
231
  return testFunctionNames.includes(callee.object.name);
232
+ } else {
233
+ return false;
232
234
  }
233
-
234
- return false;
235
235
  }
236
236
 
237
237
  function getTestCallback(
@@ -16,9 +16,9 @@ function getCalleeBaseName(callee: CallExpression['callee']): string | undefined
16
16
  return callee.name;
17
17
  } else if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier') {
18
18
  return callee.object.name;
19
+ } else {
20
+ return undefined;
19
21
  }
20
-
21
- return undefined;
22
22
  }
23
23
 
24
24
  /**
@@ -34,8 +34,9 @@ function getStaticStringValue(node: Node | undefined): string | undefined {
34
34
  node.quasis[0]
35
35
  ) {
36
36
  return node.quasis[0].value.cooked ?? undefined;
37
+ } else {
38
+ return undefined;
37
39
  }
38
- return undefined;
39
40
  }
40
41
 
41
42
  function startsWithShould(value: string | undefined): boolean {
@@ -46,13 +46,14 @@ function isInlineCallbackArgument(node: AnyFunctionNode): boolean {
46
46
  }
47
47
 
48
48
  /**
49
- * The typescript-eslint parser emits `TSParameterProperty` nodes for constructor parameters that
50
- * use an accessibility (`public`/`private`/`protected`) or `readonly` modifier. These are absent
51
- * from the base estree `Pattern` union. Such parameters declare class fields rather than plain
52
- * positional arguments, so the rule ignores them when counting/comparing parameters.
49
+ * Class constructors are exempt: they can declare class fields through parameter properties and
50
+ * their signatures are constrained by `super()` calls in subclasses, so a params object is not
51
+ * always an available refactor.
53
52
  */
54
- function isParameterProperty(param: Pattern): boolean {
55
- return (param as {type: string}).type === 'TSParameterProperty';
53
+ function isClassConstructor(node: AnyFunctionNode): boolean {
54
+ const parent = (node as Rule.Node).parent;
55
+
56
+ return parent?.type === 'MethodDefinition' && parent.kind === 'constructor';
56
57
  }
57
58
 
58
59
  /**
@@ -186,22 +187,16 @@ const rule: Rule.RuleModule = {
186
187
  const sourceCode = context.sourceCode;
187
188
 
188
189
  function check(node: AnyFunctionNode) {
189
- if (isInlineCallbackArgument(node)) {
190
+ if (isInlineCallbackArgument(node) || isClassConstructor(node)) {
190
191
  return;
191
192
  }
192
193
 
193
194
  const realParams = getRealParams(node.params);
194
- /**
195
- * Constructor parameter properties (those with an access modifier) declare class fields
196
- * rather than plain positional arguments, so they are excluded from the count and
197
- * duplicate-type comparison.
198
- */
199
- const consideredParams = realParams.filter((param) => !isParameterProperty(param));
200
195
 
201
196
  const messageId =
202
- consideredParams.length > 3
197
+ realParams.length > 3
203
198
  ? 'tooManyPositionalParams'
204
- : hasDuplicateType(consideredParams, sourceCode)
199
+ : hasDuplicateType(realParams, sourceCode)
205
200
  ? 'duplicateParamType'
206
201
  : undefined;
207
202
 
@@ -209,20 +204,10 @@ const rule: Rule.RuleModule = {
209
204
  return;
210
205
  }
211
206
 
212
- /**
213
- * A params object can only wrap the plain parameters. When parameter properties are
214
- * interspersed there is no safe single-range replacement, so the fix is omitted and the
215
- * developer resolves it manually.
216
- */
217
- const fix =
218
- consideredParams.length === realParams.length
219
- ? buildParamsObjectFix(consideredParams, sourceCode)
220
- : undefined;
221
-
222
207
  context.report({
223
208
  node,
224
209
  messageId,
225
- fix: fix ?? null,
210
+ fix: buildParamsObjectFix(realParams, sourceCode) ?? null,
226
211
  });
227
212
  }
228
213
 
@@ -9,8 +9,9 @@ function templateRawToSingleQuoted(raw: string): string {
9
9
  return '${';
10
10
  } else if (match === "'") {
11
11
  return String.raw`\'`;
12
+ } else {
13
+ return match;
12
14
  }
13
- return match;
14
15
  });
15
16
  return "'" + escaped + "'";
16
17
  }
@@ -0,0 +1,137 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {Directive, IfStatement, ModuleDeclaration, Statement} from 'estree';
3
+
4
+ type AnyStatement = Directive | ModuleDeclaration | Statement;
5
+
6
+ const terminalStatementTypes: ReadonlyArray<string> = [
7
+ 'BreakStatement',
8
+ 'ContinueStatement',
9
+ 'ReturnStatement',
10
+ 'ThrowStatement',
11
+ ];
12
+
13
+ function isTerminalStatement(statement: AnyStatement | undefined): boolean {
14
+ return statement != undefined && terminalStatementTypes.includes(statement.type);
15
+ }
16
+
17
+ /** The statements that make up a branch, unwrapping a block body so its braces are ignored. */
18
+ function getBranchStatements(branch: Statement): ReadonlyArray<Statement> {
19
+ return branch.type === 'BlockStatement' ? branch.body : [branch];
20
+ }
21
+
22
+ /** A branch is terminal when its final statement exits the enclosing block (return/throw/etc). */
23
+ function isTerminalBranch(branch: Statement): boolean {
24
+ return isTerminalStatement(getBranchStatements(branch).at(-1));
25
+ }
26
+
27
+ type ChainInfo = {
28
+ branches: ReadonlyArray<Statement>;
29
+ hasFinalElse: boolean;
30
+ };
31
+
32
+ /**
33
+ * Walks the `alternate` links of an if statement to collect every branch consequent and to
34
+ * determine whether the chain already ends with a plain `else`.
35
+ */
36
+ function collectChain(ifStatement: IfStatement): ChainInfo {
37
+ const alternate = ifStatement.alternate;
38
+
39
+ if (alternate == undefined) {
40
+ return {
41
+ branches: [ifStatement.consequent],
42
+ hasFinalElse: false,
43
+ };
44
+ } else if (alternate.type === 'IfStatement') {
45
+ const rest = collectChain(alternate);
46
+ return {
47
+ branches: [
48
+ ifStatement.consequent,
49
+ ...rest.branches,
50
+ ],
51
+ hasFinalElse: rest.hasFinalElse,
52
+ };
53
+ } else {
54
+ return {
55
+ branches: [ifStatement.consequent],
56
+ hasFinalElse: true,
57
+ };
58
+ }
59
+ }
60
+
61
+ function checkBlock(statements: ReadonlyArray<AnyStatement>, context: Readonly<Rule.RuleContext>) {
62
+ statements.forEach((statement, index) => {
63
+ if (statement.type !== 'IfStatement') {
64
+ return;
65
+ }
66
+
67
+ const chain = collectChain(statement);
68
+
69
+ /**
70
+ * Only chains with at least one `else if`, no existing final `else`, and terminal branches
71
+ * throughout are candidates: in that shape everything after the chain is already reachable
72
+ * only when no branch matched, so it is effectively the missing `else`.
73
+ */
74
+ if (
75
+ chain.hasFinalElse ||
76
+ chain.branches.length < 2 ||
77
+ !chain.branches.every((branch) => isTerminalBranch(branch))
78
+ ) {
79
+ return;
80
+ }
81
+
82
+ const dangling = statements.slice(index + 1);
83
+ const firstDangling = dangling[0];
84
+ const lastDangling = dangling.at(-1);
85
+
86
+ if (!firstDangling || !lastDangling || !isTerminalStatement(lastDangling)) {
87
+ return;
88
+ }
89
+
90
+ const maxBranchStatementCount = Math.max(
91
+ ...chain.branches.map((branch) => getBranchStatements(branch).length),
92
+ );
93
+
94
+ /**
95
+ * A dangling branch with at least twice as many statements as the longest chain branch
96
+ * stays an early-return style tail rather than being forced into an else.
97
+ */
98
+ if (dangling.length >= maxBranchStatementCount * 2) {
99
+ return;
100
+ }
101
+
102
+ context.report({
103
+ node: firstDangling,
104
+ messageId: 'requireElse',
105
+ fix(fixer) {
106
+ return [
107
+ fixer.insertTextAfter(statement, ' else {'),
108
+ fixer.insertTextAfter(lastDangling, '\n}'),
109
+ ];
110
+ },
111
+ });
112
+ });
113
+ }
114
+
115
+ const rule: Rule.RuleModule = {
116
+ meta: {
117
+ type: 'suggestion',
118
+ fixable: 'code',
119
+ messages: {
120
+ requireElse:
121
+ 'A dangling terminal statement following an if-chain whose branches all terminate should be wrapped in an else block.',
122
+ },
123
+ schema: [],
124
+ },
125
+ create(context) {
126
+ return {
127
+ BlockStatement(node) {
128
+ checkBlock(node.body, context);
129
+ },
130
+ Program(node) {
131
+ checkBlock(node.body, context);
132
+ },
133
+ };
134
+ },
135
+ };
136
+
137
+ export default rule;