@eslint-react/eslint-plugin 5.30.0-beta.2 → 5.30.0-beta.20
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 +5 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1087 -62
- package/package.json +17 -10
package/dist/index.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { DEFAULT_ESLINT_REACT_SETTINGS } from "@eslint-react/shared";
|
|
1
|
+
import { DEFAULT_ESLINT_REACT_SETTINGS, getSettingsFromContext } from "@eslint-react/shared";
|
|
2
2
|
import reactX from "eslint-plugin-react-x";
|
|
3
3
|
import reactDomPlugin from "eslint-plugin-react-dom";
|
|
4
4
|
import reactJsxPlugin from "eslint-plugin-react-jsx";
|
|
5
5
|
import reactNamingConventionPlugin from "eslint-plugin-react-naming-convention";
|
|
6
6
|
import reactRscPlugin from "eslint-plugin-react-rsc";
|
|
7
7
|
import reactWebApiPlugin from "eslint-plugin-react-web-api";
|
|
8
|
+
import { Extract } from "@eslint-react/ast";
|
|
9
|
+
import { DefinitionType } from "@typescript-eslint/scope-manager";
|
|
10
|
+
import { AST_NODE_TYPES } from "@typescript-eslint/types";
|
|
8
11
|
// \0rolldown/runtime.js
|
|
9
12
|
var __defProp = Object.defineProperty;
|
|
10
13
|
var __exportAll = (all, no_symbols) => {
|
|
@@ -18,11 +21,11 @@ var __exportAll = (all, no_symbols) => {
|
|
|
18
21
|
};
|
|
19
22
|
// src/configs/dom.ts
|
|
20
23
|
var dom_exports = /* @__PURE__ */ __exportAll({
|
|
21
|
-
name: () => name$
|
|
22
|
-
rules: () => rules$
|
|
24
|
+
name: () => name$24,
|
|
25
|
+
rules: () => rules$23
|
|
23
26
|
});
|
|
24
|
-
const name$
|
|
25
|
-
const rules$
|
|
27
|
+
const name$24 = "@eslint-react/dom";
|
|
28
|
+
const rules$23 = {
|
|
26
29
|
"@eslint-react/dom-no-dangerously-set-innerhtml": "warn",
|
|
27
30
|
"@eslint-react/dom-no-dangerously-set-innerhtml-with-children": "error",
|
|
28
31
|
"@eslint-react/dom-no-find-dom-node": "error",
|
|
@@ -37,11 +40,11 @@ const rules$22 = {
|
|
|
37
40
|
};
|
|
38
41
|
// src/configs/jsx.ts
|
|
39
42
|
var jsx_exports = /* @__PURE__ */ __exportAll({
|
|
40
|
-
name: () => name$
|
|
41
|
-
rules: () => rules$
|
|
43
|
+
name: () => name$23,
|
|
44
|
+
rules: () => rules$22
|
|
42
45
|
});
|
|
43
|
-
const name$
|
|
44
|
-
const rules$
|
|
46
|
+
const name$23 = "@eslint-react/jsx";
|
|
47
|
+
const rules$22 = {
|
|
45
48
|
"@eslint-react/jsx-no-children-prop": "warn",
|
|
46
49
|
"@eslint-react/jsx-no-children-prop-with-children": "error",
|
|
47
50
|
"@eslint-react/jsx-no-comment-textnodes": "warn",
|
|
@@ -52,30 +55,30 @@ const rules$21 = {
|
|
|
52
55
|
};
|
|
53
56
|
// src/configs/naming-convention.ts
|
|
54
57
|
var naming_convention_exports = /* @__PURE__ */ __exportAll({
|
|
55
|
-
name: () => name$
|
|
56
|
-
rules: () => rules$
|
|
58
|
+
name: () => name$22,
|
|
59
|
+
rules: () => rules$21
|
|
57
60
|
});
|
|
58
|
-
const name$
|
|
59
|
-
const rules$
|
|
61
|
+
const name$22 = "@eslint-react/naming-convention";
|
|
62
|
+
const rules$21 = {
|
|
60
63
|
"@eslint-react/naming-convention-context-name": "warn",
|
|
61
64
|
"@eslint-react/naming-convention-id-name": "warn",
|
|
62
65
|
"@eslint-react/naming-convention-ref-name": "warn"
|
|
63
66
|
};
|
|
64
67
|
// src/configs/rsc.ts
|
|
65
68
|
var rsc_exports = /* @__PURE__ */ __exportAll({
|
|
66
|
-
name: () => name$
|
|
67
|
-
rules: () => rules$
|
|
69
|
+
name: () => name$21,
|
|
70
|
+
rules: () => rules$20
|
|
68
71
|
});
|
|
69
|
-
const name$
|
|
70
|
-
const rules$
|
|
72
|
+
const name$21 = "@eslint-react/rsc";
|
|
73
|
+
const rules$20 = { "@eslint-react/rsc-function-definition": "error" };
|
|
71
74
|
// src/configs/x.ts
|
|
72
75
|
var x_exports = /* @__PURE__ */ __exportAll({
|
|
73
|
-
name: () => name$
|
|
74
|
-
rules: () => rules$
|
|
75
|
-
settings: () => settings$
|
|
76
|
+
name: () => name$20,
|
|
77
|
+
rules: () => rules$19,
|
|
78
|
+
settings: () => settings$9
|
|
76
79
|
});
|
|
77
|
-
const name$
|
|
78
|
-
const rules$
|
|
80
|
+
const name$20 = "@eslint-react/x";
|
|
81
|
+
const rules$19 = {
|
|
79
82
|
"@eslint-react/error-boundaries": "error",
|
|
80
83
|
"@eslint-react/exhaustive-deps": "warn",
|
|
81
84
|
"@eslint-react/no-access-state-in-setstate": "error",
|
|
@@ -114,15 +117,15 @@ const rules$18 = {
|
|
|
114
117
|
"@eslint-react/use-memo": "error",
|
|
115
118
|
"@eslint-react/use-state": "warn"
|
|
116
119
|
};
|
|
117
|
-
const settings$
|
|
120
|
+
const settings$9 = { "react-x": DEFAULT_ESLINT_REACT_SETTINGS };
|
|
118
121
|
// src/configs/web-api.ts
|
|
119
122
|
var web_api_exports = /* @__PURE__ */ __exportAll({
|
|
120
|
-
name: () => name$
|
|
121
|
-
rules: () => rules$
|
|
122
|
-
settings: () => settings$
|
|
123
|
+
name: () => name$19,
|
|
124
|
+
rules: () => rules$18,
|
|
125
|
+
settings: () => settings$8
|
|
123
126
|
});
|
|
124
|
-
const name$
|
|
125
|
-
const rules$
|
|
127
|
+
const name$19 = "@eslint-react/web-api";
|
|
128
|
+
const rules$18 = {
|
|
126
129
|
"@eslint-react/web-api-no-leaked-event-listener": "warn",
|
|
127
130
|
"@eslint-react/web-api-no-leaked-fetch": "warn",
|
|
128
131
|
"@eslint-react/web-api-no-leaked-intersection-observer": "warn",
|
|
@@ -130,34 +133,34 @@ const rules$17 = {
|
|
|
130
133
|
"@eslint-react/web-api-no-leaked-resize-observer": "warn",
|
|
131
134
|
"@eslint-react/web-api-no-leaked-timeout": "warn"
|
|
132
135
|
};
|
|
133
|
-
const settings$
|
|
136
|
+
const settings$8 = { ...settings$9 };
|
|
134
137
|
// src/configs/recommended.ts
|
|
135
138
|
var recommended_exports = /* @__PURE__ */ __exportAll({
|
|
136
|
-
languageOptions: () => languageOptions$
|
|
137
|
-
name: () => name$
|
|
138
|
-
rules: () => rules$
|
|
139
|
-
settings: () => settings$
|
|
139
|
+
languageOptions: () => languageOptions$7,
|
|
140
|
+
name: () => name$18,
|
|
141
|
+
rules: () => rules$17,
|
|
142
|
+
settings: () => settings$7
|
|
140
143
|
});
|
|
141
|
-
const name$
|
|
142
|
-
const rules$
|
|
143
|
-
...rules$18,
|
|
144
|
-
...rules$21,
|
|
144
|
+
const name$18 = "@eslint-react/recommended";
|
|
145
|
+
const rules$17 = {
|
|
145
146
|
...rules$19,
|
|
146
147
|
...rules$22,
|
|
147
|
-
...rules$
|
|
148
|
-
...rules$
|
|
148
|
+
...rules$20,
|
|
149
|
+
...rules$23,
|
|
150
|
+
...rules$18,
|
|
151
|
+
...rules$21
|
|
149
152
|
};
|
|
150
|
-
const settings$
|
|
151
|
-
const languageOptions$
|
|
153
|
+
const settings$7 = { ...settings$9 };
|
|
154
|
+
const languageOptions$7 = { parserOptions: { ecmaFeatures: { jsx: true } } };
|
|
152
155
|
// src/configs/all.ts
|
|
153
156
|
var all_exports = /* @__PURE__ */ __exportAll({
|
|
154
|
-
languageOptions: () => languageOptions$
|
|
155
|
-
name: () => name$
|
|
156
|
-
rules: () => rules$
|
|
157
|
-
settings: () => settings$
|
|
157
|
+
languageOptions: () => languageOptions$6,
|
|
158
|
+
name: () => name$17,
|
|
159
|
+
rules: () => rules$16,
|
|
160
|
+
settings: () => settings$6
|
|
158
161
|
});
|
|
159
|
-
const name$
|
|
160
|
-
const rules$
|
|
162
|
+
const name$17 = "@eslint-react/all";
|
|
163
|
+
const rules$16 = {
|
|
161
164
|
"@eslint-react/error-boundaries": "error",
|
|
162
165
|
"@eslint-react/exhaustive-deps": "warn",
|
|
163
166
|
"@eslint-react/globals": "warn",
|
|
@@ -241,7 +244,25 @@ const rules$15 = {
|
|
|
241
244
|
"@eslint-react/naming-convention-id-name": "warn",
|
|
242
245
|
"@eslint-react/naming-convention-ref-name": "warn"
|
|
243
246
|
};
|
|
244
|
-
const settings$
|
|
247
|
+
const settings$6 = { ...settings$9 };
|
|
248
|
+
const languageOptions$6 = languageOptions$7;
|
|
249
|
+
// src/configs/all-type-checked.ts
|
|
250
|
+
var all_type_checked_exports = /* @__PURE__ */ __exportAll({
|
|
251
|
+
languageOptions: () => languageOptions$5,
|
|
252
|
+
name: () => name$16,
|
|
253
|
+
rules: () => rules$15,
|
|
254
|
+
settings: () => settings$5
|
|
255
|
+
});
|
|
256
|
+
const name$16 = "@eslint-react/all-type-checked";
|
|
257
|
+
const rules$15 = {
|
|
258
|
+
...rules$16,
|
|
259
|
+
"@eslint-react/no-implicit-children": "warn",
|
|
260
|
+
"@eslint-react/no-implicit-key": "warn",
|
|
261
|
+
"@eslint-react/no-implicit-ref": "warn",
|
|
262
|
+
"@eslint-react/no-leaked-conditional-rendering": "error",
|
|
263
|
+
"@eslint-react/no-unused-props": "warn"
|
|
264
|
+
};
|
|
265
|
+
const settings$5 = { ...settings$6 };
|
|
245
266
|
const languageOptions$5 = languageOptions$6;
|
|
246
267
|
// src/configs/disable-conflict-eslint-plugin-react.ts
|
|
247
268
|
var disable_conflict_eslint_plugin_react_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -263,7 +284,7 @@ var disable_dom_exports = /* @__PURE__ */ __exportAll({
|
|
|
263
284
|
rules: () => rules$12
|
|
264
285
|
});
|
|
265
286
|
const name$13 = "@eslint-react/disable-dom";
|
|
266
|
-
const rules$12 = Object.fromEntries(Object.entries(rules$
|
|
287
|
+
const rules$12 = Object.fromEntries(Object.entries(rules$23).map(([key]) => [key, "off"]));
|
|
267
288
|
// src/configs/disable-experimental.ts
|
|
268
289
|
var disable_experimental_exports = /* @__PURE__ */ __exportAll({
|
|
269
290
|
name: () => name$12,
|
|
@@ -292,21 +313,21 @@ var disable_jsx_exports = /* @__PURE__ */ __exportAll({
|
|
|
292
313
|
rules: () => rules$10
|
|
293
314
|
});
|
|
294
315
|
const name$11 = "@eslint-react/disable-jsx";
|
|
295
|
-
const rules$10 = Object.fromEntries(Object.entries(rules$
|
|
316
|
+
const rules$10 = Object.fromEntries(Object.entries(rules$22).map(([key]) => [key, "off"]));
|
|
296
317
|
// src/configs/disable-naming-convention.ts
|
|
297
318
|
var disable_naming_convention_exports = /* @__PURE__ */ __exportAll({
|
|
298
319
|
name: () => name$10,
|
|
299
320
|
rules: () => rules$9
|
|
300
321
|
});
|
|
301
322
|
const name$10 = "@eslint-react/disable-naming-convention";
|
|
302
|
-
const rules$9 = Object.fromEntries(Object.entries(rules$
|
|
323
|
+
const rules$9 = Object.fromEntries(Object.entries(rules$21).map(([key]) => [key, "off"]));
|
|
303
324
|
// src/configs/disable-rsc.ts
|
|
304
325
|
var disable_rsc_exports = /* @__PURE__ */ __exportAll({
|
|
305
326
|
name: () => name$9,
|
|
306
327
|
rules: () => rules$8
|
|
307
328
|
});
|
|
308
329
|
const name$9 = "@eslint-react/disable-rsc";
|
|
309
|
-
const rules$8 = Object.fromEntries(Object.entries(rules$
|
|
330
|
+
const rules$8 = Object.fromEntries(Object.entries(rules$20).map(([key]) => [key, "off"]));
|
|
310
331
|
// src/configs/disable-type-checked.ts
|
|
311
332
|
var disable_type_checked_exports = /* @__PURE__ */ __exportAll({
|
|
312
333
|
name: () => name$8,
|
|
@@ -326,7 +347,7 @@ var disable_web_api_exports = /* @__PURE__ */ __exportAll({
|
|
|
326
347
|
rules: () => rules$6
|
|
327
348
|
});
|
|
328
349
|
const name$7 = "@eslint-react/disable-web-api";
|
|
329
|
-
const rules$6 = Object.fromEntries(Object.entries(rules$
|
|
350
|
+
const rules$6 = Object.fromEntries(Object.entries(rules$18).map(([key]) => [key, "off"]));
|
|
330
351
|
// src/configs/off.ts
|
|
331
352
|
var off_exports = /* @__PURE__ */ __exportAll({
|
|
332
353
|
name: () => name$6,
|
|
@@ -334,7 +355,7 @@ var off_exports = /* @__PURE__ */ __exportAll({
|
|
|
334
355
|
});
|
|
335
356
|
const name$6 = "@eslint-react/off";
|
|
336
357
|
const rules$5 = {
|
|
337
|
-
...Object.fromEntries(Object.entries(rules$
|
|
358
|
+
...Object.fromEntries(Object.entries(rules$16).map(([key]) => [key, "off"])),
|
|
338
359
|
...rules$7
|
|
339
360
|
};
|
|
340
361
|
// src/configs/recommended-typescript.ts
|
|
@@ -345,9 +366,9 @@ var recommended_typescript_exports = /* @__PURE__ */ __exportAll({
|
|
|
345
366
|
settings: () => settings$4
|
|
346
367
|
});
|
|
347
368
|
const name$5 = "@eslint-react/recommended-typescript";
|
|
348
|
-
const rules$4 = { ...rules$
|
|
349
|
-
const settings$4 = { ...settings$
|
|
350
|
-
const languageOptions$4 = languageOptions$
|
|
369
|
+
const rules$4 = { ...rules$17 };
|
|
370
|
+
const settings$4 = { ...settings$7 };
|
|
371
|
+
const languageOptions$4 = languageOptions$7;
|
|
351
372
|
// src/configs/recommended-type-checked.ts
|
|
352
373
|
var recommended_type_checked_exports = /* @__PURE__ */ __exportAll({
|
|
353
374
|
languageOptions: () => languageOptions$3,
|
|
@@ -371,7 +392,7 @@ var strict_exports = /* @__PURE__ */ __exportAll({
|
|
|
371
392
|
});
|
|
372
393
|
const name$3 = "@eslint-react/strict";
|
|
373
394
|
const rules$2 = {
|
|
374
|
-
...rules$
|
|
395
|
+
...rules$17,
|
|
375
396
|
"@eslint-react/no-class-component": "error",
|
|
376
397
|
"@eslint-react/no-misused-capture-owner-stack": "error",
|
|
377
398
|
"@eslint-react/no-unstable-context-value": "warn",
|
|
@@ -382,8 +403,8 @@ const rules$2 = {
|
|
|
382
403
|
"@eslint-react/dom-no-missing-iframe-sandbox": "warn",
|
|
383
404
|
"@eslint-react/dom-no-unsafe-target-blank": "warn"
|
|
384
405
|
};
|
|
385
|
-
const settings$2 = { ...settings$
|
|
386
|
-
const languageOptions$2 = languageOptions$
|
|
406
|
+
const settings$2 = { ...settings$7 };
|
|
407
|
+
const languageOptions$2 = languageOptions$7;
|
|
387
408
|
// src/configs/strict-typescript.ts
|
|
388
409
|
var strict_typescript_exports = /* @__PURE__ */ __exportAll({
|
|
389
410
|
languageOptions: () => languageOptions$1,
|
|
@@ -412,7 +433,7 @@ const settings = { ...settings$1 };
|
|
|
412
433
|
const languageOptions = languageOptions$1;
|
|
413
434
|
// package.json
|
|
414
435
|
var name = "@eslint-react/eslint-plugin";
|
|
415
|
-
var version = "5.30.0-beta.
|
|
436
|
+
var version = "5.30.0-beta.20";
|
|
416
437
|
// src/utils/type-of.ts
|
|
417
438
|
function typeOf(t) {
|
|
418
439
|
return Object.prototype.toString.call(t).replace(/^\[object (.+)\]$/, "$1").toLowerCase();
|
|
@@ -428,6 +449,1008 @@ function transformKeys(obj, transform) {
|
|
|
428
449
|
function padKeysLeft(obj, left) {
|
|
429
450
|
return transformKeys(obj, (key) => `${left}${key}`);
|
|
430
451
|
}
|
|
452
|
+
// src/rules/exhaustive-deps/lib.ts
|
|
453
|
+
function getHookConfigs(hooks = []) {
|
|
454
|
+
const reactive = /* @__PURE__ */ new Map();
|
|
455
|
+
const stable = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const { name, closureIndex, dependenciesIndex, stableResult } of hooks) {
|
|
457
|
+
if (closureIndex != null && dependenciesIndex != null && closureIndex !== dependenciesIndex) reactive.set(name, {
|
|
458
|
+
closureIndex,
|
|
459
|
+
dependenciesIndex
|
|
460
|
+
});
|
|
461
|
+
if (stableResult === true) stable.set(name, true);
|
|
462
|
+
else if (typeof stableResult === "number") stable.set(name, /* @__PURE__ */ new Set([stableResult]));
|
|
463
|
+
else if (Array.isArray(stableResult)) stable.set(name, new Set(stableResult));
|
|
464
|
+
}
|
|
465
|
+
return {
|
|
466
|
+
reactive,
|
|
467
|
+
stable
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
function getReactiveHookConfig(node, configs) {
|
|
471
|
+
if (configs.reactive.size === 0) return null;
|
|
472
|
+
const name = Extract.getCalleeName(node);
|
|
473
|
+
if (name == null) return null;
|
|
474
|
+
const config = configs.reactive.get(name);
|
|
475
|
+
if (config == null) return null;
|
|
476
|
+
return {
|
|
477
|
+
name,
|
|
478
|
+
...config
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
function isConfiguredStableHookValue(variable, configs) {
|
|
482
|
+
if (configs.stable.size === 0) return false;
|
|
483
|
+
let matchedNode = null;
|
|
484
|
+
let stableResult = null;
|
|
485
|
+
let initializerCount = 0;
|
|
486
|
+
for (const def of variable.defs) {
|
|
487
|
+
if (def.type !== DefinitionType.Variable || def.node.init == null) continue;
|
|
488
|
+
initializerCount++;
|
|
489
|
+
const init = Extract.unwrap(def.node.init);
|
|
490
|
+
if (init.type !== AST_NODE_TYPES.CallExpression) continue;
|
|
491
|
+
const name = Extract.getCalleeName(init);
|
|
492
|
+
if (name == null) continue;
|
|
493
|
+
const config = configs.stable.get(name);
|
|
494
|
+
if (config == null) continue;
|
|
495
|
+
if (matchedNode != null) return false;
|
|
496
|
+
matchedNode = def.node;
|
|
497
|
+
stableResult = config;
|
|
498
|
+
}
|
|
499
|
+
if (initializerCount !== 1) return false;
|
|
500
|
+
if (matchedNode == null || stableResult == null) return false;
|
|
501
|
+
if (variable.references.some((reference) => reference.isWrite() && reference.init !== true)) return false;
|
|
502
|
+
const { id } = matchedNode;
|
|
503
|
+
if (stableResult === true) return id.type === AST_NODE_TYPES.Identifier;
|
|
504
|
+
if (id.type !== AST_NODE_TYPES.ArrayPattern) return false;
|
|
505
|
+
const index = id.elements.findIndex((element) => {
|
|
506
|
+
if (element == null) return false;
|
|
507
|
+
const binding = element.type === AST_NODE_TYPES.AssignmentPattern ? element.left : element;
|
|
508
|
+
return variable.identifiers.some((identifier) => identifier === binding);
|
|
509
|
+
});
|
|
510
|
+
return index !== -1 && stableResult.has(index);
|
|
511
|
+
}
|
|
512
|
+
// src/rules/exhaustive-deps/exhaustive-deps.ts
|
|
513
|
+
const rule = {
|
|
514
|
+
meta: {
|
|
515
|
+
type: "suggestion",
|
|
516
|
+
docs: {
|
|
517
|
+
description: "Verifies the list of dependencies for Hooks like 'useEffect' and similar, with support for custom Hooks and stable Hook results.",
|
|
518
|
+
url: "https://eslint-react.xyz/docs/rules/unstable-exhaustive-deps"
|
|
519
|
+
},
|
|
520
|
+
fixable: "code",
|
|
521
|
+
hasSuggestions: true,
|
|
522
|
+
schema: [{
|
|
523
|
+
type: "object",
|
|
524
|
+
additionalProperties: false,
|
|
525
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: false,
|
|
526
|
+
properties: {
|
|
527
|
+
additionalHooks: { type: "string" },
|
|
528
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: { type: "boolean" },
|
|
529
|
+
experimental_autoDependenciesHooks: {
|
|
530
|
+
type: "array",
|
|
531
|
+
items: { type: "string" }
|
|
532
|
+
},
|
|
533
|
+
hooks: {
|
|
534
|
+
type: "array",
|
|
535
|
+
items: {
|
|
536
|
+
type: "object",
|
|
537
|
+
additionalProperties: false,
|
|
538
|
+
dependencies: {
|
|
539
|
+
closureIndex: ["dependenciesIndex"],
|
|
540
|
+
dependenciesIndex: ["closureIndex"]
|
|
541
|
+
},
|
|
542
|
+
properties: {
|
|
543
|
+
name: {
|
|
544
|
+
type: "string",
|
|
545
|
+
minLength: 1
|
|
546
|
+
},
|
|
547
|
+
closureIndex: {
|
|
548
|
+
type: "integer",
|
|
549
|
+
minimum: 0
|
|
550
|
+
},
|
|
551
|
+
dependenciesIndex: {
|
|
552
|
+
type: "integer",
|
|
553
|
+
minimum: 0
|
|
554
|
+
},
|
|
555
|
+
stableResult: { oneOf: [
|
|
556
|
+
{ type: "boolean" },
|
|
557
|
+
{
|
|
558
|
+
type: "integer",
|
|
559
|
+
minimum: 0
|
|
560
|
+
},
|
|
561
|
+
{
|
|
562
|
+
type: "array",
|
|
563
|
+
items: {
|
|
564
|
+
type: "integer",
|
|
565
|
+
minimum: 0
|
|
566
|
+
},
|
|
567
|
+
minItems: 1
|
|
568
|
+
}
|
|
569
|
+
] }
|
|
570
|
+
},
|
|
571
|
+
required: ["name"]
|
|
572
|
+
}
|
|
573
|
+
},
|
|
574
|
+
requireExplicitEffectDeps: { type: "boolean" }
|
|
575
|
+
}
|
|
576
|
+
}]
|
|
577
|
+
},
|
|
578
|
+
create(context) {
|
|
579
|
+
const rawOptions = context.options && context.options[0];
|
|
580
|
+
const additionalHooks = rawOptions && rawOptions.additionalHooks ? new RegExp(rawOptions.additionalHooks) : getSettingsFromContext(context).additionalEffectHooks;
|
|
581
|
+
const enableDangerousAutofixThisMayCauseInfiniteLoops = rawOptions && rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops || false;
|
|
582
|
+
const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) ? rawOptions.experimental_autoDependenciesHooks : [];
|
|
583
|
+
const requireExplicitEffectDeps = rawOptions && rawOptions.requireExplicitEffectDeps || false;
|
|
584
|
+
const options = {
|
|
585
|
+
additionalHooks,
|
|
586
|
+
experimental_autoDependenciesHooks,
|
|
587
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops,
|
|
588
|
+
hooks: getHookConfigs(rawOptions && rawOptions.hooks),
|
|
589
|
+
requireExplicitEffectDeps
|
|
590
|
+
};
|
|
591
|
+
function reportProblem(problem) {
|
|
592
|
+
if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
|
|
593
|
+
if (Array.isArray(problem.suggest) && problem.suggest.length > 0 && problem.suggest[0]) problem.fix = problem.suggest[0].fix;
|
|
594
|
+
}
|
|
595
|
+
context.report(problem);
|
|
596
|
+
}
|
|
597
|
+
const getSourceCode = typeof context.getSourceCode === "function" ? () => {
|
|
598
|
+
return context.getSourceCode();
|
|
599
|
+
} : () => {
|
|
600
|
+
return context.sourceCode;
|
|
601
|
+
};
|
|
602
|
+
const getScope = typeof context.getScope === "function" ? () => {
|
|
603
|
+
return context.getScope();
|
|
604
|
+
} : (node) => {
|
|
605
|
+
return context.sourceCode.getScope(node);
|
|
606
|
+
};
|
|
607
|
+
const scopeManager = getSourceCode().scopeManager;
|
|
608
|
+
const setStateCallSites = /* @__PURE__ */ new WeakMap();
|
|
609
|
+
const stateVariables = /* @__PURE__ */ new WeakSet();
|
|
610
|
+
const stableKnownValueCache = /* @__PURE__ */ new WeakMap();
|
|
611
|
+
const functionWithoutCapturedValueCache = /* @__PURE__ */ new WeakMap();
|
|
612
|
+
const useEffectEventVariables = /* @__PURE__ */ new WeakSet();
|
|
613
|
+
function memoizeWithWeakMap(fn, map) {
|
|
614
|
+
return function(arg) {
|
|
615
|
+
if (map.has(arg)) return map.get(arg);
|
|
616
|
+
const result = fn(arg);
|
|
617
|
+
map.set(arg, result);
|
|
618
|
+
return result;
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, callExpression, dependenciesIndex) {
|
|
622
|
+
if (isEffect && node.async) reportProblem({
|
|
623
|
+
node,
|
|
624
|
+
message: "Effect callbacks are synchronous to prevent race conditions. Put the async function inside:\n\nuseEffect(() => {\n async function fetchData() {\n // You can await here\n const response = await MyAPI.getData(someId);\n // ...\n }\n fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching"
|
|
625
|
+
});
|
|
626
|
+
const scope = scopeManager.acquire(node);
|
|
627
|
+
if (!scope) throw new Error("Unable to acquire scope for the current node. This is a bug in eslint-plugin-react-hooks, please file an issue.");
|
|
628
|
+
const pureScopes = /* @__PURE__ */ new Set();
|
|
629
|
+
let componentScope = null;
|
|
630
|
+
{
|
|
631
|
+
let currentScope = scope.upper;
|
|
632
|
+
while (currentScope) {
|
|
633
|
+
pureScopes.add(currentScope);
|
|
634
|
+
if (currentScope.type === "function" || currentScope.type === "hook" || currentScope.type === "component") break;
|
|
635
|
+
currentScope = currentScope.upper;
|
|
636
|
+
}
|
|
637
|
+
if (!currentScope) return;
|
|
638
|
+
componentScope = currentScope;
|
|
639
|
+
}
|
|
640
|
+
const isArray = Array.isArray;
|
|
641
|
+
function isStableKnownHookValue(resolved) {
|
|
642
|
+
if (!isArray(resolved.defs)) return false;
|
|
643
|
+
const initializers = resolved.defs.filter((definition) => definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.init != null);
|
|
644
|
+
if (initializers.length !== 1) return false;
|
|
645
|
+
const def = initializers[0];
|
|
646
|
+
const defNode = def.node;
|
|
647
|
+
if (defNode.type !== "VariableDeclarator") return false;
|
|
648
|
+
let init = defNode.init;
|
|
649
|
+
if (init == null) return false;
|
|
650
|
+
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
651
|
+
let declaration = defNode.parent;
|
|
652
|
+
if (declaration == null && componentScope != null) {
|
|
653
|
+
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
654
|
+
declaration = def.node.parent;
|
|
655
|
+
if (declaration == null) return false;
|
|
656
|
+
}
|
|
657
|
+
if (declaration != null && "kind" in declaration && declaration.kind === "const" && init.type === "Literal" && (typeof init.value === "string" || typeof init.value === "number" || init.value === null)) return true;
|
|
658
|
+
if (init.type !== "CallExpression") return false;
|
|
659
|
+
let callee = init.callee;
|
|
660
|
+
if (callee.type === "MemberExpression" && "name" in callee.object && callee.object.name === "React" && callee.property != null && !callee.computed) callee = callee.property;
|
|
661
|
+
if (callee.type !== "Identifier") return false;
|
|
662
|
+
const id = def.node.id;
|
|
663
|
+
const { name } = callee;
|
|
664
|
+
if (name === "useRef" && id.type === "Identifier") return true;
|
|
665
|
+
else if (isUseEffectEventIdentifier(callee) && id.type === "Identifier") {
|
|
666
|
+
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
667
|
+
return true;
|
|
668
|
+
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
669
|
+
const isActionState = name === "useActionState";
|
|
670
|
+
if (id.type === "ArrayPattern" && (isActionState ? id.elements.length >= 2 : id.elements.length === 2) && isArray(resolved.identifiers)) {
|
|
671
|
+
const firstNode = id.elements[0] ?? null;
|
|
672
|
+
const secondNode = id.elements[1] ?? null;
|
|
673
|
+
const firstElement = firstNode?.type === "AssignmentPattern" ? firstNode.left : firstNode;
|
|
674
|
+
const secondElement = secondNode?.type === "AssignmentPattern" ? secondNode.left : secondNode;
|
|
675
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) {
|
|
676
|
+
if (name === "useState") {
|
|
677
|
+
const references = resolved.references;
|
|
678
|
+
for (const reference of references) {
|
|
679
|
+
if (reference.isWrite() && reference.init !== true) return false;
|
|
680
|
+
setStateCallSites.set(reference.identifier, firstElement);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return true;
|
|
684
|
+
} else if (resolved.identifiers.some((identifier) => identifier === firstElement)) {
|
|
685
|
+
if (name === "useState") {
|
|
686
|
+
const references = resolved.references;
|
|
687
|
+
for (const reference of references) stateVariables.add(reference.identifier);
|
|
688
|
+
}
|
|
689
|
+
return false;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
} else if (name === "useTransition") {
|
|
693
|
+
if (id.type === "ArrayPattern" && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
|
|
694
|
+
const secondNode = id.elements[1] ?? null;
|
|
695
|
+
const secondElement = secondNode?.type === "AssignmentPattern" ? secondNode.left : secondNode;
|
|
696
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) return true;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return false;
|
|
700
|
+
}
|
|
701
|
+
function isFunctionWithoutCapturedValues(resolved) {
|
|
702
|
+
if (!isArray(resolved.defs)) return false;
|
|
703
|
+
const def = resolved.defs[0];
|
|
704
|
+
if (def == null) return false;
|
|
705
|
+
if (def.node == null || def.node.id == null) return false;
|
|
706
|
+
const fnNode = def.node;
|
|
707
|
+
const childScopes = componentScope?.childScopes || [];
|
|
708
|
+
let fnScope = null;
|
|
709
|
+
for (const childScope of childScopes) {
|
|
710
|
+
const childScopeBlock = childScope.block;
|
|
711
|
+
if (fnNode.type === "FunctionDeclaration" && childScopeBlock === fnNode || fnNode.type === "VariableDeclarator" && childScopeBlock.parent === fnNode) {
|
|
712
|
+
fnScope = childScope;
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (fnScope == null) return false;
|
|
717
|
+
for (const ref of fnScope.through) {
|
|
718
|
+
if (ref.resolved == null) continue;
|
|
719
|
+
if (pureScopes.has(ref.resolved.scope) && !memoizedIsStableKnownHookValue(ref.resolved)) return false;
|
|
720
|
+
}
|
|
721
|
+
return true;
|
|
722
|
+
}
|
|
723
|
+
const memoizedIsStableKnownHookValue = memoizeWithWeakMap((resolved) => isStableKnownHookValue(resolved) || isConfiguredStableHookValue(resolved, options.hooks), stableKnownValueCache);
|
|
724
|
+
const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache);
|
|
725
|
+
const currentRefsInEffectCleanup = /* @__PURE__ */ new Map();
|
|
726
|
+
function isInsideEffectCleanup(reference) {
|
|
727
|
+
let curScope = reference.from;
|
|
728
|
+
let isInReturnedFunction = false;
|
|
729
|
+
while (curScope != null && curScope.block !== node) {
|
|
730
|
+
if (curScope.type === "function") isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === "ReturnStatement";
|
|
731
|
+
curScope = curScope.upper;
|
|
732
|
+
}
|
|
733
|
+
return isInReturnedFunction;
|
|
734
|
+
}
|
|
735
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
736
|
+
const optionalChains = /* @__PURE__ */ new Map();
|
|
737
|
+
gatherDependenciesRecursively(scope);
|
|
738
|
+
function gatherDependenciesRecursively(currentScope) {
|
|
739
|
+
for (const reference of currentScope.references) {
|
|
740
|
+
if (!reference.resolved) continue;
|
|
741
|
+
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
742
|
+
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
743
|
+
if (referenceNode == null) continue;
|
|
744
|
+
const dependencyNode = getDependency(referenceNode);
|
|
745
|
+
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
746
|
+
if (isEffect && dependencyNode.type === "Identifier" && (dependencyNode.parent?.type === "MemberExpression" || dependencyNode.parent?.type === "OptionalMemberExpression") && !dependencyNode.parent.computed && dependencyNode.parent.property.type === "Identifier" && dependencyNode.parent.property.name === "current" && isInsideEffectCleanup(reference)) currentRefsInEffectCleanup.set(dependency, {
|
|
747
|
+
reference,
|
|
748
|
+
dependencyNode
|
|
749
|
+
});
|
|
750
|
+
if (dependencyNode.parent?.type === "TSTypeQuery" || dependencyNode.parent?.type === "TSTypeReference") continue;
|
|
751
|
+
const def = reference.resolved.defs[0];
|
|
752
|
+
if (def == null) continue;
|
|
753
|
+
if (def.node != null && def.node.init === node.parent) continue;
|
|
754
|
+
if (def.type === "TypeParameter" || dependencyNode.parent?.type === "GenericTypeAnnotation") continue;
|
|
755
|
+
if (!dependencies.has(dependency)) {
|
|
756
|
+
const resolved = reference.resolved;
|
|
757
|
+
const isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
|
|
758
|
+
dependencies.set(dependency, {
|
|
759
|
+
isStable,
|
|
760
|
+
references: [reference]
|
|
761
|
+
});
|
|
762
|
+
} else dependencies.get(dependency)?.references.push(reference);
|
|
763
|
+
}
|
|
764
|
+
for (const childScope of currentScope.childScopes) gatherDependenciesRecursively(childScope);
|
|
765
|
+
}
|
|
766
|
+
currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => {
|
|
767
|
+
const references = reference.resolved?.references || [];
|
|
768
|
+
let foundCurrentAssignment = false;
|
|
769
|
+
for (const ref of references) {
|
|
770
|
+
const { identifier } = ref;
|
|
771
|
+
const { parent } = identifier;
|
|
772
|
+
if (parent != null && parent.type === "MemberExpression" && !parent.computed && parent.property.type === "Identifier" && parent.property.name === "current" && parent.parent?.type === "AssignmentExpression" && parent.parent.left === parent) {
|
|
773
|
+
foundCurrentAssignment = true;
|
|
774
|
+
break;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
if (foundCurrentAssignment) return;
|
|
778
|
+
reportProblem({
|
|
779
|
+
node: dependencyNode.parent.property,
|
|
780
|
+
message: `The ref value '${dependency}.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy '${dependency}.current' to a variable inside the effect, and use that variable in the cleanup function.`
|
|
781
|
+
});
|
|
782
|
+
});
|
|
783
|
+
const staleAssignments = /* @__PURE__ */ new Set();
|
|
784
|
+
function reportStaleAssignment(writeExpr, key) {
|
|
785
|
+
if (staleAssignments.has(key)) return;
|
|
786
|
+
staleAssignments.add(key);
|
|
787
|
+
reportProblem({
|
|
788
|
+
node: writeExpr,
|
|
789
|
+
message: `Assignments to the '${key}' variable from inside React Hook ${getSourceCode().getText(reactiveHook)} will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside ${getSourceCode().getText(reactiveHook)}.`
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
const stableDependencies = /* @__PURE__ */ new Set();
|
|
793
|
+
dependencies.forEach(({ isStable, references }, key) => {
|
|
794
|
+
if (isStable) stableDependencies.add(key);
|
|
795
|
+
references.forEach((reference) => {
|
|
796
|
+
if (reference.writeExpr) reportStaleAssignment(reference.writeExpr, key);
|
|
797
|
+
});
|
|
798
|
+
});
|
|
799
|
+
if (staleAssignments.size > 0) return;
|
|
800
|
+
if (!declaredDependenciesNode) {
|
|
801
|
+
if (isAutoDepsHook) return;
|
|
802
|
+
let setStateInsideEffectWithoutDeps = null;
|
|
803
|
+
dependencies.forEach(({ references }, key) => {
|
|
804
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
805
|
+
references.forEach((reference) => {
|
|
806
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
807
|
+
const id = reference.identifier;
|
|
808
|
+
if (!setStateCallSites.has(id)) return;
|
|
809
|
+
let fnScope = reference.from;
|
|
810
|
+
while (fnScope != null && fnScope.type !== "function") fnScope = fnScope.upper;
|
|
811
|
+
if (fnScope?.block === node) setStateInsideEffectWithoutDeps = key;
|
|
812
|
+
});
|
|
813
|
+
});
|
|
814
|
+
if (setStateInsideEffectWithoutDeps) {
|
|
815
|
+
const { suggestedDependencies } = collectRecommendations({
|
|
816
|
+
dependencies,
|
|
817
|
+
declaredDependencies: [],
|
|
818
|
+
stableDependencies,
|
|
819
|
+
externalDependencies: /* @__PURE__ */ new Set(),
|
|
820
|
+
isEffect: true
|
|
821
|
+
});
|
|
822
|
+
const suggestedDependenciesText = `[${suggestedDependencies.join(", ")}]`;
|
|
823
|
+
const dependenciesArgument = callExpression.arguments[dependenciesIndex];
|
|
824
|
+
const hasSpreadArgumentBeforeOrAtDependencies = callExpression.arguments.slice(0, dependenciesIndex + 1).some((argument) => argument?.type === "SpreadElement");
|
|
825
|
+
let fix = null;
|
|
826
|
+
if (!hasSpreadArgumentBeforeOrAtDependencies) {
|
|
827
|
+
if (dependenciesArgument?.type === "Identifier" && dependenciesArgument.name === "undefined") fix = (fixer) => fixer.replaceText(dependenciesArgument, suggestedDependenciesText);
|
|
828
|
+
else if (dependenciesArgument == null && dependenciesIndex === callExpression.arguments.length) {
|
|
829
|
+
const closeParen = getSourceCode().getLastToken(callExpression);
|
|
830
|
+
if (closeParen != null && closeParen.value === ")") {
|
|
831
|
+
const tokenBeforeCloseParen = getSourceCode().getTokenBefore(closeParen);
|
|
832
|
+
fix = tokenBeforeCloseParen?.value === "," ? (fixer) => fixer.insertTextAfter(tokenBeforeCloseParen, ` ${suggestedDependenciesText}`) : (fixer) => fixer.insertTextBefore(closeParen, `, ${suggestedDependenciesText}`);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
const dependenciesArgumentText = dependenciesIndex === 1 ? "as a second argument" : `as the dependencies argument (index ${dependenciesIndex})`;
|
|
837
|
+
const problem = {
|
|
838
|
+
node: reactiveHook,
|
|
839
|
+
message: `React Hook ${reactiveHookName} contains a call to '${setStateInsideEffectWithoutDeps}'. Without a list of dependencies, this can lead to an infinite chain of updates. To fix this, pass ${suggestedDependenciesText} ${dependenciesArgumentText} to the ${reactiveHookName} Hook.`
|
|
840
|
+
};
|
|
841
|
+
if (fix != null) problem.suggest = [{
|
|
842
|
+
desc: `Add dependencies array: ${suggestedDependenciesText}`,
|
|
843
|
+
fix
|
|
844
|
+
}];
|
|
845
|
+
reportProblem(problem);
|
|
846
|
+
}
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
if (isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
850
|
+
const declaredDependencies = [];
|
|
851
|
+
const externalDependencies = /* @__PURE__ */ new Set();
|
|
852
|
+
const isArrayExpression = declaredDependenciesNode.type === "ArrayExpression";
|
|
853
|
+
const isTSAsArrayExpression = declaredDependenciesNode.type === "TSAsExpression" && declaredDependenciesNode.expression.type === "ArrayExpression";
|
|
854
|
+
if (!isArrayExpression && !isTSAsArrayExpression) reportProblem({
|
|
855
|
+
node: declaredDependenciesNode,
|
|
856
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies.`
|
|
857
|
+
});
|
|
858
|
+
else (isTSAsArrayExpression ? declaredDependenciesNode.expression : declaredDependenciesNode).elements.forEach((declaredDependencyNode) => {
|
|
859
|
+
if (declaredDependencyNode === null) return;
|
|
860
|
+
if (declaredDependencyNode.type === "SpreadElement") {
|
|
861
|
+
reportProblem({
|
|
862
|
+
node: declaredDependencyNode,
|
|
863
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies.`
|
|
864
|
+
});
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
if (useEffectEventVariables.has(declaredDependencyNode)) reportProblem({
|
|
868
|
+
node: declaredDependencyNode,
|
|
869
|
+
message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`,
|
|
870
|
+
suggest: [{
|
|
871
|
+
desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``,
|
|
872
|
+
fix(fixer) {
|
|
873
|
+
return fixer.removeRange(declaredDependencyNode.range);
|
|
874
|
+
}
|
|
875
|
+
}]
|
|
876
|
+
});
|
|
877
|
+
let declaredDependency;
|
|
878
|
+
try {
|
|
879
|
+
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
880
|
+
} catch (error) {
|
|
881
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
882
|
+
if (declaredDependencyNode.type === "Literal") {
|
|
883
|
+
if (declaredDependencyNode.value && dependencies.has(declaredDependencyNode.value)) reportProblem({
|
|
884
|
+
node: declaredDependencyNode,
|
|
885
|
+
message: `The ${declaredDependencyNode.raw} literal is not a valid dependency because it never changes. Did you mean to include ${declaredDependencyNode.value} in the array instead?`
|
|
886
|
+
});
|
|
887
|
+
else reportProblem({
|
|
888
|
+
node: declaredDependencyNode,
|
|
889
|
+
message: `The ${declaredDependencyNode.raw} literal is not a valid dependency because it never changes. You can safely remove it.`
|
|
890
|
+
});
|
|
891
|
+
} else reportProblem({
|
|
892
|
+
node: declaredDependencyNode,
|
|
893
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked.`
|
|
894
|
+
});
|
|
895
|
+
return;
|
|
896
|
+
} else throw error;
|
|
897
|
+
}
|
|
898
|
+
let maybeID = declaredDependencyNode;
|
|
899
|
+
while (maybeID.type === "MemberExpression" || maybeID.type === "OptionalMemberExpression" || maybeID.type === "ChainExpression") maybeID = maybeID.object || maybeID.expression.object;
|
|
900
|
+
const isDeclaredInComponent = !componentScope.through.some((ref) => ref.identifier === maybeID);
|
|
901
|
+
declaredDependencies.push({
|
|
902
|
+
key: declaredDependency,
|
|
903
|
+
node: declaredDependencyNode
|
|
904
|
+
});
|
|
905
|
+
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
906
|
+
});
|
|
907
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
908
|
+
dependencies,
|
|
909
|
+
declaredDependencies,
|
|
910
|
+
stableDependencies,
|
|
911
|
+
externalDependencies,
|
|
912
|
+
isEffect
|
|
913
|
+
});
|
|
914
|
+
let suggestedDeps = suggestedDependencies;
|
|
915
|
+
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
916
|
+
scanForConstructions({
|
|
917
|
+
declaredDependencies,
|
|
918
|
+
declaredDependenciesNode,
|
|
919
|
+
componentScope,
|
|
920
|
+
scope
|
|
921
|
+
}).forEach(({ construction, isUsedOutsideOfHook, depType }) => {
|
|
922
|
+
const wrapperHook = depType === "function" ? "useCallback" : "useMemo";
|
|
923
|
+
const constructionType = depType === "function" ? "definition" : "initialization";
|
|
924
|
+
const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`;
|
|
925
|
+
const advice = isUsedOutsideOfHook ? `To fix this, ${defaultAdvice}` : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`;
|
|
926
|
+
const causation = depType === "conditional" || depType === "logical expression" ? "could make" : "makes";
|
|
927
|
+
const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc?.start.line}) change on every render. ${advice}`;
|
|
928
|
+
let suggest;
|
|
929
|
+
if (isUsedOutsideOfHook && construction.type === "Variable" && depType === "function") suggest = [{
|
|
930
|
+
desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`,
|
|
931
|
+
fix(fixer) {
|
|
932
|
+
const [before, after] = wrapperHook === "useMemo" ? [`useMemo(() => { return `, "; })"] : ["useCallback(", ")"];
|
|
933
|
+
return [fixer.insertTextBefore(construction.node.init, before), fixer.insertTextAfter(construction.node.init, after)];
|
|
934
|
+
}
|
|
935
|
+
}];
|
|
936
|
+
reportProblem({
|
|
937
|
+
node: construction.node,
|
|
938
|
+
message,
|
|
939
|
+
suggest
|
|
940
|
+
});
|
|
941
|
+
});
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
945
|
+
dependencies,
|
|
946
|
+
declaredDependencies: [],
|
|
947
|
+
stableDependencies,
|
|
948
|
+
externalDependencies,
|
|
949
|
+
isEffect
|
|
950
|
+
}).suggestedDependencies;
|
|
951
|
+
function areDeclaredDepsAlphabetized() {
|
|
952
|
+
if (declaredDependencies.length === 0) return true;
|
|
953
|
+
const declaredDepKeys = declaredDependencies.map((dep) => dep.key);
|
|
954
|
+
const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
|
|
955
|
+
return declaredDepKeys.join(",") === sortedDeclaredDepKeys.join(",");
|
|
956
|
+
}
|
|
957
|
+
if (areDeclaredDepsAlphabetized()) suggestedDeps.sort();
|
|
958
|
+
function formatDependency(path) {
|
|
959
|
+
const members = path.split(".");
|
|
960
|
+
let finalPath = "";
|
|
961
|
+
for (let i = 0; i < members.length; i++) {
|
|
962
|
+
if (i !== 0) {
|
|
963
|
+
const pathSoFar = members.slice(0, i + 1).join(".");
|
|
964
|
+
const isOptional = optionalChains.get(pathSoFar) === true;
|
|
965
|
+
finalPath += isOptional ? "?." : ".";
|
|
966
|
+
}
|
|
967
|
+
finalPath += members[i];
|
|
968
|
+
}
|
|
969
|
+
return finalPath;
|
|
970
|
+
}
|
|
971
|
+
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
972
|
+
if (deps.size === 0) return null;
|
|
973
|
+
return (deps.size > 1 ? "" : singlePrefix + " ") + label + " " + (deps.size > 1 ? "dependencies" : "dependency") + ": " + joinEnglish(Array.from(deps).sort().map((name) => "'" + formatDependency(name) + "'")) + `. Either ${fixVerb} ${deps.size > 1 ? "them" : "it"} or remove the dependency array.`;
|
|
974
|
+
}
|
|
975
|
+
let extraWarning = "";
|
|
976
|
+
if (unnecessaryDependencies.size > 0) {
|
|
977
|
+
let badRef = null;
|
|
978
|
+
Array.from(unnecessaryDependencies.keys()).forEach((key) => {
|
|
979
|
+
if (badRef !== null) return;
|
|
980
|
+
if (key.endsWith(".current")) badRef = key;
|
|
981
|
+
});
|
|
982
|
+
if (badRef !== null) extraWarning = ` Mutable values like '${badRef}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
983
|
+
else if (externalDependencies.size > 0) {
|
|
984
|
+
const dep = Array.from(externalDependencies)[0];
|
|
985
|
+
if (!scope.set.has(dep)) extraWarning = ` Outer scope values like '${dep}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
if (!extraWarning && missingDependencies.has("props")) {
|
|
989
|
+
const propDep = dependencies.get("props");
|
|
990
|
+
if (propDep == null) return;
|
|
991
|
+
const refs = propDep.references;
|
|
992
|
+
if (!Array.isArray(refs)) return;
|
|
993
|
+
let isPropsOnlyUsedInMembers = true;
|
|
994
|
+
for (const ref of refs) {
|
|
995
|
+
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
996
|
+
if (!id) {
|
|
997
|
+
isPropsOnlyUsedInMembers = false;
|
|
998
|
+
break;
|
|
999
|
+
}
|
|
1000
|
+
const parent = id.parent;
|
|
1001
|
+
if (parent == null) {
|
|
1002
|
+
isPropsOnlyUsedInMembers = false;
|
|
1003
|
+
break;
|
|
1004
|
+
}
|
|
1005
|
+
if (parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression") {
|
|
1006
|
+
isPropsOnlyUsedInMembers = false;
|
|
1007
|
+
break;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
if (isPropsOnlyUsedInMembers) extraWarning = ` However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the ${reactiveHookName} call and refer to those specific props inside ${getSourceCode().getText(reactiveHook)}.`;
|
|
1011
|
+
}
|
|
1012
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
1013
|
+
let missingCallbackDep = null;
|
|
1014
|
+
missingDependencies.forEach((missingDep) => {
|
|
1015
|
+
if (missingCallbackDep) return;
|
|
1016
|
+
const topScopeRef = componentScope.set.get(missingDep);
|
|
1017
|
+
const usedDep = dependencies.get(missingDep);
|
|
1018
|
+
if (!usedDep?.references || usedDep?.references[0]?.resolved !== topScopeRef) return;
|
|
1019
|
+
const def = topScopeRef?.defs[0];
|
|
1020
|
+
if (def == null || def.name == null || def.type !== "Parameter") return;
|
|
1021
|
+
let isFunctionCall = false;
|
|
1022
|
+
let id;
|
|
1023
|
+
for (const reference of usedDep.references) {
|
|
1024
|
+
id = reference.identifier;
|
|
1025
|
+
if (id != null && id.parent != null && (id.parent.type === "CallExpression" || id.parent.type === "OptionalCallExpression") && id.parent.callee === id) {
|
|
1026
|
+
isFunctionCall = true;
|
|
1027
|
+
break;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
if (!isFunctionCall) return;
|
|
1031
|
+
missingCallbackDep = missingDep;
|
|
1032
|
+
});
|
|
1033
|
+
if (missingCallbackDep !== null) extraWarning = ` If '${missingCallbackDep}' changes too often, find the parent component that defines it and wrap that definition in useCallback.`;
|
|
1034
|
+
}
|
|
1035
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
1036
|
+
let setStateRecommendation = null;
|
|
1037
|
+
for (const missingDep of missingDependencies) {
|
|
1038
|
+
if (setStateRecommendation !== null) break;
|
|
1039
|
+
const references = dependencies.get(missingDep).references;
|
|
1040
|
+
let id;
|
|
1041
|
+
let maybeCall;
|
|
1042
|
+
for (const reference of references) {
|
|
1043
|
+
id = reference.identifier;
|
|
1044
|
+
maybeCall = id.parent;
|
|
1045
|
+
while (maybeCall != null && maybeCall !== componentScope.block) {
|
|
1046
|
+
if (maybeCall.type === "CallExpression") {
|
|
1047
|
+
const correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
|
|
1048
|
+
if (correspondingStateVariable != null) {
|
|
1049
|
+
if ("name" in correspondingStateVariable && correspondingStateVariable.name === missingDep) setStateRecommendation = {
|
|
1050
|
+
missingDep,
|
|
1051
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
1052
|
+
form: "updater"
|
|
1053
|
+
};
|
|
1054
|
+
else if (stateVariables.has(id)) setStateRecommendation = {
|
|
1055
|
+
missingDep,
|
|
1056
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
1057
|
+
form: "reducer"
|
|
1058
|
+
};
|
|
1059
|
+
else {
|
|
1060
|
+
const resolved = reference.resolved;
|
|
1061
|
+
if (resolved != null) {
|
|
1062
|
+
const def = resolved.defs[0];
|
|
1063
|
+
if (def != null && def.type === "Parameter") setStateRecommendation = {
|
|
1064
|
+
missingDep,
|
|
1065
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
1066
|
+
form: "inlineReducer"
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
break;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
maybeCall = maybeCall.parent;
|
|
1074
|
+
}
|
|
1075
|
+
if (setStateRecommendation !== null) break;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
if (setStateRecommendation !== null) switch (setStateRecommendation.form) {
|
|
1079
|
+
case "reducer":
|
|
1080
|
+
extraWarning = ` You can also replace multiple useState variables with useReducer if '${setStateRecommendation.setter}' needs the current value of '${setStateRecommendation.missingDep}'.`;
|
|
1081
|
+
break;
|
|
1082
|
+
case "inlineReducer":
|
|
1083
|
+
extraWarning = ` If '${setStateRecommendation.setter}' needs the current value of '${setStateRecommendation.missingDep}', you can also switch to useReducer instead of useState and read '${setStateRecommendation.missingDep}' in the reducer.`;
|
|
1084
|
+
break;
|
|
1085
|
+
case "updater":
|
|
1086
|
+
extraWarning = ` You can also do a functional update '${setStateRecommendation.setter}(${setStateRecommendation.missingDep.slice(0, 1)} => ...)' if you only need '${setStateRecommendation.missingDep}' in the '${setStateRecommendation.setter}' call.`;
|
|
1087
|
+
break;
|
|
1088
|
+
default: throw new Error("Unknown case.");
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
reportProblem({
|
|
1092
|
+
node: declaredDependenciesNode,
|
|
1093
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + (getWarningMessage(missingDependencies, "a", "missing", "include") || getWarningMessage(unnecessaryDependencies, "an", "unnecessary", "exclude") || getWarningMessage(duplicateDependencies, "a", "duplicate", "omit")) + extraWarning,
|
|
1094
|
+
suggest: [{
|
|
1095
|
+
desc: `Update the dependencies array to be: [${suggestedDeps.map(formatDependency).join(", ")}]`,
|
|
1096
|
+
fix(fixer) {
|
|
1097
|
+
return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(", ")}]`);
|
|
1098
|
+
}
|
|
1099
|
+
}]
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
function visitCallExpression(node) {
|
|
1103
|
+
const configuredHook = getReactiveHookConfig(node, options.hooks);
|
|
1104
|
+
const callbackIndex = configuredHook ? configuredHook.closureIndex : getReactiveHookCallbackIndex(node.callee, options);
|
|
1105
|
+
if (callbackIndex === -1) return;
|
|
1106
|
+
let callback = node.arguments[callbackIndex];
|
|
1107
|
+
const reactiveHook = node.callee;
|
|
1108
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook);
|
|
1109
|
+
const reactiveHookName = configuredHook?.name ?? ("name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "");
|
|
1110
|
+
const dependenciesIndex = configuredHook ? configuredHook.dependenciesIndex : callbackIndex + 1;
|
|
1111
|
+
const maybeNode = node.arguments[dependenciesIndex];
|
|
1112
|
+
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
1113
|
+
const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName);
|
|
1114
|
+
if (!callback) {
|
|
1115
|
+
if (configuredHook) {
|
|
1116
|
+
const builtInCallbackIndex = getReactiveHookCallbackIndex(reactiveHook, { additionalHooks: void 0 });
|
|
1117
|
+
const builtInCallback = builtInCallbackIndex === -1 ? null : node.arguments[builtInCallbackIndex];
|
|
1118
|
+
if (builtInCallbackIndex === -1 || builtInCallback != null) return;
|
|
1119
|
+
}
|
|
1120
|
+
reportProblem({
|
|
1121
|
+
node: reactiveHook,
|
|
1122
|
+
message: `React Hook ${reactiveHookName} requires an effect callback. Did you forget to pass a callback to the hook?`
|
|
1123
|
+
});
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
if (!maybeNode && isEffect && options.requireExplicitEffectDeps) reportProblem({
|
|
1127
|
+
node: reactiveHook,
|
|
1128
|
+
message: `React Hook ${reactiveHookName} always requires dependencies. Please add a dependency array or an explicit \`undefined\``
|
|
1129
|
+
});
|
|
1130
|
+
const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName);
|
|
1131
|
+
if ((!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) && !isEffect) {
|
|
1132
|
+
if (reactiveHookName === "useMemo" || reactiveHookName === "useCallback") reportProblem({
|
|
1133
|
+
node: reactiveHook,
|
|
1134
|
+
message: `React Hook ${reactiveHookName} does nothing when called with only one argument. Did you forget to pass an array of dependencies?`
|
|
1135
|
+
});
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
while (callback.type === "TSAsExpression" || callback.type === "AsExpression") callback = callback.expression;
|
|
1139
|
+
switch (callback.type) {
|
|
1140
|
+
case "FunctionExpression":
|
|
1141
|
+
case "ArrowFunctionExpression":
|
|
1142
|
+
visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
1143
|
+
return;
|
|
1144
|
+
case "Identifier":
|
|
1145
|
+
if (!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
1146
|
+
if ("elements" in declaredDependenciesNode && declaredDependenciesNode.elements && declaredDependenciesNode.elements.some((el) => el && el.type === "Identifier" && el.name === callback.name)) return;
|
|
1147
|
+
const variable = getScope(callback).set.get(callback.name);
|
|
1148
|
+
if (variable == null || variable.defs == null) return;
|
|
1149
|
+
const def = variable.defs[0];
|
|
1150
|
+
if (!def || !def.node) break;
|
|
1151
|
+
if (def.type === "Parameter") {
|
|
1152
|
+
reportProblem({
|
|
1153
|
+
node: reactiveHook,
|
|
1154
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
1155
|
+
});
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
if (def.type !== "Variable" && def.type !== "FunctionName") break;
|
|
1159
|
+
switch (def.node.type) {
|
|
1160
|
+
case "FunctionDeclaration":
|
|
1161
|
+
visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
1162
|
+
return;
|
|
1163
|
+
case "VariableDeclarator":
|
|
1164
|
+
const init = def.node.init;
|
|
1165
|
+
if (!init) break;
|
|
1166
|
+
switch (init.type) {
|
|
1167
|
+
case "ArrowFunctionExpression":
|
|
1168
|
+
case "FunctionExpression":
|
|
1169
|
+
visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
break;
|
|
1174
|
+
default:
|
|
1175
|
+
if (configuredHook) return;
|
|
1176
|
+
reportProblem({
|
|
1177
|
+
node: reactiveHook,
|
|
1178
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
1179
|
+
});
|
|
1180
|
+
return;
|
|
1181
|
+
}
|
|
1182
|
+
reportProblem({
|
|
1183
|
+
node: reactiveHook,
|
|
1184
|
+
message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. Either include it or remove the dependency array.`,
|
|
1185
|
+
suggest: [{
|
|
1186
|
+
desc: `Update the dependencies array to be: [${callback.name}]`,
|
|
1187
|
+
fix(fixer) {
|
|
1188
|
+
return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`);
|
|
1189
|
+
}
|
|
1190
|
+
}]
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
return { CallExpression: visitCallExpression };
|
|
1194
|
+
}
|
|
1195
|
+
};
|
|
1196
|
+
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
1197
|
+
const depTree = createDepTree();
|
|
1198
|
+
function createDepTree() {
|
|
1199
|
+
return {
|
|
1200
|
+
isUsed: false,
|
|
1201
|
+
isSatisfiedRecursively: false,
|
|
1202
|
+
isSubtreeUsed: false,
|
|
1203
|
+
children: /* @__PURE__ */ new Map()
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
dependencies.forEach((_, key) => {
|
|
1207
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
1208
|
+
node.isUsed = true;
|
|
1209
|
+
markAllParentsByPath(depTree, key, (parent) => {
|
|
1210
|
+
parent.isSubtreeUsed = true;
|
|
1211
|
+
});
|
|
1212
|
+
});
|
|
1213
|
+
declaredDependencies.forEach(({ key }) => {
|
|
1214
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
1215
|
+
node.isSatisfiedRecursively = true;
|
|
1216
|
+
});
|
|
1217
|
+
stableDependencies.forEach((key) => {
|
|
1218
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
1219
|
+
node.isSatisfiedRecursively = true;
|
|
1220
|
+
});
|
|
1221
|
+
function getOrCreateNodeByPath(rootNode, path) {
|
|
1222
|
+
const keys = path.split(".");
|
|
1223
|
+
let node = rootNode;
|
|
1224
|
+
for (const key of keys) {
|
|
1225
|
+
let child = node.children.get(key);
|
|
1226
|
+
if (!child) {
|
|
1227
|
+
child = createDepTree();
|
|
1228
|
+
node.children.set(key, child);
|
|
1229
|
+
}
|
|
1230
|
+
node = child;
|
|
1231
|
+
}
|
|
1232
|
+
return node;
|
|
1233
|
+
}
|
|
1234
|
+
function markAllParentsByPath(rootNode, path, fn) {
|
|
1235
|
+
const keys = path.split(".");
|
|
1236
|
+
let node = rootNode;
|
|
1237
|
+
for (const key of keys) {
|
|
1238
|
+
const child = node.children.get(key);
|
|
1239
|
+
if (!child) return;
|
|
1240
|
+
fn(child);
|
|
1241
|
+
node = child;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
const missingDependencies = /* @__PURE__ */ new Set();
|
|
1245
|
+
const satisfyingDependencies = /* @__PURE__ */ new Set();
|
|
1246
|
+
scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, (key) => key);
|
|
1247
|
+
function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
|
|
1248
|
+
node.children.forEach((child, key) => {
|
|
1249
|
+
const path = keyToPath(key);
|
|
1250
|
+
if (child.isSatisfiedRecursively) {
|
|
1251
|
+
if (child.isSubtreeUsed) satisfyingPaths.add(path);
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
if (child.isUsed) {
|
|
1255
|
+
missingPaths.add(path);
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
scanTreeRecursively(child, missingPaths, satisfyingPaths, (childKey) => path + "." + childKey);
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
const suggestedDependencies = [];
|
|
1262
|
+
const unnecessaryDependencies = /* @__PURE__ */ new Set();
|
|
1263
|
+
const duplicateDependencies = /* @__PURE__ */ new Set();
|
|
1264
|
+
declaredDependencies.forEach(({ key }) => {
|
|
1265
|
+
if (satisfyingDependencies.has(key)) {
|
|
1266
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
1267
|
+
else duplicateDependencies.add(key);
|
|
1268
|
+
} else if (isEffect && !key.endsWith(".current") && !externalDependencies.has(key)) {
|
|
1269
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
1270
|
+
} else unnecessaryDependencies.add(key);
|
|
1271
|
+
});
|
|
1272
|
+
missingDependencies.forEach((key) => {
|
|
1273
|
+
suggestedDependencies.push(key);
|
|
1274
|
+
});
|
|
1275
|
+
return {
|
|
1276
|
+
suggestedDependencies,
|
|
1277
|
+
unnecessaryDependencies,
|
|
1278
|
+
duplicateDependencies,
|
|
1279
|
+
missingDependencies
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
function getConstructionExpressionType(node) {
|
|
1283
|
+
switch (node.type) {
|
|
1284
|
+
case "ObjectExpression": return "object";
|
|
1285
|
+
case "ArrayExpression": return "array";
|
|
1286
|
+
case "ArrowFunctionExpression":
|
|
1287
|
+
case "FunctionExpression": return "function";
|
|
1288
|
+
case "ClassExpression": return "class";
|
|
1289
|
+
case "ConditionalExpression":
|
|
1290
|
+
if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
|
|
1291
|
+
return null;
|
|
1292
|
+
case "LogicalExpression":
|
|
1293
|
+
if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
|
|
1294
|
+
return null;
|
|
1295
|
+
case "JSXFragment": return "JSX fragment";
|
|
1296
|
+
case "JSXElement": return "JSX element";
|
|
1297
|
+
case "AssignmentExpression":
|
|
1298
|
+
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
1299
|
+
return null;
|
|
1300
|
+
case "NewExpression": return "object construction";
|
|
1301
|
+
case "Literal":
|
|
1302
|
+
if (node.value instanceof RegExp) return "regular expression";
|
|
1303
|
+
return null;
|
|
1304
|
+
case "TypeCastExpression":
|
|
1305
|
+
case "AsExpression":
|
|
1306
|
+
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
1307
|
+
}
|
|
1308
|
+
return null;
|
|
1309
|
+
}
|
|
1310
|
+
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
1311
|
+
const constructions = declaredDependencies.map(({ key }) => {
|
|
1312
|
+
const ref = componentScope.variables.find((v) => v.name === key);
|
|
1313
|
+
if (ref == null) return null;
|
|
1314
|
+
const node = ref.defs[0];
|
|
1315
|
+
if (node == null) return null;
|
|
1316
|
+
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
1317
|
+
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
1318
|
+
if (constantExpressionType) return [ref, constantExpressionType];
|
|
1319
|
+
}
|
|
1320
|
+
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
1321
|
+
if (node.type === "ClassName" && node.node.type === "ClassDeclaration") return [ref, "class"];
|
|
1322
|
+
return null;
|
|
1323
|
+
}).filter(Boolean);
|
|
1324
|
+
function isUsedOutsideOfHook(ref) {
|
|
1325
|
+
let foundWriteExpr = false;
|
|
1326
|
+
for (const reference of ref.references) {
|
|
1327
|
+
if (reference.writeExpr) {
|
|
1328
|
+
if (foundWriteExpr) return true;
|
|
1329
|
+
else {
|
|
1330
|
+
foundWriteExpr = true;
|
|
1331
|
+
continue;
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
let currentScope = reference.from;
|
|
1335
|
+
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
1336
|
+
if (currentScope !== scope) {
|
|
1337
|
+
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
return false;
|
|
1341
|
+
}
|
|
1342
|
+
return constructions.map(([ref, depType]) => ({
|
|
1343
|
+
construction: ref.defs[0],
|
|
1344
|
+
depType,
|
|
1345
|
+
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
1346
|
+
}));
|
|
1347
|
+
}
|
|
1348
|
+
function getDependency(node) {
|
|
1349
|
+
if (node.parent && (node.parent.type === "MemberExpression" || node.parent.type === "OptionalMemberExpression") && node.parent.object === node && "name" in node.parent.property && node.parent.property.name !== "current" && !node.parent.computed && !(node.parent.parent != null && (node.parent.parent.type === "CallExpression" || node.parent.parent.type === "OptionalCallExpression") && node.parent.parent.callee === node.parent)) return getDependency(node.parent);
|
|
1350
|
+
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
1351
|
+
else return node;
|
|
1352
|
+
}
|
|
1353
|
+
function markNode(node, optionalChains, result) {
|
|
1354
|
+
if (optionalChains) {
|
|
1355
|
+
if ("optional" in node && node.optional) {
|
|
1356
|
+
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
1357
|
+
} else optionalChains.set(result, false);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
function analyzePropertyChain(node, optionalChains) {
|
|
1361
|
+
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
1362
|
+
const result = node.name;
|
|
1363
|
+
if (optionalChains) optionalChains.set(result, false);
|
|
1364
|
+
return result;
|
|
1365
|
+
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
1366
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
1367
|
+
markNode(node, optionalChains, result);
|
|
1368
|
+
return result;
|
|
1369
|
+
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
1370
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
1371
|
+
markNode(node, optionalChains, result);
|
|
1372
|
+
return result;
|
|
1373
|
+
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
1374
|
+
const expression = node.expression;
|
|
1375
|
+
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
1376
|
+
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
1377
|
+
markNode(expression, optionalChains, result);
|
|
1378
|
+
return result;
|
|
1379
|
+
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
1380
|
+
}
|
|
1381
|
+
function getNodeWithoutReactNamespace(node) {
|
|
1382
|
+
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
1383
|
+
return node;
|
|
1384
|
+
}
|
|
1385
|
+
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
1386
|
+
const node = getNodeWithoutReactNamespace(calleeNode);
|
|
1387
|
+
if (node.type !== "Identifier") return -1;
|
|
1388
|
+
switch (node.name) {
|
|
1389
|
+
case "useEffect":
|
|
1390
|
+
case "useLayoutEffect":
|
|
1391
|
+
case "useCallback":
|
|
1392
|
+
case "useMemo": return 0;
|
|
1393
|
+
case "useImperativeHandle": return 1;
|
|
1394
|
+
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
1395
|
+
let name;
|
|
1396
|
+
try {
|
|
1397
|
+
name = analyzePropertyChain(node, null);
|
|
1398
|
+
} catch (error) {
|
|
1399
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
1400
|
+
else throw error;
|
|
1401
|
+
}
|
|
1402
|
+
if (options.additionalHooks instanceof RegExp) options.additionalHooks.lastIndex = 0;
|
|
1403
|
+
return options.additionalHooks.test(name) ? 0 : -1;
|
|
1404
|
+
} else return -1;
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
function fastFindReferenceWithParent(start, target) {
|
|
1408
|
+
const queue = [start];
|
|
1409
|
+
let item;
|
|
1410
|
+
while (queue.length) {
|
|
1411
|
+
item = queue.shift();
|
|
1412
|
+
if (isSameIdentifier(item, target)) return item;
|
|
1413
|
+
if (!isAncestorNodeOf(item, target)) continue;
|
|
1414
|
+
for (const [key, value] of Object.entries(item)) {
|
|
1415
|
+
if (key === "parent") continue;
|
|
1416
|
+
if (isNodeLike(value)) {
|
|
1417
|
+
value.parent = item;
|
|
1418
|
+
queue.push(value);
|
|
1419
|
+
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
1420
|
+
if (isNodeLike(val)) {
|
|
1421
|
+
val.parent = item;
|
|
1422
|
+
queue.push(val);
|
|
1423
|
+
}
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
return null;
|
|
1428
|
+
}
|
|
1429
|
+
function joinEnglish(arr) {
|
|
1430
|
+
let s = "";
|
|
1431
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1432
|
+
s += arr[i];
|
|
1433
|
+
if (i === 0 && arr.length === 2) s += " and ";
|
|
1434
|
+
else if (i === arr.length - 2 && arr.length > 2) s += ", and ";
|
|
1435
|
+
else if (i < arr.length - 1) s += ", ";
|
|
1436
|
+
}
|
|
1437
|
+
return s;
|
|
1438
|
+
}
|
|
1439
|
+
function isNodeLike(val) {
|
|
1440
|
+
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
1441
|
+
}
|
|
1442
|
+
function isSameIdentifier(a, b) {
|
|
1443
|
+
return (a.type === "Identifier" || a.type === "JSXIdentifier") && a.type === b.type && a.name === b.name && !!a.range && !!b.range && a.range[0] === b.range[0] && a.range[1] === b.range[1];
|
|
1444
|
+
}
|
|
1445
|
+
function isAncestorNodeOf(a, b) {
|
|
1446
|
+
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
1447
|
+
}
|
|
1448
|
+
function isUseEffectEventIdentifier(node) {
|
|
1449
|
+
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
1450
|
+
}
|
|
1451
|
+
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
1452
|
+
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
1453
|
+
}
|
|
431
1454
|
// src/plugin.ts
|
|
432
1455
|
const plugin = {
|
|
433
1456
|
meta: {
|
|
@@ -441,7 +1464,8 @@ const plugin = {
|
|
|
441
1464
|
...padKeysLeft(reactRscPlugin.rules, "rsc-"),
|
|
442
1465
|
...padKeysLeft(reactDomPlugin.rules, "dom-"),
|
|
443
1466
|
...padKeysLeft(reactWebApiPlugin.rules, "web-api-"),
|
|
444
|
-
...padKeysLeft(reactNamingConventionPlugin.rules, "naming-convention-")
|
|
1467
|
+
...padKeysLeft(reactNamingConventionPlugin.rules, "naming-convention-"),
|
|
1468
|
+
"unstable-exhaustive-deps": rule
|
|
445
1469
|
}
|
|
446
1470
|
};
|
|
447
1471
|
// src/index.ts
|
|
@@ -460,6 +1484,7 @@ const finalPlugin = {
|
|
|
460
1484
|
...plugin,
|
|
461
1485
|
configs: {
|
|
462
1486
|
["all"]: createConfig(all_exports),
|
|
1487
|
+
["all-type-checked"]: createConfig(all_type_checked_exports),
|
|
463
1488
|
["disable-conflict-eslint-plugin-react"]: createConfig(disable_conflict_eslint_plugin_react_exports),
|
|
464
1489
|
["disable-conflict-eslint-plugin-react-hooks"]: createConfig(disable_conflict_eslint_plugin_react_hooks_exports),
|
|
465
1490
|
["disable-dom"]: createConfig(disable_dom_exports),
|