eslint 9.34.0 → 9.36.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,539 @@
1
+ /**
2
+ * @fileoverview Rule to preserve caught errors when re-throwing exceptions
3
+ * @author Amnish Singh Arora
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Requirements
9
+ //------------------------------------------------------------------------------
10
+
11
+ const astUtils = require("./utils/ast-utils");
12
+
13
+ //------------------------------------------------------------------------------
14
+ // Types
15
+ //------------------------------------------------------------------------------
16
+
17
+ /** @typedef {import("estree").Node} ASTNode */
18
+
19
+ //------------------------------------------------------------------------------
20
+ // Helpers
21
+ //------------------------------------------------------------------------------
22
+
23
+ /*
24
+ * This is an indicator of an error cause node, that is too complicated to be detected and fixed.
25
+ * Eg, when error options is an `Identifier` or a `SpreadElement`.
26
+ */
27
+ const UNKNOWN_CAUSE = Symbol("unknown_cause");
28
+
29
+ const BUILT_IN_ERROR_TYPES = new Set([
30
+ "Error",
31
+ "EvalError",
32
+ "RangeError",
33
+ "ReferenceError",
34
+ "SyntaxError",
35
+ "TypeError",
36
+ "URIError",
37
+ "AggregateError",
38
+ ]);
39
+
40
+ /**
41
+ * Finds and returns information about the `cause` property of an error being thrown.
42
+ * @param {ASTNode} throwStatement `ThrowStatement` to be checked.
43
+ * @returns {{ value: ASTNode; multipleDefinitions: boolean; } | UNKNOWN_CAUSE | null}
44
+ * Information about the `cause` of the error being thrown, such as the value node and
45
+ * whether there are multiple definitions of `cause`. `null` if there is no `cause`.
46
+ */
47
+ function getErrorCause(throwStatement) {
48
+ const throwExpression = throwStatement.argument;
49
+ /*
50
+ * Determine which argument index holds the options object
51
+ * `AggregateError` is a special case as it accepts the `options` object as third argument.
52
+ */
53
+ const optionsIndex =
54
+ throwExpression.callee.name === "AggregateError" ? 2 : 1;
55
+
56
+ /*
57
+ * Make sure there is no `SpreadElement` at or before the `optionsIndex`
58
+ * as this messes up the effective order of arguments and makes it complicated
59
+ * to track where the actual error options need to be at
60
+ */
61
+ const spreadExpressionIndex = throwExpression.arguments.findIndex(
62
+ arg => arg.type === "SpreadElement",
63
+ );
64
+ if (spreadExpressionIndex >= 0 && spreadExpressionIndex <= optionsIndex) {
65
+ return UNKNOWN_CAUSE;
66
+ }
67
+
68
+ const errorOptions = throwExpression.arguments[optionsIndex];
69
+
70
+ if (errorOptions) {
71
+ if (errorOptions.type === "ObjectExpression") {
72
+ if (
73
+ errorOptions.properties.some(
74
+ prop => prop.type === "SpreadElement",
75
+ )
76
+ ) {
77
+ /*
78
+ * If there is a spread element as part of error options, it is too complicated
79
+ * to verify if the cause is used properly and auto-fix.
80
+ */
81
+ return UNKNOWN_CAUSE;
82
+ }
83
+
84
+ const causeProperties = errorOptions.properties.filter(
85
+ prop =>
86
+ prop.type === "Property" &&
87
+ prop.key.type === "Identifier" &&
88
+ prop.key.name === "cause" &&
89
+ !prop.computed, // It is hard to accurately identify the value of computed props
90
+ );
91
+
92
+ const causeProperty = causeProperties.at(-1);
93
+ return causeProperty
94
+ ? {
95
+ value: causeProperty.value,
96
+ multipleDefinitions: causeProperties.length > 1,
97
+ }
98
+ : null;
99
+ }
100
+
101
+ // Error options exist, but too complicated to be analyzed/fixed
102
+ return UNKNOWN_CAUSE;
103
+ }
104
+
105
+ return null;
106
+ }
107
+
108
+ /**
109
+ * Finds and returns the `CatchClause` node, that the `node` is part of.
110
+ * @param {ASTNode} node The AST node to be evaluated.
111
+ * @returns {ASTNode | null } The closest parent `CatchClause` node, `null` if the `node` is not in a catch block.
112
+ */
113
+ function findParentCatch(node) {
114
+ let currentNode = node;
115
+
116
+ while (currentNode && currentNode.type !== "CatchClause") {
117
+ if (
118
+ [
119
+ "FunctionDeclaration",
120
+ "FunctionExpression",
121
+ "ArrowFunctionExpression",
122
+ "StaticBlock",
123
+ ].includes(currentNode.type)
124
+ ) {
125
+ /*
126
+ * Make sure the ThrowStatement is not made inside a function definition or a static block inside a high level catch.
127
+ * In such cases, the caught error is not directly related to the Throw.
128
+ *
129
+ * For example,
130
+ * try {
131
+ * } catch (error) {
132
+ * foo = {
133
+ * bar() {
134
+ * throw new Error();
135
+ * }
136
+ * };
137
+ * }
138
+ */
139
+ return null;
140
+ }
141
+ currentNode = currentNode.parent;
142
+ }
143
+
144
+ return currentNode;
145
+ }
146
+
147
+ //------------------------------------------------------------------------------
148
+ // Rule Definition
149
+ //------------------------------------------------------------------------------
150
+
151
+ /** @type {import('../types').Rule.RuleModule} */
152
+ module.exports = {
153
+ meta: {
154
+ type: "suggestion",
155
+
156
+ defaultOptions: [
157
+ {
158
+ requireCatchParameter: false,
159
+ },
160
+ ],
161
+
162
+ docs: {
163
+ description:
164
+ "Disallow losing originally caught error when re-throwing custom errors",
165
+ recommended: false,
166
+ url: "https://eslint.org/docs/latest/rules/preserve-caught-error", // URL to the documentation page for this rule
167
+ },
168
+ /*
169
+ * TODO: We should allow passing `customErrorTypes` option once something like `typescript-eslint`'s
170
+ * `TypeOrValueSpecifier` is implemented in core Eslint.
171
+ * See:
172
+ * 1. https://typescript-eslint.io/packages/type-utils/type-or-value-specifier/
173
+ * 2. https://github.com/eslint/eslint/pull/19913#discussion_r2192608593
174
+ * 3. https://github.com/eslint/eslint/discussions/16540
175
+ */
176
+ schema: [
177
+ {
178
+ type: "object",
179
+ properties: {
180
+ requireCatchParameter: {
181
+ type: "boolean",
182
+ description:
183
+ "Requires the catch blocks to always have the caught error parameter so it is not discarded.",
184
+ },
185
+ },
186
+ additionalProperties: false,
187
+ },
188
+ ],
189
+ messages: {
190
+ missingCause:
191
+ "There is no `cause` attached to the symptom error being thrown.",
192
+ incorrectCause:
193
+ "The symptom error is being thrown with an incorrect `cause`.",
194
+ includeCause:
195
+ "Include the original caught error as the `cause` of the symptom error.",
196
+ missingCatchErrorParam:
197
+ "The caught error is not accessible because the catch clause lacks the error parameter. Start referencing the caught error using the catch parameter.",
198
+ partiallyLostError:
199
+ "Re-throws cannot preserve the caught error as a part of it is being lost due to destructuring.",
200
+ caughtErrorShadowed:
201
+ "The caught error is being attached as `cause`, but is shadowed by a closer scoped redeclaration.",
202
+ },
203
+ hasSuggestions: true,
204
+ },
205
+
206
+ create(context) {
207
+ const sourceCode = context.sourceCode;
208
+ const [{ requireCatchParameter }] = context.options;
209
+
210
+ //----------------------------------------------------------------------
211
+ // Helpers
212
+ //----------------------------------------------------------------------
213
+
214
+ /**
215
+ * Checks if a `ThrowStatement` is constructing and throwing a new `Error` object.
216
+ *
217
+ * Covers all the error types on `globalThis` that support `cause` property:
218
+ * https://github.com/microsoft/TypeScript/blob/main/src/lib/es2022.error.d.ts
219
+ * @param {ASTNode} throwStatement The `ThrowStatement` that needs to be checked.
220
+ * @returns {boolean} `true` if a new "Error" is being thrown, else `false`.
221
+ */
222
+ function isThrowingNewError(throwStatement) {
223
+ return (
224
+ (throwStatement.argument.type === "NewExpression" ||
225
+ throwStatement.argument.type === "CallExpression") &&
226
+ throwStatement.argument.callee.type === "Identifier" &&
227
+ BUILT_IN_ERROR_TYPES.has(throwStatement.argument.callee.name) &&
228
+ /*
229
+ * Make sure the thrown Error is instance is one of the built-in global error types.
230
+ * Custom imports could shadow this, which would lead to false positives.
231
+ * e.g. import { Error } from "./my-custom-error.js";
232
+ * throw Error("Failed to perform error prone operations");
233
+ */
234
+ sourceCode.isGlobalReference(throwStatement.argument.callee)
235
+ );
236
+ }
237
+
238
+ /**
239
+ * Inserts `cause: <caughtErrorName>` into an inline options object expression.
240
+ * @param {RuleFixer} fixer The fixer object.
241
+ * @param {ASTNode} optionsNode The options object node.
242
+ * @param {string} caughtErrorName The name of the caught error (e.g., "err").
243
+ * @returns {Fix} The fix object.
244
+ */
245
+ function insertCauseIntoOptions(fixer, optionsNode, caughtErrorName) {
246
+ const properties = optionsNode.properties;
247
+
248
+ if (properties.length === 0) {
249
+ // Insert inside empty braces: `{}` → `{ cause: err }`
250
+ return fixer.insertTextAfter(
251
+ sourceCode.getFirstToken(optionsNode),
252
+ `cause: ${caughtErrorName}`,
253
+ );
254
+ }
255
+
256
+ const lastProp = properties.at(-1);
257
+ return fixer.insertTextAfter(
258
+ lastProp,
259
+ `, cause: ${caughtErrorName}`,
260
+ );
261
+ }
262
+
263
+ //----------------------------------------------------------------------
264
+ // Public
265
+ //----------------------------------------------------------------------
266
+ return {
267
+ ThrowStatement(node) {
268
+ // Check if the throw is inside a catch block
269
+ const parentCatch = findParentCatch(node);
270
+ const throwStatement = node;
271
+
272
+ // Check if a new error is being thrown in a catch block
273
+ if (parentCatch && isThrowingNewError(throwStatement)) {
274
+ if (
275
+ parentCatch.param &&
276
+ parentCatch.param.type !== "Identifier"
277
+ ) {
278
+ /*
279
+ * When a part of the caught error is being lost at the parameter level, commonly due to destructuring.
280
+ * e.g. catch({ message, ...rest })
281
+ */
282
+ context.report({
283
+ messageId: "partiallyLostError",
284
+ node: parentCatch,
285
+ });
286
+ return;
287
+ }
288
+
289
+ const caughtError =
290
+ parentCatch.param?.type === "Identifier"
291
+ ? parentCatch.param
292
+ : null;
293
+
294
+ // Check if there are throw statements and caught error is being ignored
295
+ if (!caughtError) {
296
+ if (requireCatchParameter) {
297
+ context.report({
298
+ node: throwStatement,
299
+ messageId: "missingCatchErrorParam",
300
+ });
301
+ return;
302
+ }
303
+ return;
304
+ }
305
+
306
+ // Check if there is a cause attached to the new error
307
+ const errorCauseInfo = getErrorCause(throwStatement);
308
+
309
+ if (errorCauseInfo === UNKNOWN_CAUSE) {
310
+ // Error options exist, but too complicated to be analyzed/fixed
311
+ return;
312
+ }
313
+
314
+ if (errorCauseInfo === null) {
315
+ // If there is no `cause` attached to the error being thrown.
316
+ context.report({
317
+ messageId: "missingCause",
318
+ node: throwStatement,
319
+ suggest: [
320
+ {
321
+ messageId: "includeCause",
322
+ fix(fixer) {
323
+ const throwExpression =
324
+ throwStatement.argument;
325
+ const args = throwExpression.arguments;
326
+ const errorType =
327
+ throwExpression.callee.name;
328
+
329
+ // AggregateError: errors, message, options
330
+ if (errorType === "AggregateError") {
331
+ const errorsArg = args[0];
332
+ const messageArg = args[1];
333
+ const optionsArg = args[2];
334
+
335
+ if (!errorsArg) {
336
+ // Case: `throw new AggregateError()` → insert all arguments
337
+ const lastToken =
338
+ sourceCode.getLastToken(
339
+ throwExpression,
340
+ );
341
+ const lastCalleeToken =
342
+ sourceCode.getLastToken(
343
+ throwExpression.callee,
344
+ );
345
+ const parenToken =
346
+ sourceCode.getFirstTokenBetween(
347
+ lastCalleeToken,
348
+ lastToken,
349
+ astUtils.isOpeningParenToken,
350
+ );
351
+
352
+ if (parenToken) {
353
+ return fixer.insertTextAfter(
354
+ parenToken,
355
+ `[], "", { cause: ${caughtError.name} }`,
356
+ );
357
+ }
358
+ return fixer.insertTextAfter(
359
+ throwExpression.callee,
360
+ `([], "", { cause: ${caughtError.name} })`,
361
+ );
362
+ }
363
+
364
+ if (!messageArg) {
365
+ // Case: `throw new AggregateError([])` → insert message and options
366
+ return fixer.insertTextAfter(
367
+ errorsArg,
368
+ `, "", { cause: ${caughtError.name} }`,
369
+ );
370
+ }
371
+
372
+ if (!optionsArg) {
373
+ // Case: `throw new AggregateError([], "")` → insert error options only
374
+ return fixer.insertTextAfter(
375
+ messageArg,
376
+ `, { cause: ${caughtError.name} }`,
377
+ );
378
+ }
379
+
380
+ if (
381
+ optionsArg.type ===
382
+ "ObjectExpression"
383
+ ) {
384
+ return insertCauseIntoOptions(
385
+ fixer,
386
+ optionsArg,
387
+ caughtError.name,
388
+ );
389
+ }
390
+
391
+ // Complex dynamic options — skip
392
+ return null;
393
+ }
394
+
395
+ // Normal Error types
396
+ const messageArg = args[0];
397
+ const optionsArg = args[1];
398
+
399
+ if (!messageArg) {
400
+ // Case: `throw new Error()` → insert both message and options
401
+ const lastToken =
402
+ sourceCode.getLastToken(
403
+ throwExpression,
404
+ );
405
+ const lastCalleeToken =
406
+ sourceCode.getLastToken(
407
+ throwExpression.callee,
408
+ );
409
+ const parenToken =
410
+ sourceCode.getFirstTokenBetween(
411
+ lastCalleeToken,
412
+ lastToken,
413
+ astUtils.isOpeningParenToken,
414
+ );
415
+
416
+ if (parenToken) {
417
+ return fixer.insertTextAfter(
418
+ parenToken,
419
+ `"", { cause: ${caughtError.name} }`,
420
+ );
421
+ }
422
+ return fixer.insertTextAfter(
423
+ throwExpression.callee,
424
+ `("", { cause: ${caughtError.name} })`,
425
+ );
426
+ }
427
+ if (!optionsArg) {
428
+ // Case: `throw new Error("Some message")` → insert only options
429
+ return fixer.insertTextAfter(
430
+ messageArg,
431
+ `, { cause: ${caughtError.name} }`,
432
+ );
433
+ }
434
+
435
+ if (
436
+ optionsArg.type ===
437
+ "ObjectExpression"
438
+ ) {
439
+ return insertCauseIntoOptions(
440
+ fixer,
441
+ optionsArg,
442
+ caughtError.name,
443
+ );
444
+ }
445
+
446
+ return null; // Identifier or spread — do not fix
447
+ },
448
+ },
449
+ ],
450
+ });
451
+
452
+ // We don't need to check further
453
+ return;
454
+ }
455
+
456
+ const { value: thrownErrorCause } = errorCauseInfo;
457
+
458
+ // If there is an attached cause, verify that it matches the caught error
459
+ if (
460
+ !(
461
+ thrownErrorCause.type === "Identifier" &&
462
+ thrownErrorCause.name === caughtError.name
463
+ )
464
+ ) {
465
+ const suggest = errorCauseInfo.multipleDefinitions
466
+ ? null // If there are multiple `cause` definitions, a suggestion could be confusing.
467
+ : [
468
+ {
469
+ messageId: "includeCause",
470
+ fix(fixer) {
471
+ /*
472
+ * In case `cause` is attached using object property shorthand or as a method or accessor.
473
+ * e.g. throw Error("fail", { cause });
474
+ * throw Error("fail", { cause() { doSomething(); } });
475
+ * throw Error("fail", { get cause() { return error; } });
476
+ */
477
+ if (
478
+ thrownErrorCause.parent
479
+ .method ||
480
+ thrownErrorCause.parent
481
+ .shorthand ||
482
+ thrownErrorCause.parent.kind !==
483
+ "init"
484
+ ) {
485
+ return fixer.replaceText(
486
+ thrownErrorCause.parent,
487
+ `cause: ${caughtError.name}`,
488
+ );
489
+ }
490
+
491
+ return fixer.replaceText(
492
+ thrownErrorCause,
493
+ caughtError.name,
494
+ );
495
+ },
496
+ },
497
+ ];
498
+ context.report({
499
+ messageId: "incorrectCause",
500
+ node: thrownErrorCause,
501
+ suggest,
502
+ });
503
+ return;
504
+ }
505
+
506
+ /*
507
+ * If the attached cause matches the identifier name of the caught error,
508
+ * make sure it is not being shadowed by a closer scoped redeclaration.
509
+ *
510
+ * e.g. try {
511
+ * doSomething();
512
+ * } catch (error) {
513
+ * if (whatever) {
514
+ * const error = anotherError;
515
+ * throw new Error("Something went wrong");
516
+ * }
517
+ * }
518
+ */
519
+ let scope = sourceCode.getScope(throwStatement);
520
+ do {
521
+ const variable = scope.set.get(caughtError.name);
522
+ if (variable) {
523
+ break;
524
+ }
525
+ scope = scope.upper;
526
+ } while (scope);
527
+
528
+ if (scope?.block !== parentCatch) {
529
+ // Caught error is being shadowed
530
+ context.report({
531
+ messageId: "caughtErrorShadowed",
532
+ node: throwStatement,
533
+ });
534
+ }
535
+ }
536
+ },
537
+ };
538
+ },
539
+ };
@@ -47,6 +47,8 @@ module.exports = {
47
47
  meta: {
48
48
  type: "suggestion",
49
49
 
50
+ defaultOptions: [{}],
51
+
50
52
  docs: {
51
53
  description:
52
54
  "Enforce the use of `u` or `v` flag on regular expressions",
@@ -79,7 +81,7 @@ module.exports = {
79
81
  create(context) {
80
82
  const sourceCode = context.sourceCode;
81
83
 
82
- const { requireFlag } = context.options[0] ?? {};
84
+ const [{ requireFlag }] = context.options;
83
85
 
84
86
  return {
85
87
  "Literal[regex]"(node) {
@@ -101,7 +101,8 @@ module.exports = {
101
101
  },
102
102
 
103
103
  create(context) {
104
- const ecmaFeatures = context.parserOptions.ecmaFeatures || {},
104
+ const ecmaFeatures =
105
+ context.languageOptions.parserOptions.ecmaFeatures || {},
105
106
  scopes = [],
106
107
  classScopes = [];
107
108
  let [mode] = context.options;
@@ -221,6 +221,9 @@ class SuppressionsService {
221
221
  }
222
222
  throw new Error(
223
223
  `Failed to parse suppressions file at ${this.filePath}`,
224
+ {
225
+ cause: err,
226
+ },
224
227
  );
225
228
  }
226
229
  }
@@ -92,6 +92,8 @@ export namespace Scope {
92
92
  | "block"
93
93
  | "catch"
94
94
  | "class"
95
+ | "class-field-initializer"
96
+ | "class-static-block"
95
97
  | "for"
96
98
  | "function"
97
99
  | "function-expression-name"
@@ -2259,6 +2261,8 @@ export namespace RuleTester {
2259
2261
  only?: boolean;
2260
2262
  languageOptions?: Linter.LanguageOptions | undefined;
2261
2263
  settings?: { [name: string]: any } | undefined;
2264
+ before?: () => void;
2265
+ after?: () => void;
2262
2266
  }
2263
2267
 
2264
2268
  interface SuggestionOutput {