eslint-plugin-react-x 5.30.0-beta.1 → 5.30.0-beta.3
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/dist/index.js +1184 -359
- package/package.json +7 -8
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DEFAULT_ESLINT_REACT_SETTINGS, getSettingsFromContext, toRegExp } from "@eslint-react/shared";
|
|
2
2
|
import * as ESLintUtils from "@typescript-eslint/utils/eslint-utils";
|
|
3
|
-
import { Check, Compare, Extract, Traverse } from "@eslint-react/ast";
|
|
3
|
+
import { Check, Collect, Compare, Extract, Traverse } from "@eslint-react/ast";
|
|
4
4
|
import * as core from "@eslint-react/core";
|
|
5
5
|
import { getConstrainedTypeAtLocation, getText, merge, report } from "@eslint-react/eslint";
|
|
6
6
|
import { AST_NODE_TYPES } from "@typescript-eslint/types";
|
|
@@ -12,7 +12,6 @@ import { findParentAttribute, getCreateElementPropsObject, getElementFullType, h
|
|
|
12
12
|
import { compare } from "compare-versions";
|
|
13
13
|
import { unionConstituents } from "ts-api-utils";
|
|
14
14
|
import "typescript";
|
|
15
|
-
import { simpleTraverse } from "@typescript-eslint/typescript-estree";
|
|
16
15
|
import { delimiterCase, snakeCase, toLowerCase } from "string-ts";
|
|
17
16
|
// \0rolldown/runtime.js
|
|
18
17
|
var __defProp = Object.defineProperty;
|
|
@@ -113,7 +112,8 @@ const rules$7 = {
|
|
|
113
112
|
"react-x/no-unused-state": "off",
|
|
114
113
|
"react-x/refs": "off",
|
|
115
114
|
"react-x/set-state-in-render": "off",
|
|
116
|
-
"react-x/static-components": "off"
|
|
115
|
+
"react-x/static-components": "off",
|
|
116
|
+
"react-x/unstable-exhaustive-deps": "off"
|
|
117
117
|
};
|
|
118
118
|
// src/configs/disable-type-checked.ts
|
|
119
119
|
var disable_type_checked_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -130,7 +130,7 @@ const rules$6 = {
|
|
|
130
130
|
};
|
|
131
131
|
// package.json
|
|
132
132
|
var name$6 = "eslint-plugin-react-x";
|
|
133
|
-
var version = "5.30.0-beta.
|
|
133
|
+
var version = "5.30.0-beta.3";
|
|
134
134
|
// src/utils/create-rule.ts
|
|
135
135
|
function getDocsUrl(ruleName) {
|
|
136
136
|
return `https://eslint-react.xyz/docs/rules/${ruleName}`;
|
|
@@ -192,7 +192,7 @@ function create$50(context) {
|
|
|
192
192
|
});
|
|
193
193
|
}
|
|
194
194
|
// src/rules/exhaustive-deps/exhaustive-deps.ts
|
|
195
|
-
const rule$
|
|
195
|
+
const rule$2 = {
|
|
196
196
|
meta: {
|
|
197
197
|
type: "suggestion",
|
|
198
198
|
docs: {
|
|
@@ -288,7 +288,7 @@ const rule$1 = {
|
|
|
288
288
|
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
289
289
|
let declaration = defNode.parent;
|
|
290
290
|
if (declaration == null && componentScope != null) {
|
|
291
|
-
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
291
|
+
fastFindReferenceWithParent$1(componentScope.block, def.node.id);
|
|
292
292
|
declaration = def.node.parent;
|
|
293
293
|
if (declaration == null) return false;
|
|
294
294
|
}
|
|
@@ -300,7 +300,7 @@ const rule$1 = {
|
|
|
300
300
|
const id = def.node.id;
|
|
301
301
|
const { name } = callee;
|
|
302
302
|
if (name === "useRef" && id.type === "Identifier") return true;
|
|
303
|
-
else if (isUseEffectEventIdentifier$
|
|
303
|
+
else if (isUseEffectEventIdentifier$2(callee) && id.type === "Identifier") {
|
|
304
304
|
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
305
305
|
return true;
|
|
306
306
|
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
@@ -372,10 +372,10 @@ const rule$1 = {
|
|
|
372
372
|
for (const reference of currentScope.references) {
|
|
373
373
|
if (!reference.resolved) continue;
|
|
374
374
|
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
375
|
-
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
375
|
+
const referenceNode = fastFindReferenceWithParent$1(node, reference.identifier);
|
|
376
376
|
if (referenceNode == null) continue;
|
|
377
|
-
const dependencyNode = getDependency(referenceNode);
|
|
378
|
-
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
377
|
+
const dependencyNode = getDependency$1(referenceNode);
|
|
378
|
+
const dependency = analyzePropertyChain$1(dependencyNode, optionalChains);
|
|
379
379
|
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, {
|
|
380
380
|
reference,
|
|
381
381
|
dependencyNode
|
|
@@ -445,7 +445,7 @@ const rule$1 = {
|
|
|
445
445
|
});
|
|
446
446
|
});
|
|
447
447
|
if (setStateInsideEffectWithoutDeps) {
|
|
448
|
-
const { suggestedDependencies } = collectRecommendations({
|
|
448
|
+
const { suggestedDependencies } = collectRecommendations$1({
|
|
449
449
|
dependencies,
|
|
450
450
|
declaredDependencies: [],
|
|
451
451
|
stableDependencies,
|
|
@@ -495,7 +495,7 @@ const rule$1 = {
|
|
|
495
495
|
});
|
|
496
496
|
let declaredDependency;
|
|
497
497
|
try {
|
|
498
|
-
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
498
|
+
declaredDependency = analyzePropertyChain$1(declaredDependencyNode, null);
|
|
499
499
|
} catch (error) {
|
|
500
500
|
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
501
501
|
if (declaredDependencyNode.type === "Literal") {
|
|
@@ -523,7 +523,7 @@ const rule$1 = {
|
|
|
523
523
|
});
|
|
524
524
|
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
525
525
|
});
|
|
526
|
-
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
526
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations$1({
|
|
527
527
|
dependencies,
|
|
528
528
|
declaredDependencies,
|
|
529
529
|
stableDependencies,
|
|
@@ -532,7 +532,7 @@ const rule$1 = {
|
|
|
532
532
|
});
|
|
533
533
|
let suggestedDeps = suggestedDependencies;
|
|
534
534
|
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
535
|
-
scanForConstructions({
|
|
535
|
+
scanForConstructions$1({
|
|
536
536
|
declaredDependencies,
|
|
537
537
|
declaredDependenciesNode,
|
|
538
538
|
componentScope,
|
|
@@ -560,7 +560,7 @@ const rule$1 = {
|
|
|
560
560
|
});
|
|
561
561
|
return;
|
|
562
562
|
}
|
|
563
|
-
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
563
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations$1({
|
|
564
564
|
dependencies,
|
|
565
565
|
declaredDependencies: [],
|
|
566
566
|
stableDependencies,
|
|
@@ -589,7 +589,7 @@ const rule$1 = {
|
|
|
589
589
|
}
|
|
590
590
|
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
591
591
|
if (deps.size === 0) return null;
|
|
592
|
-
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.`;
|
|
592
|
+
return (deps.size > 1 ? "" : singlePrefix + " ") + label + " " + (deps.size > 1 ? "dependencies" : "dependency") + ": " + joinEnglish$1(Array.from(deps).sort().map((name) => "'" + formatDependency(name) + "'")) + `. Either ${fixVerb} ${deps.size > 1 ? "them" : "it"} or remove the dependency array.`;
|
|
593
593
|
}
|
|
594
594
|
let extraWarning = "";
|
|
595
595
|
if (unnecessaryDependencies.size > 0) {
|
|
@@ -611,7 +611,7 @@ const rule$1 = {
|
|
|
611
611
|
if (!Array.isArray(refs)) return;
|
|
612
612
|
let isPropsOnlyUsedInMembers = true;
|
|
613
613
|
for (const ref of refs) {
|
|
614
|
-
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
614
|
+
const id = fastFindReferenceWithParent$1(componentScope.block, ref.identifier);
|
|
615
615
|
if (!id) {
|
|
616
616
|
isPropsOnlyUsedInMembers = false;
|
|
617
617
|
break;
|
|
@@ -719,11 +719,11 @@ const rule$1 = {
|
|
|
719
719
|
});
|
|
720
720
|
}
|
|
721
721
|
function visitCallExpression(node) {
|
|
722
|
-
const callbackIndex = getReactiveHookCallbackIndex(node.callee, options);
|
|
722
|
+
const callbackIndex = getReactiveHookCallbackIndex$1(node.callee, options);
|
|
723
723
|
if (callbackIndex === -1) return;
|
|
724
724
|
let callback = node.arguments[callbackIndex];
|
|
725
725
|
const reactiveHook = node.callee;
|
|
726
|
-
const nodeWithoutNamespace = getNodeWithoutReactNamespace$
|
|
726
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace$2(reactiveHook);
|
|
727
727
|
const reactiveHookName = "name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "";
|
|
728
728
|
const maybeNode = node.arguments[callbackIndex + 1];
|
|
729
729
|
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
@@ -763,7 +763,7 @@ const rule$1 = {
|
|
|
763
763
|
if (def.type === "Parameter") {
|
|
764
764
|
reportProblem({
|
|
765
765
|
node: reactiveHook,
|
|
766
|
-
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
766
|
+
message: getUnknownDependenciesMessage$1(reactiveHookName)
|
|
767
767
|
});
|
|
768
768
|
return;
|
|
769
769
|
}
|
|
@@ -786,7 +786,7 @@ const rule$1 = {
|
|
|
786
786
|
default:
|
|
787
787
|
reportProblem({
|
|
788
788
|
node: reactiveHook,
|
|
789
|
-
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
789
|
+
message: getUnknownDependenciesMessage$1(reactiveHookName)
|
|
790
790
|
});
|
|
791
791
|
return;
|
|
792
792
|
}
|
|
@@ -804,7 +804,7 @@ const rule$1 = {
|
|
|
804
804
|
return { CallExpression: visitCallExpression };
|
|
805
805
|
}
|
|
806
806
|
};
|
|
807
|
-
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
807
|
+
function collectRecommendations$1({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
808
808
|
const depTree = createDepTree();
|
|
809
809
|
function createDepTree() {
|
|
810
810
|
return {
|
|
@@ -890,7 +890,7 @@ function collectRecommendations({ dependencies, declaredDependencies, stableDepe
|
|
|
890
890
|
missingDependencies
|
|
891
891
|
};
|
|
892
892
|
}
|
|
893
|
-
function getConstructionExpressionType(node) {
|
|
893
|
+
function getConstructionExpressionType$1(node) {
|
|
894
894
|
switch (node.type) {
|
|
895
895
|
case "ObjectExpression": return "object";
|
|
896
896
|
case "ArrayExpression": return "array";
|
|
@@ -898,15 +898,15 @@ function getConstructionExpressionType(node) {
|
|
|
898
898
|
case "FunctionExpression": return "function";
|
|
899
899
|
case "ClassExpression": return "class";
|
|
900
900
|
case "ConditionalExpression":
|
|
901
|
-
if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
|
|
901
|
+
if (getConstructionExpressionType$1(node.consequent) != null || getConstructionExpressionType$1(node.alternate) != null) return "conditional";
|
|
902
902
|
return null;
|
|
903
903
|
case "LogicalExpression":
|
|
904
|
-
if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
|
|
904
|
+
if (getConstructionExpressionType$1(node.left) != null || getConstructionExpressionType$1(node.right) != null) return "logical expression";
|
|
905
905
|
return null;
|
|
906
906
|
case "JSXFragment": return "JSX fragment";
|
|
907
907
|
case "JSXElement": return "JSX element";
|
|
908
908
|
case "AssignmentExpression":
|
|
909
|
-
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
909
|
+
if (getConstructionExpressionType$1(node.right) != null) return "assignment expression";
|
|
910
910
|
return null;
|
|
911
911
|
case "NewExpression": return "object construction";
|
|
912
912
|
case "Literal":
|
|
@@ -914,18 +914,18 @@ function getConstructionExpressionType(node) {
|
|
|
914
914
|
return null;
|
|
915
915
|
case "TypeCastExpression":
|
|
916
916
|
case "AsExpression":
|
|
917
|
-
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
917
|
+
case "TSAsExpression": return getConstructionExpressionType$1(node.expression);
|
|
918
918
|
}
|
|
919
919
|
return null;
|
|
920
920
|
}
|
|
921
|
-
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
921
|
+
function scanForConstructions$1({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
922
922
|
const constructions = declaredDependencies.map(({ key }) => {
|
|
923
923
|
const ref = componentScope.variables.find((v) => v.name === key);
|
|
924
924
|
if (ref == null) return null;
|
|
925
925
|
const node = ref.defs[0];
|
|
926
926
|
if (node == null) return null;
|
|
927
927
|
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
928
|
-
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
928
|
+
const constantExpressionType = getConstructionExpressionType$1(node.node.init);
|
|
929
929
|
if (constantExpressionType) return [ref, constantExpressionType];
|
|
930
930
|
}
|
|
931
931
|
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
@@ -945,7 +945,7 @@ function scanForConstructions({ declaredDependencies, declaredDependenciesNode,
|
|
|
945
945
|
let currentScope = reference.from;
|
|
946
946
|
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
947
947
|
if (currentScope !== scope) {
|
|
948
|
-
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
948
|
+
if (!isAncestorNodeOf$1(declaredDependenciesNode, reference.identifier)) return true;
|
|
949
949
|
}
|
|
950
950
|
}
|
|
951
951
|
return false;
|
|
@@ -956,45 +956,45 @@ function scanForConstructions({ declaredDependencies, declaredDependenciesNode,
|
|
|
956
956
|
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
957
957
|
}));
|
|
958
958
|
}
|
|
959
|
-
function getDependency(node) {
|
|
960
|
-
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);
|
|
959
|
+
function getDependency$1(node) {
|
|
960
|
+
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$1(node.parent);
|
|
961
961
|
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
962
962
|
else return node;
|
|
963
963
|
}
|
|
964
|
-
function markNode(node, optionalChains, result) {
|
|
964
|
+
function markNode$1(node, optionalChains, result) {
|
|
965
965
|
if (optionalChains) {
|
|
966
966
|
if ("optional" in node && node.optional) {
|
|
967
967
|
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
968
968
|
} else optionalChains.set(result, false);
|
|
969
969
|
}
|
|
970
970
|
}
|
|
971
|
-
function analyzePropertyChain(node, optionalChains) {
|
|
971
|
+
function analyzePropertyChain$1(node, optionalChains) {
|
|
972
972
|
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
973
973
|
const result = node.name;
|
|
974
974
|
if (optionalChains) optionalChains.set(result, false);
|
|
975
975
|
return result;
|
|
976
976
|
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
977
|
-
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
978
|
-
markNode(node, optionalChains, result);
|
|
977
|
+
const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
|
|
978
|
+
markNode$1(node, optionalChains, result);
|
|
979
979
|
return result;
|
|
980
980
|
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
981
|
-
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
982
|
-
markNode(node, optionalChains, result);
|
|
981
|
+
const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
|
|
982
|
+
markNode$1(node, optionalChains, result);
|
|
983
983
|
return result;
|
|
984
984
|
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
985
985
|
const expression = node.expression;
|
|
986
986
|
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
987
|
-
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
988
|
-
markNode(expression, optionalChains, result);
|
|
987
|
+
const result = `${analyzePropertyChain$1(expression.object, optionalChains)}.${analyzePropertyChain$1(expression.property, null)}`;
|
|
988
|
+
markNode$1(expression, optionalChains, result);
|
|
989
989
|
return result;
|
|
990
990
|
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
991
991
|
}
|
|
992
|
-
function getNodeWithoutReactNamespace$
|
|
992
|
+
function getNodeWithoutReactNamespace$2(node) {
|
|
993
993
|
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
994
994
|
return node;
|
|
995
995
|
}
|
|
996
|
-
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
997
|
-
const node = getNodeWithoutReactNamespace$
|
|
996
|
+
function getReactiveHookCallbackIndex$1(calleeNode, options) {
|
|
997
|
+
const node = getNodeWithoutReactNamespace$2(calleeNode);
|
|
998
998
|
if (node.type !== "Identifier") return -1;
|
|
999
999
|
switch (node.name) {
|
|
1000
1000
|
case "useEffect":
|
|
@@ -1005,7 +1005,7 @@ function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
|
1005
1005
|
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
1006
1006
|
let name;
|
|
1007
1007
|
try {
|
|
1008
|
-
name = analyzePropertyChain(node, null);
|
|
1008
|
+
name = analyzePropertyChain$1(node, null);
|
|
1009
1009
|
} catch (error) {
|
|
1010
1010
|
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
1011
1011
|
else throw error;
|
|
@@ -1014,20 +1014,20 @@ function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
|
1014
1014
|
} else return -1;
|
|
1015
1015
|
}
|
|
1016
1016
|
}
|
|
1017
|
-
function fastFindReferenceWithParent(start, target) {
|
|
1017
|
+
function fastFindReferenceWithParent$1(start, target) {
|
|
1018
1018
|
const queue = [start];
|
|
1019
1019
|
let item;
|
|
1020
1020
|
while (queue.length) {
|
|
1021
1021
|
item = queue.shift();
|
|
1022
|
-
if (isSameIdentifier(item, target)) return item;
|
|
1023
|
-
if (!isAncestorNodeOf(item, target)) continue;
|
|
1022
|
+
if (isSameIdentifier$1(item, target)) return item;
|
|
1023
|
+
if (!isAncestorNodeOf$1(item, target)) continue;
|
|
1024
1024
|
for (const [key, value] of Object.entries(item)) {
|
|
1025
1025
|
if (key === "parent") continue;
|
|
1026
|
-
if (isNodeLike(value)) {
|
|
1026
|
+
if (isNodeLike$1(value)) {
|
|
1027
1027
|
value.parent = item;
|
|
1028
1028
|
queue.push(value);
|
|
1029
1029
|
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
1030
|
-
if (isNodeLike(val)) {
|
|
1030
|
+
if (isNodeLike$1(val)) {
|
|
1031
1031
|
val.parent = item;
|
|
1032
1032
|
queue.push(val);
|
|
1033
1033
|
}
|
|
@@ -1036,7 +1036,7 @@ function fastFindReferenceWithParent(start, target) {
|
|
|
1036
1036
|
}
|
|
1037
1037
|
return null;
|
|
1038
1038
|
}
|
|
1039
|
-
function joinEnglish(arr) {
|
|
1039
|
+
function joinEnglish$1(arr) {
|
|
1040
1040
|
let s = "";
|
|
1041
1041
|
for (let i = 0; i < arr.length; i++) {
|
|
1042
1042
|
s += arr[i];
|
|
@@ -1046,19 +1046,19 @@ function joinEnglish(arr) {
|
|
|
1046
1046
|
}
|
|
1047
1047
|
return s;
|
|
1048
1048
|
}
|
|
1049
|
-
function isNodeLike(val) {
|
|
1049
|
+
function isNodeLike$1(val) {
|
|
1050
1050
|
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
1051
1051
|
}
|
|
1052
|
-
function isSameIdentifier(a, b) {
|
|
1052
|
+
function isSameIdentifier$1(a, b) {
|
|
1053
1053
|
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];
|
|
1054
1054
|
}
|
|
1055
|
-
function isAncestorNodeOf(a, b) {
|
|
1055
|
+
function isAncestorNodeOf$1(a, b) {
|
|
1056
1056
|
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
1057
1057
|
}
|
|
1058
|
-
function isUseEffectEventIdentifier$
|
|
1058
|
+
function isUseEffectEventIdentifier$2(node) {
|
|
1059
1059
|
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
1060
1060
|
}
|
|
1061
|
-
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
1061
|
+
function getUnknownDependenciesMessage$1(reactiveHookName) {
|
|
1062
1062
|
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
1063
1063
|
}
|
|
1064
1064
|
// src/rules/globals/helpers.ts
|
|
@@ -2684,16 +2684,6 @@ const KNOWN_CALLBACK_POSITIONS = /* @__PURE__ */ new Map([
|
|
|
2684
2684
|
["from", 1],
|
|
2685
2685
|
["map", 0]
|
|
2686
2686
|
]);
|
|
2687
|
-
function getReturnStatements$1(node) {
|
|
2688
|
-
const stmts = [];
|
|
2689
|
-
const boundary = Check.isFunction(node) ? node : Traverse.findParent(node, Check.isFunction);
|
|
2690
|
-
simpleTraverse(node, { enter(node) {
|
|
2691
|
-
if (node.type !== AST_NODE_TYPES.ReturnStatement) return;
|
|
2692
|
-
if (Traverse.hasParent(node, Check.isFunction, (n) => n === boundary)) return;
|
|
2693
|
-
stmts.push(node);
|
|
2694
|
-
} });
|
|
2695
|
-
return stmts;
|
|
2696
|
-
}
|
|
2697
2687
|
var no_missing_key_default = createRule({
|
|
2698
2688
|
meta: {
|
|
2699
2689
|
type: "problem",
|
|
@@ -2741,8 +2731,7 @@ function create$24(context) {
|
|
|
2741
2731
|
}
|
|
2742
2732
|
}
|
|
2743
2733
|
function visitIteratorCallback(node) {
|
|
2744
|
-
|
|
2745
|
-
return getReturnStatements$1(node.body).flatMap((stmt) => stmt.argument == null ? [] : visitItemExpression(stmt.argument));
|
|
2734
|
+
return Collect.getReturnExpressions(node).flatMap(visitItemExpression);
|
|
2746
2735
|
}
|
|
2747
2736
|
return {
|
|
2748
2737
|
ArrayExpression(node) {
|
|
@@ -6067,7 +6056,7 @@ function isInsideTryCatch(node) {
|
|
|
6067
6056
|
}
|
|
6068
6057
|
return false;
|
|
6069
6058
|
}
|
|
6070
|
-
function getNodeWithoutReactNamespace(node) {
|
|
6059
|
+
function getNodeWithoutReactNamespace$1(node) {
|
|
6071
6060
|
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
6072
6061
|
return node;
|
|
6073
6062
|
}
|
|
@@ -6076,7 +6065,7 @@ function isEffectIdentifier(node, additionalHooks) {
|
|
|
6076
6065
|
if (additionalHooks && node.type === "Identifier") return additionalHooks.test(node.name);
|
|
6077
6066
|
return false;
|
|
6078
6067
|
}
|
|
6079
|
-
function isUseEffectEventIdentifier(node) {
|
|
6068
|
+
function isUseEffectEventIdentifier$1(node) {
|
|
6080
6069
|
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
6081
6070
|
}
|
|
6082
6071
|
function useEffectEventError(fn, called) {
|
|
@@ -6086,7 +6075,7 @@ function useEffectEventError(fn, called) {
|
|
|
6086
6075
|
function isUseIdentifier(node) {
|
|
6087
6076
|
return isReactFunction(node, "use");
|
|
6088
6077
|
}
|
|
6089
|
-
const rule = {
|
|
6078
|
+
const rule$1 = {
|
|
6090
6079
|
meta: {
|
|
6091
6080
|
type: "problem",
|
|
6092
6081
|
docs: {
|
|
@@ -6111,7 +6100,7 @@ const rule = {
|
|
|
6111
6100
|
function recordAllUseEffectEventFunctions(scope) {
|
|
6112
6101
|
for (const reference of scope.references) {
|
|
6113
6102
|
const parent = reference.identifier.parent;
|
|
6114
|
-
if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier(parent.init.callee)) {
|
|
6103
|
+
if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier$1(parent.init.callee)) {
|
|
6115
6104
|
if (reference.resolved === null) throw new Error("Unexpected null reference.resolved");
|
|
6116
6105
|
for (const ref of reference.resolved.references) if (ref !== reference) useEffectEventFunctions.add(ref.identifier);
|
|
6117
6106
|
}
|
|
@@ -6290,9 +6279,9 @@ const rule = {
|
|
|
6290
6279
|
}
|
|
6291
6280
|
reactHooks.push(callee);
|
|
6292
6281
|
}
|
|
6293
|
-
const nodeWithoutNamespace = getNodeWithoutReactNamespace(node.callee);
|
|
6294
|
-
if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
|
|
6295
|
-
if (isUseEffectEventIdentifier(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
|
|
6282
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(node.callee);
|
|
6283
|
+
if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier$1(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
|
|
6284
|
+
if (isUseEffectEventIdentifier$1(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
|
|
6296
6285
|
const message = useEffectEventError(null, false);
|
|
6297
6286
|
context.report({
|
|
6298
6287
|
node,
|
|
@@ -6385,95 +6374,11 @@ function createFactCollector$3(additionalStateHooks, additionalEffectHooks) {
|
|
|
6385
6374
|
};
|
|
6386
6375
|
}
|
|
6387
6376
|
// src/rules/set-state-in-effect/helpers.ts
|
|
6388
|
-
const IDENTIFIER_VISITOR_KEYS = {
|
|
6389
|
-
[AST_NODE_TYPES.ArrayExpression]: ["elements"],
|
|
6390
|
-
[AST_NODE_TYPES.ArrayPattern]: ["elements"],
|
|
6391
|
-
[AST_NODE_TYPES.AssignmentExpression]: ["left", "right"],
|
|
6392
|
-
[AST_NODE_TYPES.AssignmentPattern]: ["left", "right"],
|
|
6393
|
-
[AST_NODE_TYPES.AwaitExpression]: ["argument"],
|
|
6394
|
-
[AST_NODE_TYPES.BinaryExpression]: ["left", "right"],
|
|
6395
|
-
[AST_NODE_TYPES.CallExpression]: ["callee", "arguments"],
|
|
6396
|
-
[AST_NODE_TYPES.ChainExpression]: ["expression"],
|
|
6397
|
-
[AST_NODE_TYPES.ConditionalExpression]: [
|
|
6398
|
-
"test",
|
|
6399
|
-
"consequent",
|
|
6400
|
-
"alternate"
|
|
6401
|
-
],
|
|
6402
|
-
[AST_NODE_TYPES.ForInStatement]: ["left", "right"],
|
|
6403
|
-
[AST_NODE_TYPES.ForOfStatement]: ["left", "right"],
|
|
6404
|
-
[AST_NODE_TYPES.ImportExpression]: ["source"],
|
|
6405
|
-
[AST_NODE_TYPES.LogicalExpression]: ["left", "right"],
|
|
6406
|
-
[AST_NODE_TYPES.MemberExpression]: ["object", "property"],
|
|
6407
|
-
[AST_NODE_TYPES.NewExpression]: ["callee", "arguments"],
|
|
6408
|
-
[AST_NODE_TYPES.ObjectExpression]: ["properties"],
|
|
6409
|
-
[AST_NODE_TYPES.ObjectPattern]: ["properties"],
|
|
6410
|
-
[AST_NODE_TYPES.Property]: ["value"],
|
|
6411
|
-
[AST_NODE_TYPES.SequenceExpression]: ["expressions"],
|
|
6412
|
-
[AST_NODE_TYPES.SpreadElement]: ["argument"],
|
|
6413
|
-
[AST_NODE_TYPES.TaggedTemplateExpression]: ["tag", "quasi"],
|
|
6414
|
-
[AST_NODE_TYPES.TemplateLiteral]: ["expressions"],
|
|
6415
|
-
[AST_NODE_TYPES.TSAsExpression]: ["expression"],
|
|
6416
|
-
[AST_NODE_TYPES.TSInstantiationExpression]: ["expression"],
|
|
6417
|
-
[AST_NODE_TYPES.TSNonNullExpression]: ["expression"],
|
|
6418
|
-
[AST_NODE_TYPES.TSSatisfiesExpression]: ["expression"],
|
|
6419
|
-
[AST_NODE_TYPES.TSTypeAssertion]: ["expression"],
|
|
6420
|
-
[AST_NODE_TYPES.UnaryExpression]: ["argument"],
|
|
6421
|
-
[AST_NODE_TYPES.UpdateExpression]: ["argument"],
|
|
6422
|
-
[AST_NODE_TYPES.YieldExpression]: ["argument"]
|
|
6423
|
-
};
|
|
6424
|
-
function getIdentifiers(node) {
|
|
6425
|
-
const identifiers = [];
|
|
6426
|
-
simpleTraverse(node, {
|
|
6427
|
-
enter(node, parent) {
|
|
6428
|
-
if (node.type !== AST_NODE_TYPES.Identifier) return;
|
|
6429
|
-
if (parent?.type === AST_NODE_TYPES.MemberExpression && !parent.computed && parent.property === node) return;
|
|
6430
|
-
identifiers.push(node);
|
|
6431
|
-
},
|
|
6432
|
-
visitorKeys: IDENTIFIER_VISITOR_KEYS
|
|
6433
|
-
});
|
|
6434
|
-
return identifiers;
|
|
6435
|
-
}
|
|
6436
6377
|
function isTerminatingStatement(node) {
|
|
6437
6378
|
if (node.type === AST_NODE_TYPES.ReturnStatement || node.type === AST_NODE_TYPES.ThrowStatement) return true;
|
|
6438
6379
|
if (node.type === AST_NODE_TYPES.BlockStatement) return node.body.some(isTerminatingStatement);
|
|
6439
6380
|
return false;
|
|
6440
6381
|
}
|
|
6441
|
-
function getReturnExpressions(fn) {
|
|
6442
|
-
if (fn.type === AST_NODE_TYPES.ArrowFunctionExpression && fn.body.type !== AST_NODE_TYPES.BlockStatement) return [fn.body];
|
|
6443
|
-
const returns = [];
|
|
6444
|
-
const visitStatements = (statements) => {
|
|
6445
|
-
for (const statement of statements) switch (statement.type) {
|
|
6446
|
-
case AST_NODE_TYPES.ReturnStatement:
|
|
6447
|
-
if (statement.argument != null) returns.push(statement.argument);
|
|
6448
|
-
break;
|
|
6449
|
-
case AST_NODE_TYPES.BlockStatement:
|
|
6450
|
-
visitStatements(statement.body);
|
|
6451
|
-
break;
|
|
6452
|
-
case AST_NODE_TYPES.IfStatement:
|
|
6453
|
-
visitStatements([statement.consequent]);
|
|
6454
|
-
if (statement.alternate != null) visitStatements([statement.alternate]);
|
|
6455
|
-
break;
|
|
6456
|
-
case AST_NODE_TYPES.SwitchStatement:
|
|
6457
|
-
for (const switchCase of statement.cases) visitStatements(switchCase.consequent);
|
|
6458
|
-
break;
|
|
6459
|
-
case AST_NODE_TYPES.TryStatement:
|
|
6460
|
-
visitStatements([statement.block]);
|
|
6461
|
-
if (statement.handler != null) visitStatements([statement.handler.body]);
|
|
6462
|
-
if (statement.finalizer != null) visitStatements([statement.finalizer]);
|
|
6463
|
-
break;
|
|
6464
|
-
case AST_NODE_TYPES.DoWhileStatement:
|
|
6465
|
-
case AST_NODE_TYPES.ForInStatement:
|
|
6466
|
-
case AST_NODE_TYPES.ForOfStatement:
|
|
6467
|
-
case AST_NODE_TYPES.ForStatement:
|
|
6468
|
-
case AST_NODE_TYPES.LabeledStatement:
|
|
6469
|
-
case AST_NODE_TYPES.WhileStatement:
|
|
6470
|
-
case AST_NODE_TYPES.WithStatement: visitStatements([statement.body]);
|
|
6471
|
-
}
|
|
6472
|
-
};
|
|
6473
|
-
if (fn.body.type !== AST_NODE_TYPES.BlockStatement) return [];
|
|
6474
|
-
visitStatements(fn.body.body);
|
|
6475
|
-
return returns;
|
|
6476
|
-
}
|
|
6477
6382
|
function getConditionalBranch(node) {
|
|
6478
6383
|
let child = node;
|
|
6479
6384
|
let current = node.parent;
|
|
@@ -6531,7 +6436,7 @@ const EMPTY_FACTS = {
|
|
|
6531
6436
|
};
|
|
6532
6437
|
function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
6533
6438
|
const { additionalRefHooks, additionalStateHooks } = getSettingsFromContext(context);
|
|
6534
|
-
const getReturnExpressions
|
|
6439
|
+
const getReturnExpressions = memoize(Collect.getReturnExpressions);
|
|
6535
6440
|
function isUseRefCall(node) {
|
|
6536
6441
|
return node.type === AST_NODE_TYPES.CallExpression && core.isUseRefLikeCall(node, additionalRefHooks);
|
|
6537
6442
|
}
|
|
@@ -6617,7 +6522,7 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6617
6522
|
const targets = [];
|
|
6618
6523
|
for (const factory of factories) {
|
|
6619
6524
|
if (factory.kind !== "function" || factory.node.async) continue;
|
|
6620
|
-
for (const returnExpression of getReturnExpressions
|
|
6525
|
+
for (const returnExpression of getReturnExpressions(factory.node)) targets.push(...resolveValues(returnExpression, new Set(seen)));
|
|
6621
6526
|
}
|
|
6622
6527
|
return uniqueTargets(targets);
|
|
6623
6528
|
}
|
|
@@ -6709,7 +6614,7 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6709
6614
|
if (seen.has(key)) continue;
|
|
6710
6615
|
seen.add(key);
|
|
6711
6616
|
const childRefParams = getRefDerivedParams(expression, target.node, refParams);
|
|
6712
|
-
if (getReturnExpressions
|
|
6617
|
+
if (getReturnExpressions(target.node).some((r) => isRefValue(r, childRefParams, seen, mode))) return true;
|
|
6713
6618
|
}
|
|
6714
6619
|
return isRefValue(expression.callee, refParams, seen, mode) || expression.arguments.some((a) => isRefValue(a, refParams, seen, mode));
|
|
6715
6620
|
case AST_NODE_TYPES.BinaryExpression:
|
|
@@ -6737,7 +6642,7 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6737
6642
|
return context.sourceCode.getScope(expression.body).references.some((r) => isRefValue(r.identifier, refParams, seen, "argument"));
|
|
6738
6643
|
}
|
|
6739
6644
|
function isRefInExpression(node, refParams) {
|
|
6740
|
-
return getIdentifiers(node).some((id) => isInitializedFromRef(id, refParams));
|
|
6645
|
+
return Collect.getIdentifiers(node).some((id) => isInitializedFromRef(id, refParams));
|
|
6741
6646
|
}
|
|
6742
6647
|
function isRefGatedContext(node, refParams) {
|
|
6743
6648
|
let child = node;
|
|
@@ -7166,139 +7071,1128 @@ function create$3(context) {
|
|
|
7166
7071
|
}
|
|
7167
7072
|
} });
|
|
7168
7073
|
}
|
|
7169
|
-
// src/rules/
|
|
7170
|
-
function
|
|
7171
|
-
const
|
|
7172
|
-
|
|
7173
|
-
|
|
7174
|
-
|
|
7175
|
-
|
|
7176
|
-
|
|
7177
|
-
|
|
7074
|
+
// src/rules/unstable-exhaustive-deps/lib.ts
|
|
7075
|
+
function getHookConfigs(hooks = []) {
|
|
7076
|
+
const reactive = /* @__PURE__ */ new Map();
|
|
7077
|
+
const stable = /* @__PURE__ */ new Map();
|
|
7078
|
+
for (const { name, closureIndex, dependenciesIndex, stableResult } of hooks) {
|
|
7079
|
+
if (closureIndex != null && dependenciesIndex != null && closureIndex !== dependenciesIndex) reactive.set(name, {
|
|
7080
|
+
closureIndex,
|
|
7081
|
+
dependenciesIndex
|
|
7082
|
+
});
|
|
7083
|
+
if (stableResult === true) stable.set(name, true);
|
|
7084
|
+
else if (typeof stableResult === "number") stable.set(name, /* @__PURE__ */ new Set([stableResult]));
|
|
7085
|
+
else if (Array.isArray(stableResult)) stable.set(name, new Set(stableResult));
|
|
7178
7086
|
}
|
|
7087
|
+
return {
|
|
7088
|
+
reactive,
|
|
7089
|
+
stable
|
|
7090
|
+
};
|
|
7179
7091
|
}
|
|
7180
|
-
|
|
7092
|
+
function getReactiveHookConfig(node, configs) {
|
|
7093
|
+
if (configs.reactive.size === 0) return null;
|
|
7094
|
+
const name = Extract.getCalleeName(node);
|
|
7095
|
+
if (name == null) return null;
|
|
7096
|
+
const config = configs.reactive.get(name);
|
|
7097
|
+
if (config == null) return null;
|
|
7098
|
+
return {
|
|
7099
|
+
name,
|
|
7100
|
+
...config
|
|
7101
|
+
};
|
|
7102
|
+
}
|
|
7103
|
+
function isConfiguredStableHookValue(variable, configs) {
|
|
7104
|
+
if (configs.stable.size === 0) return false;
|
|
7105
|
+
let matchedNode = null;
|
|
7106
|
+
let stableResult = null;
|
|
7107
|
+
let initializerCount = 0;
|
|
7108
|
+
for (const def of variable.defs) {
|
|
7109
|
+
if (def.type !== DefinitionType.Variable || def.node.init == null) continue;
|
|
7110
|
+
initializerCount++;
|
|
7111
|
+
const init = Extract.unwrap(def.node.init);
|
|
7112
|
+
if (init.type !== AST_NODE_TYPES.CallExpression) continue;
|
|
7113
|
+
const name = Extract.getCalleeName(init);
|
|
7114
|
+
if (name == null) continue;
|
|
7115
|
+
const config = configs.stable.get(name);
|
|
7116
|
+
if (config == null) continue;
|
|
7117
|
+
if (matchedNode != null) return false;
|
|
7118
|
+
matchedNode = def.node;
|
|
7119
|
+
stableResult = config;
|
|
7120
|
+
}
|
|
7121
|
+
if (initializerCount !== 1) return false;
|
|
7122
|
+
if (matchedNode == null || stableResult == null) return false;
|
|
7123
|
+
if (variable.references.some((reference) => reference.isWrite() && reference.init !== true)) return false;
|
|
7124
|
+
const { id } = matchedNode;
|
|
7125
|
+
if (stableResult === true) return id.type === AST_NODE_TYPES.Identifier;
|
|
7126
|
+
if (id.type !== AST_NODE_TYPES.ArrayPattern) return false;
|
|
7127
|
+
const index = id.elements.findIndex((element) => {
|
|
7128
|
+
if (element == null) return false;
|
|
7129
|
+
const binding = element.type === AST_NODE_TYPES.AssignmentPattern ? element.left : element;
|
|
7130
|
+
return variable.identifiers.some((identifier) => identifier === binding);
|
|
7131
|
+
});
|
|
7132
|
+
return index !== -1 && stableResult.has(index);
|
|
7133
|
+
}
|
|
7134
|
+
// src/rules/unstable-exhaustive-deps/unstable-exhaustive-deps.ts
|
|
7135
|
+
const rule = {
|
|
7181
7136
|
meta: {
|
|
7182
|
-
type: "
|
|
7183
|
-
docs: {
|
|
7184
|
-
|
|
7185
|
-
|
|
7186
|
-
with: "Do not use 'with' statements inside components or hooks. 'with' changes scope dynamically and is not supported by React Compiler."
|
|
7187
|
-
},
|
|
7188
|
-
schema: []
|
|
7189
|
-
},
|
|
7190
|
-
name: "unsupported-syntax",
|
|
7191
|
-
create: create$2
|
|
7192
|
-
});
|
|
7193
|
-
function create$2(context) {
|
|
7194
|
-
const hc = core.getHookCollector(context);
|
|
7195
|
-
const fc = core.getFunctionComponentCollector(context);
|
|
7196
|
-
const evalCalls = [];
|
|
7197
|
-
const withStmts = [];
|
|
7198
|
-
return merge(hc.visitor, fc.visitor, {
|
|
7199
|
-
CallExpression(node) {
|
|
7200
|
-
if (!isEvalCall(node)) return;
|
|
7201
|
-
const func = Traverse.findParent(node, Check.isFunction);
|
|
7202
|
-
if (func == null) return;
|
|
7203
|
-
evalCalls.push({
|
|
7204
|
-
func,
|
|
7205
|
-
node
|
|
7206
|
-
});
|
|
7207
|
-
},
|
|
7208
|
-
WithStatement(node) {
|
|
7209
|
-
const func = Traverse.findParent(node, Check.isFunction);
|
|
7210
|
-
if (func == null) return;
|
|
7211
|
-
withStmts.push({
|
|
7212
|
-
func,
|
|
7213
|
-
node
|
|
7214
|
-
});
|
|
7137
|
+
type: "suggestion",
|
|
7138
|
+
docs: {
|
|
7139
|
+
description: "Verifies the list of dependencies for Hooks like 'useEffect' and similar, with support for custom Hooks and stable Hook results.",
|
|
7140
|
+
url: "https://eslint-react.xyz/docs/rules/unstable-exhaustive-deps"
|
|
7215
7141
|
},
|
|
7216
|
-
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
7220
|
-
|
|
7221
|
-
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7142
|
+
fixable: "code",
|
|
7143
|
+
hasSuggestions: true,
|
|
7144
|
+
schema: [{
|
|
7145
|
+
type: "object",
|
|
7146
|
+
additionalProperties: false,
|
|
7147
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: false,
|
|
7148
|
+
properties: {
|
|
7149
|
+
additionalHooks: { type: "string" },
|
|
7150
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: { type: "boolean" },
|
|
7151
|
+
experimental_autoDependenciesHooks: {
|
|
7152
|
+
type: "array",
|
|
7153
|
+
items: { type: "string" }
|
|
7154
|
+
},
|
|
7155
|
+
hooks: {
|
|
7156
|
+
type: "array",
|
|
7157
|
+
items: {
|
|
7158
|
+
type: "object",
|
|
7159
|
+
additionalProperties: false,
|
|
7160
|
+
dependencies: {
|
|
7161
|
+
closureIndex: ["dependenciesIndex"],
|
|
7162
|
+
dependenciesIndex: ["closureIndex"]
|
|
7163
|
+
},
|
|
7164
|
+
properties: {
|
|
7165
|
+
name: {
|
|
7166
|
+
type: "string",
|
|
7167
|
+
minLength: 1
|
|
7168
|
+
},
|
|
7169
|
+
closureIndex: {
|
|
7170
|
+
type: "integer",
|
|
7171
|
+
minimum: 0
|
|
7172
|
+
},
|
|
7173
|
+
dependenciesIndex: {
|
|
7174
|
+
type: "integer",
|
|
7175
|
+
minimum: 0
|
|
7176
|
+
},
|
|
7177
|
+
stableResult: { oneOf: [
|
|
7178
|
+
{ type: "boolean" },
|
|
7179
|
+
{
|
|
7180
|
+
type: "integer",
|
|
7181
|
+
minimum: 0
|
|
7182
|
+
},
|
|
7183
|
+
{
|
|
7184
|
+
type: "array",
|
|
7185
|
+
items: {
|
|
7186
|
+
type: "integer",
|
|
7187
|
+
minimum: 0
|
|
7188
|
+
},
|
|
7189
|
+
minItems: 1
|
|
7190
|
+
}
|
|
7191
|
+
] }
|
|
7192
|
+
},
|
|
7193
|
+
required: ["name"]
|
|
7194
|
+
}
|
|
7195
|
+
},
|
|
7196
|
+
requireExplicitEffectDeps: { type: "boolean" }
|
|
7226
7197
|
}
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
7231
|
-
|
|
7232
|
-
|
|
7198
|
+
}]
|
|
7199
|
+
},
|
|
7200
|
+
create(context) {
|
|
7201
|
+
const rawOptions = context.options && context.options[0];
|
|
7202
|
+
const additionalHooks = rawOptions && rawOptions.additionalHooks ? new RegExp(rawOptions.additionalHooks) : getSettingsFromContext(context).additionalEffectHooks;
|
|
7203
|
+
const enableDangerousAutofixThisMayCauseInfiniteLoops = rawOptions && rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops || false;
|
|
7204
|
+
const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) ? rawOptions.experimental_autoDependenciesHooks : [];
|
|
7205
|
+
const requireExplicitEffectDeps = rawOptions && rawOptions.requireExplicitEffectDeps || false;
|
|
7206
|
+
const options = {
|
|
7207
|
+
additionalHooks,
|
|
7208
|
+
experimental_autoDependenciesHooks,
|
|
7209
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops,
|
|
7210
|
+
hooks: getHookConfigs(rawOptions && rawOptions.hooks),
|
|
7211
|
+
requireExplicitEffectDeps
|
|
7212
|
+
};
|
|
7213
|
+
function reportProblem(problem) {
|
|
7214
|
+
if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
|
|
7215
|
+
if (Array.isArray(problem.suggest) && problem.suggest.length > 0 && problem.suggest[0]) problem.fix = problem.suggest[0].fix;
|
|
7233
7216
|
}
|
|
7217
|
+
context.report(problem);
|
|
7234
7218
|
}
|
|
7235
|
-
|
|
7236
|
-
|
|
7237
|
-
|
|
7238
|
-
|
|
7239
|
-
|
|
7240
|
-
|
|
7241
|
-
|
|
7242
|
-
}
|
|
7243
|
-
|
|
7244
|
-
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7250
|
-
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
7256
|
-
|
|
7257
|
-
|
|
7258
|
-
function pushWrite(node, target) {
|
|
7259
|
-
if (!Check.isIdentifier(target)) return;
|
|
7260
|
-
if (Traverse.hasParent(node, Check.isFunction, (n) => n === callback)) return;
|
|
7261
|
-
writes.push({
|
|
7262
|
-
node,
|
|
7263
|
-
target
|
|
7264
|
-
});
|
|
7219
|
+
const getSourceCode = typeof context.getSourceCode === "function" ? () => {
|
|
7220
|
+
return context.getSourceCode();
|
|
7221
|
+
} : () => {
|
|
7222
|
+
return context.sourceCode;
|
|
7223
|
+
};
|
|
7224
|
+
const getScope = typeof context.getScope === "function" ? () => {
|
|
7225
|
+
return context.getScope();
|
|
7226
|
+
} : (node) => {
|
|
7227
|
+
return context.sourceCode.getScope(node);
|
|
7228
|
+
};
|
|
7229
|
+
const scopeManager = getSourceCode().scopeManager;
|
|
7230
|
+
const setStateCallSites = /* @__PURE__ */ new WeakMap();
|
|
7231
|
+
const stateVariables = /* @__PURE__ */ new WeakSet();
|
|
7232
|
+
const stableKnownValueCache = /* @__PURE__ */ new WeakMap();
|
|
7233
|
+
const functionWithoutCapturedValueCache = /* @__PURE__ */ new WeakMap();
|
|
7234
|
+
const useEffectEventVariables = /* @__PURE__ */ new WeakSet();
|
|
7235
|
+
function memoizeWithWeakMap(fn, map) {
|
|
7236
|
+
return function(arg) {
|
|
7237
|
+
if (map.has(arg)) return map.get(arg);
|
|
7238
|
+
const result = fn(arg);
|
|
7239
|
+
map.set(arg, result);
|
|
7240
|
+
return result;
|
|
7241
|
+
};
|
|
7265
7242
|
}
|
|
7266
|
-
|
|
7267
|
-
|
|
7268
|
-
case AST_NODE_TYPES.AssignmentExpression:
|
|
7269
|
-
for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
|
|
7270
|
-
return;
|
|
7271
|
-
case AST_NODE_TYPES.ForInStatement:
|
|
7272
|
-
case AST_NODE_TYPES.ForOfStatement:
|
|
7273
|
-
if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
|
|
7274
|
-
for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
|
|
7275
|
-
return;
|
|
7276
|
-
}
|
|
7277
|
-
} });
|
|
7278
|
-
return writes;
|
|
7279
|
-
}
|
|
7280
|
-
return {
|
|
7281
|
-
facts,
|
|
7282
|
-
visitor: { CallExpression(node) {
|
|
7283
|
-
if (!isUseMemoCall(node)) return;
|
|
7284
|
-
const callbackArg = node.arguments[0] ?? null;
|
|
7285
|
-
const callback = callbackArg != null ? Extract.unwrap(callbackArg) : null;
|
|
7286
|
-
const callbackFunction = callback != null && Check.isFunction(callback) ? callback : null;
|
|
7287
|
-
facts.calls.push({
|
|
7288
|
-
callback: callbackFunction,
|
|
7289
|
-
callbackArg,
|
|
7290
|
-
isResultUsed: isResultUsed(node),
|
|
7243
|
+
function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, callExpression, dependenciesIndex) {
|
|
7244
|
+
if (isEffect && node.async) reportProblem({
|
|
7291
7245
|
node,
|
|
7292
|
-
|
|
7293
|
-
writes: callbackFunction != null ? collectWrites(callbackFunction) : []
|
|
7246
|
+
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"
|
|
7294
7247
|
});
|
|
7295
|
-
|
|
7296
|
-
|
|
7297
|
-
|
|
7298
|
-
|
|
7299
|
-
|
|
7300
|
-
|
|
7301
|
-
|
|
7248
|
+
const scope = scopeManager.acquire(node);
|
|
7249
|
+
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.");
|
|
7250
|
+
const pureScopes = /* @__PURE__ */ new Set();
|
|
7251
|
+
let componentScope = null;
|
|
7252
|
+
{
|
|
7253
|
+
let currentScope = scope.upper;
|
|
7254
|
+
while (currentScope) {
|
|
7255
|
+
pureScopes.add(currentScope);
|
|
7256
|
+
if (currentScope.type === "function" || currentScope.type === "hook" || currentScope.type === "component") break;
|
|
7257
|
+
currentScope = currentScope.upper;
|
|
7258
|
+
}
|
|
7259
|
+
if (!currentScope) return;
|
|
7260
|
+
componentScope = currentScope;
|
|
7261
|
+
}
|
|
7262
|
+
const isArray = Array.isArray;
|
|
7263
|
+
function isStableKnownHookValue(resolved) {
|
|
7264
|
+
if (!isArray(resolved.defs)) return false;
|
|
7265
|
+
const initializers = resolved.defs.filter((definition) => definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.init != null);
|
|
7266
|
+
if (initializers.length !== 1) return false;
|
|
7267
|
+
const def = initializers[0];
|
|
7268
|
+
const defNode = def.node;
|
|
7269
|
+
if (defNode.type !== "VariableDeclarator") return false;
|
|
7270
|
+
let init = defNode.init;
|
|
7271
|
+
if (init == null) return false;
|
|
7272
|
+
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
7273
|
+
let declaration = defNode.parent;
|
|
7274
|
+
if (declaration == null && componentScope != null) {
|
|
7275
|
+
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
7276
|
+
declaration = def.node.parent;
|
|
7277
|
+
if (declaration == null) return false;
|
|
7278
|
+
}
|
|
7279
|
+
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;
|
|
7280
|
+
if (init.type !== "CallExpression") return false;
|
|
7281
|
+
let callee = init.callee;
|
|
7282
|
+
if (callee.type === "MemberExpression" && "name" in callee.object && callee.object.name === "React" && callee.property != null && !callee.computed) callee = callee.property;
|
|
7283
|
+
if (callee.type !== "Identifier") return false;
|
|
7284
|
+
const id = def.node.id;
|
|
7285
|
+
const { name } = callee;
|
|
7286
|
+
if (name === "useRef" && id.type === "Identifier") return true;
|
|
7287
|
+
else if (isUseEffectEventIdentifier(callee) && id.type === "Identifier") {
|
|
7288
|
+
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
7289
|
+
return true;
|
|
7290
|
+
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
7291
|
+
const isActionState = name === "useActionState";
|
|
7292
|
+
if (id.type === "ArrayPattern" && (isActionState ? id.elements.length >= 2 : id.elements.length === 2) && isArray(resolved.identifiers)) {
|
|
7293
|
+
const firstElement = id.elements[0]?.type === "AssignmentPattern" ? id.elements[0].left : id.elements[0];
|
|
7294
|
+
const secondElement = id.elements[1]?.type === "AssignmentPattern" ? id.elements[1].left : id.elements[1];
|
|
7295
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) {
|
|
7296
|
+
if (name === "useState") {
|
|
7297
|
+
const references = resolved.references;
|
|
7298
|
+
for (const reference of references) {
|
|
7299
|
+
if (reference.isWrite() && reference.init !== true) return false;
|
|
7300
|
+
setStateCallSites.set(reference.identifier, firstElement);
|
|
7301
|
+
}
|
|
7302
|
+
}
|
|
7303
|
+
return true;
|
|
7304
|
+
} else if (resolved.identifiers.some((identifier) => identifier === firstElement)) {
|
|
7305
|
+
if (name === "useState") {
|
|
7306
|
+
const references = resolved.references;
|
|
7307
|
+
for (const reference of references) stateVariables.add(reference.identifier);
|
|
7308
|
+
}
|
|
7309
|
+
return false;
|
|
7310
|
+
}
|
|
7311
|
+
}
|
|
7312
|
+
} else if (name === "useTransition") {
|
|
7313
|
+
if (id.type === "ArrayPattern" && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
|
|
7314
|
+
const secondElement = id.elements[1]?.type === "AssignmentPattern" ? id.elements[1].left : id.elements[1];
|
|
7315
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) return true;
|
|
7316
|
+
}
|
|
7317
|
+
}
|
|
7318
|
+
return false;
|
|
7319
|
+
}
|
|
7320
|
+
function isFunctionWithoutCapturedValues(resolved) {
|
|
7321
|
+
if (!isArray(resolved.defs)) return false;
|
|
7322
|
+
const def = resolved.defs[0];
|
|
7323
|
+
if (def == null) return false;
|
|
7324
|
+
if (def.node == null || def.node.id == null) return false;
|
|
7325
|
+
const fnNode = def.node;
|
|
7326
|
+
const childScopes = componentScope?.childScopes || [];
|
|
7327
|
+
let fnScope = null;
|
|
7328
|
+
for (const childScope of childScopes) {
|
|
7329
|
+
const childScopeBlock = childScope.block;
|
|
7330
|
+
if (fnNode.type === "FunctionDeclaration" && childScopeBlock === fnNode || fnNode.type === "VariableDeclarator" && childScopeBlock.parent === fnNode) {
|
|
7331
|
+
fnScope = childScope;
|
|
7332
|
+
break;
|
|
7333
|
+
}
|
|
7334
|
+
}
|
|
7335
|
+
if (fnScope == null) return false;
|
|
7336
|
+
for (const ref of fnScope.through) {
|
|
7337
|
+
if (ref.resolved == null) continue;
|
|
7338
|
+
if (pureScopes.has(ref.resolved.scope) && !memoizedIsStableKnownHookValue(ref.resolved)) return false;
|
|
7339
|
+
}
|
|
7340
|
+
return true;
|
|
7341
|
+
}
|
|
7342
|
+
const memoizedIsStableKnownHookValue = memoizeWithWeakMap((resolved) => isStableKnownHookValue(resolved) || isConfiguredStableHookValue(resolved, options.hooks), stableKnownValueCache);
|
|
7343
|
+
const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache);
|
|
7344
|
+
const currentRefsInEffectCleanup = /* @__PURE__ */ new Map();
|
|
7345
|
+
function isInsideEffectCleanup(reference) {
|
|
7346
|
+
let curScope = reference.from;
|
|
7347
|
+
let isInReturnedFunction = false;
|
|
7348
|
+
while (curScope != null && curScope.block !== node) {
|
|
7349
|
+
if (curScope.type === "function") isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === "ReturnStatement";
|
|
7350
|
+
curScope = curScope.upper;
|
|
7351
|
+
}
|
|
7352
|
+
return isInReturnedFunction;
|
|
7353
|
+
}
|
|
7354
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
7355
|
+
const optionalChains = /* @__PURE__ */ new Map();
|
|
7356
|
+
gatherDependenciesRecursively(scope);
|
|
7357
|
+
function gatherDependenciesRecursively(currentScope) {
|
|
7358
|
+
for (const reference of currentScope.references) {
|
|
7359
|
+
if (!reference.resolved) continue;
|
|
7360
|
+
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
7361
|
+
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
7362
|
+
if (referenceNode == null) continue;
|
|
7363
|
+
const dependencyNode = getDependency(referenceNode);
|
|
7364
|
+
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
7365
|
+
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, {
|
|
7366
|
+
reference,
|
|
7367
|
+
dependencyNode
|
|
7368
|
+
});
|
|
7369
|
+
if (dependencyNode.parent?.type === "TSTypeQuery" || dependencyNode.parent?.type === "TSTypeReference") continue;
|
|
7370
|
+
const def = reference.resolved.defs[0];
|
|
7371
|
+
if (def == null) continue;
|
|
7372
|
+
if (def.node != null && def.node.init === node.parent) continue;
|
|
7373
|
+
if (def.type === "TypeParameter" || dependencyNode.parent?.type === "GenericTypeAnnotation") continue;
|
|
7374
|
+
if (!dependencies.has(dependency)) {
|
|
7375
|
+
const resolved = reference.resolved;
|
|
7376
|
+
const isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
|
|
7377
|
+
dependencies.set(dependency, {
|
|
7378
|
+
isStable,
|
|
7379
|
+
references: [reference]
|
|
7380
|
+
});
|
|
7381
|
+
} else dependencies.get(dependency)?.references.push(reference);
|
|
7382
|
+
}
|
|
7383
|
+
for (const childScope of currentScope.childScopes) gatherDependenciesRecursively(childScope);
|
|
7384
|
+
}
|
|
7385
|
+
currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => {
|
|
7386
|
+
const references = reference.resolved?.references || [];
|
|
7387
|
+
let foundCurrentAssignment = false;
|
|
7388
|
+
for (const ref of references) {
|
|
7389
|
+
const { identifier } = ref;
|
|
7390
|
+
const { parent } = identifier;
|
|
7391
|
+
if (parent != null && parent.type === "MemberExpression" && !parent.computed && parent.property.type === "Identifier" && parent.property.name === "current" && parent.parent?.type === "AssignmentExpression" && parent.parent.left === parent) {
|
|
7392
|
+
foundCurrentAssignment = true;
|
|
7393
|
+
break;
|
|
7394
|
+
}
|
|
7395
|
+
}
|
|
7396
|
+
if (foundCurrentAssignment) return;
|
|
7397
|
+
reportProblem({
|
|
7398
|
+
node: dependencyNode.parent.property,
|
|
7399
|
+
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.`
|
|
7400
|
+
});
|
|
7401
|
+
});
|
|
7402
|
+
const staleAssignments = /* @__PURE__ */ new Set();
|
|
7403
|
+
function reportStaleAssignment(writeExpr, key) {
|
|
7404
|
+
if (staleAssignments.has(key)) return;
|
|
7405
|
+
staleAssignments.add(key);
|
|
7406
|
+
reportProblem({
|
|
7407
|
+
node: writeExpr,
|
|
7408
|
+
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)}.`
|
|
7409
|
+
});
|
|
7410
|
+
}
|
|
7411
|
+
const stableDependencies = /* @__PURE__ */ new Set();
|
|
7412
|
+
dependencies.forEach(({ isStable, references }, key) => {
|
|
7413
|
+
if (isStable) stableDependencies.add(key);
|
|
7414
|
+
references.forEach((reference) => {
|
|
7415
|
+
if (reference.writeExpr) reportStaleAssignment(reference.writeExpr, key);
|
|
7416
|
+
});
|
|
7417
|
+
});
|
|
7418
|
+
if (staleAssignments.size > 0) return;
|
|
7419
|
+
if (!declaredDependenciesNode) {
|
|
7420
|
+
if (isAutoDepsHook) return;
|
|
7421
|
+
let setStateInsideEffectWithoutDeps = null;
|
|
7422
|
+
dependencies.forEach(({ references }, key) => {
|
|
7423
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
7424
|
+
references.forEach((reference) => {
|
|
7425
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
7426
|
+
const id = reference.identifier;
|
|
7427
|
+
if (!setStateCallSites.has(id)) return;
|
|
7428
|
+
let fnScope = reference.from;
|
|
7429
|
+
while (fnScope != null && fnScope.type !== "function") fnScope = fnScope.upper;
|
|
7430
|
+
if (fnScope?.block === node) setStateInsideEffectWithoutDeps = key;
|
|
7431
|
+
});
|
|
7432
|
+
});
|
|
7433
|
+
if (setStateInsideEffectWithoutDeps) {
|
|
7434
|
+
const { suggestedDependencies } = collectRecommendations({
|
|
7435
|
+
dependencies,
|
|
7436
|
+
declaredDependencies: [],
|
|
7437
|
+
stableDependencies,
|
|
7438
|
+
externalDependencies: /* @__PURE__ */ new Set(),
|
|
7439
|
+
isEffect: true
|
|
7440
|
+
});
|
|
7441
|
+
const suggestedDependenciesText = `[${suggestedDependencies.join(", ")}]`;
|
|
7442
|
+
const dependenciesArgument = callExpression.arguments[dependenciesIndex];
|
|
7443
|
+
const hasSpreadArgumentBeforeOrAtDependencies = callExpression.arguments.slice(0, dependenciesIndex + 1).some((argument) => argument?.type === "SpreadElement");
|
|
7444
|
+
let fix = null;
|
|
7445
|
+
if (!hasSpreadArgumentBeforeOrAtDependencies) {
|
|
7446
|
+
if (dependenciesArgument?.type === "Identifier" && dependenciesArgument.name === "undefined") fix = (fixer) => fixer.replaceText(dependenciesArgument, suggestedDependenciesText);
|
|
7447
|
+
else if (dependenciesArgument == null && dependenciesIndex === callExpression.arguments.length) {
|
|
7448
|
+
const closeParen = getSourceCode().getLastToken(callExpression);
|
|
7449
|
+
if (closeParen != null && closeParen.value === ")") {
|
|
7450
|
+
const tokenBeforeCloseParen = getSourceCode().getTokenBefore(closeParen);
|
|
7451
|
+
fix = tokenBeforeCloseParen?.value === "," ? (fixer) => fixer.insertTextAfter(tokenBeforeCloseParen, ` ${suggestedDependenciesText}`) : (fixer) => fixer.insertTextBefore(closeParen, `, ${suggestedDependenciesText}`);
|
|
7452
|
+
}
|
|
7453
|
+
}
|
|
7454
|
+
}
|
|
7455
|
+
const dependenciesArgumentText = dependenciesIndex === 1 ? "as a second argument" : `as the dependencies argument (index ${dependenciesIndex})`;
|
|
7456
|
+
const problem = {
|
|
7457
|
+
node: reactiveHook,
|
|
7458
|
+
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.`
|
|
7459
|
+
};
|
|
7460
|
+
if (fix != null) problem.suggest = [{
|
|
7461
|
+
desc: `Add dependencies array: ${suggestedDependenciesText}`,
|
|
7462
|
+
fix
|
|
7463
|
+
}];
|
|
7464
|
+
reportProblem(problem);
|
|
7465
|
+
}
|
|
7466
|
+
return;
|
|
7467
|
+
}
|
|
7468
|
+
if (isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
7469
|
+
const declaredDependencies = [];
|
|
7470
|
+
const externalDependencies = /* @__PURE__ */ new Set();
|
|
7471
|
+
const isArrayExpression = declaredDependenciesNode.type === "ArrayExpression";
|
|
7472
|
+
const isTSAsArrayExpression = declaredDependenciesNode.type === "TSAsExpression" && declaredDependenciesNode.expression.type === "ArrayExpression";
|
|
7473
|
+
if (!isArrayExpression && !isTSAsArrayExpression) reportProblem({
|
|
7474
|
+
node: declaredDependenciesNode,
|
|
7475
|
+
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.`
|
|
7476
|
+
});
|
|
7477
|
+
else (isTSAsArrayExpression ? declaredDependenciesNode.expression : declaredDependenciesNode).elements.forEach((declaredDependencyNode) => {
|
|
7478
|
+
if (declaredDependencyNode === null) return;
|
|
7479
|
+
if (declaredDependencyNode.type === "SpreadElement") {
|
|
7480
|
+
reportProblem({
|
|
7481
|
+
node: declaredDependencyNode,
|
|
7482
|
+
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.`
|
|
7483
|
+
});
|
|
7484
|
+
return;
|
|
7485
|
+
}
|
|
7486
|
+
if (useEffectEventVariables.has(declaredDependencyNode)) reportProblem({
|
|
7487
|
+
node: declaredDependencyNode,
|
|
7488
|
+
message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`,
|
|
7489
|
+
suggest: [{
|
|
7490
|
+
desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``,
|
|
7491
|
+
fix(fixer) {
|
|
7492
|
+
return fixer.removeRange(declaredDependencyNode.range);
|
|
7493
|
+
}
|
|
7494
|
+
}]
|
|
7495
|
+
});
|
|
7496
|
+
let declaredDependency;
|
|
7497
|
+
try {
|
|
7498
|
+
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
7499
|
+
} catch (error) {
|
|
7500
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
7501
|
+
if (declaredDependencyNode.type === "Literal") {
|
|
7502
|
+
if (declaredDependencyNode.value && dependencies.has(declaredDependencyNode.value)) reportProblem({
|
|
7503
|
+
node: declaredDependencyNode,
|
|
7504
|
+
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?`
|
|
7505
|
+
});
|
|
7506
|
+
else reportProblem({
|
|
7507
|
+
node: declaredDependencyNode,
|
|
7508
|
+
message: `The ${declaredDependencyNode.raw} literal is not a valid dependency because it never changes. You can safely remove it.`
|
|
7509
|
+
});
|
|
7510
|
+
} else reportProblem({
|
|
7511
|
+
node: declaredDependencyNode,
|
|
7512
|
+
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.`
|
|
7513
|
+
});
|
|
7514
|
+
return;
|
|
7515
|
+
} else throw error;
|
|
7516
|
+
}
|
|
7517
|
+
let maybeID = declaredDependencyNode;
|
|
7518
|
+
while (maybeID.type === "MemberExpression" || maybeID.type === "OptionalMemberExpression" || maybeID.type === "ChainExpression") maybeID = maybeID.object || maybeID.expression.object;
|
|
7519
|
+
const isDeclaredInComponent = !componentScope.through.some((ref) => ref.identifier === maybeID);
|
|
7520
|
+
declaredDependencies.push({
|
|
7521
|
+
key: declaredDependency,
|
|
7522
|
+
node: declaredDependencyNode
|
|
7523
|
+
});
|
|
7524
|
+
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
7525
|
+
});
|
|
7526
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
7527
|
+
dependencies,
|
|
7528
|
+
declaredDependencies,
|
|
7529
|
+
stableDependencies,
|
|
7530
|
+
externalDependencies,
|
|
7531
|
+
isEffect
|
|
7532
|
+
});
|
|
7533
|
+
let suggestedDeps = suggestedDependencies;
|
|
7534
|
+
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
7535
|
+
scanForConstructions({
|
|
7536
|
+
declaredDependencies,
|
|
7537
|
+
declaredDependenciesNode,
|
|
7538
|
+
componentScope,
|
|
7539
|
+
scope
|
|
7540
|
+
}).forEach(({ construction, isUsedOutsideOfHook, depType }) => {
|
|
7541
|
+
const wrapperHook = depType === "function" ? "useCallback" : "useMemo";
|
|
7542
|
+
const constructionType = depType === "function" ? "definition" : "initialization";
|
|
7543
|
+
const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`;
|
|
7544
|
+
const advice = isUsedOutsideOfHook ? `To fix this, ${defaultAdvice}` : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`;
|
|
7545
|
+
const causation = depType === "conditional" || depType === "logical expression" ? "could make" : "makes";
|
|
7546
|
+
const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc?.start.line}) change on every render. ${advice}`;
|
|
7547
|
+
let suggest;
|
|
7548
|
+
if (isUsedOutsideOfHook && construction.type === "Variable" && depType === "function") suggest = [{
|
|
7549
|
+
desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`,
|
|
7550
|
+
fix(fixer) {
|
|
7551
|
+
const [before, after] = wrapperHook === "useMemo" ? [`useMemo(() => { return `, "; })"] : ["useCallback(", ")"];
|
|
7552
|
+
return [fixer.insertTextBefore(construction.node.init, before), fixer.insertTextAfter(construction.node.init, after)];
|
|
7553
|
+
}
|
|
7554
|
+
}];
|
|
7555
|
+
reportProblem({
|
|
7556
|
+
node: construction.node,
|
|
7557
|
+
message,
|
|
7558
|
+
suggest
|
|
7559
|
+
});
|
|
7560
|
+
});
|
|
7561
|
+
return;
|
|
7562
|
+
}
|
|
7563
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
7564
|
+
dependencies,
|
|
7565
|
+
declaredDependencies: [],
|
|
7566
|
+
stableDependencies,
|
|
7567
|
+
externalDependencies,
|
|
7568
|
+
isEffect
|
|
7569
|
+
}).suggestedDependencies;
|
|
7570
|
+
function areDeclaredDepsAlphabetized() {
|
|
7571
|
+
if (declaredDependencies.length === 0) return true;
|
|
7572
|
+
const declaredDepKeys = declaredDependencies.map((dep) => dep.key);
|
|
7573
|
+
const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
|
|
7574
|
+
return declaredDepKeys.join(",") === sortedDeclaredDepKeys.join(",");
|
|
7575
|
+
}
|
|
7576
|
+
if (areDeclaredDepsAlphabetized()) suggestedDeps.sort();
|
|
7577
|
+
function formatDependency(path) {
|
|
7578
|
+
const members = path.split(".");
|
|
7579
|
+
let finalPath = "";
|
|
7580
|
+
for (let i = 0; i < members.length; i++) {
|
|
7581
|
+
if (i !== 0) {
|
|
7582
|
+
const pathSoFar = members.slice(0, i + 1).join(".");
|
|
7583
|
+
const isOptional = optionalChains.get(pathSoFar) === true;
|
|
7584
|
+
finalPath += isOptional ? "?." : ".";
|
|
7585
|
+
}
|
|
7586
|
+
finalPath += members[i];
|
|
7587
|
+
}
|
|
7588
|
+
return finalPath;
|
|
7589
|
+
}
|
|
7590
|
+
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
7591
|
+
if (deps.size === 0) return null;
|
|
7592
|
+
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.`;
|
|
7593
|
+
}
|
|
7594
|
+
let extraWarning = "";
|
|
7595
|
+
if (unnecessaryDependencies.size > 0) {
|
|
7596
|
+
let badRef = null;
|
|
7597
|
+
Array.from(unnecessaryDependencies.keys()).forEach((key) => {
|
|
7598
|
+
if (badRef !== null) return;
|
|
7599
|
+
if (key.endsWith(".current")) badRef = key;
|
|
7600
|
+
});
|
|
7601
|
+
if (badRef !== null) extraWarning = ` Mutable values like '${badRef}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
7602
|
+
else if (externalDependencies.size > 0) {
|
|
7603
|
+
const dep = Array.from(externalDependencies)[0];
|
|
7604
|
+
if (!scope.set.has(dep)) extraWarning = ` Outer scope values like '${dep}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
7605
|
+
}
|
|
7606
|
+
}
|
|
7607
|
+
if (!extraWarning && missingDependencies.has("props")) {
|
|
7608
|
+
const propDep = dependencies.get("props");
|
|
7609
|
+
if (propDep == null) return;
|
|
7610
|
+
const refs = propDep.references;
|
|
7611
|
+
if (!Array.isArray(refs)) return;
|
|
7612
|
+
let isPropsOnlyUsedInMembers = true;
|
|
7613
|
+
for (const ref of refs) {
|
|
7614
|
+
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
7615
|
+
if (!id) {
|
|
7616
|
+
isPropsOnlyUsedInMembers = false;
|
|
7617
|
+
break;
|
|
7618
|
+
}
|
|
7619
|
+
const parent = id.parent;
|
|
7620
|
+
if (parent == null) {
|
|
7621
|
+
isPropsOnlyUsedInMembers = false;
|
|
7622
|
+
break;
|
|
7623
|
+
}
|
|
7624
|
+
if (parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression") {
|
|
7625
|
+
isPropsOnlyUsedInMembers = false;
|
|
7626
|
+
break;
|
|
7627
|
+
}
|
|
7628
|
+
}
|
|
7629
|
+
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)}.`;
|
|
7630
|
+
}
|
|
7631
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
7632
|
+
let missingCallbackDep = null;
|
|
7633
|
+
missingDependencies.forEach((missingDep) => {
|
|
7634
|
+
if (missingCallbackDep) return;
|
|
7635
|
+
const topScopeRef = componentScope.set.get(missingDep);
|
|
7636
|
+
const usedDep = dependencies.get(missingDep);
|
|
7637
|
+
if (!usedDep?.references || usedDep?.references[0]?.resolved !== topScopeRef) return;
|
|
7638
|
+
const def = topScopeRef?.defs[0];
|
|
7639
|
+
if (def == null || def.name == null || def.type !== "Parameter") return;
|
|
7640
|
+
let isFunctionCall = false;
|
|
7641
|
+
let id;
|
|
7642
|
+
for (const reference of usedDep.references) {
|
|
7643
|
+
id = reference.identifier;
|
|
7644
|
+
if (id != null && id.parent != null && (id.parent.type === "CallExpression" || id.parent.type === "OptionalCallExpression") && id.parent.callee === id) {
|
|
7645
|
+
isFunctionCall = true;
|
|
7646
|
+
break;
|
|
7647
|
+
}
|
|
7648
|
+
}
|
|
7649
|
+
if (!isFunctionCall) return;
|
|
7650
|
+
missingCallbackDep = missingDep;
|
|
7651
|
+
});
|
|
7652
|
+
if (missingCallbackDep !== null) extraWarning = ` If '${missingCallbackDep}' changes too often, find the parent component that defines it and wrap that definition in useCallback.`;
|
|
7653
|
+
}
|
|
7654
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
7655
|
+
let setStateRecommendation = null;
|
|
7656
|
+
for (const missingDep of missingDependencies) {
|
|
7657
|
+
if (setStateRecommendation !== null) break;
|
|
7658
|
+
const references = dependencies.get(missingDep).references;
|
|
7659
|
+
let id;
|
|
7660
|
+
let maybeCall;
|
|
7661
|
+
for (const reference of references) {
|
|
7662
|
+
id = reference.identifier;
|
|
7663
|
+
maybeCall = id.parent;
|
|
7664
|
+
while (maybeCall != null && maybeCall !== componentScope.block) {
|
|
7665
|
+
if (maybeCall.type === "CallExpression") {
|
|
7666
|
+
const correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
|
|
7667
|
+
if (correspondingStateVariable != null) {
|
|
7668
|
+
if ("name" in correspondingStateVariable && correspondingStateVariable.name === missingDep) setStateRecommendation = {
|
|
7669
|
+
missingDep,
|
|
7670
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7671
|
+
form: "updater"
|
|
7672
|
+
};
|
|
7673
|
+
else if (stateVariables.has(id)) setStateRecommendation = {
|
|
7674
|
+
missingDep,
|
|
7675
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7676
|
+
form: "reducer"
|
|
7677
|
+
};
|
|
7678
|
+
else {
|
|
7679
|
+
const resolved = reference.resolved;
|
|
7680
|
+
if (resolved != null) {
|
|
7681
|
+
const def = resolved.defs[0];
|
|
7682
|
+
if (def != null && def.type === "Parameter") setStateRecommendation = {
|
|
7683
|
+
missingDep,
|
|
7684
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7685
|
+
form: "inlineReducer"
|
|
7686
|
+
};
|
|
7687
|
+
}
|
|
7688
|
+
}
|
|
7689
|
+
break;
|
|
7690
|
+
}
|
|
7691
|
+
}
|
|
7692
|
+
maybeCall = maybeCall.parent;
|
|
7693
|
+
}
|
|
7694
|
+
if (setStateRecommendation !== null) break;
|
|
7695
|
+
}
|
|
7696
|
+
}
|
|
7697
|
+
if (setStateRecommendation !== null) switch (setStateRecommendation.form) {
|
|
7698
|
+
case "reducer":
|
|
7699
|
+
extraWarning = ` You can also replace multiple useState variables with useReducer if '${setStateRecommendation.setter}' needs the current value of '${setStateRecommendation.missingDep}'.`;
|
|
7700
|
+
break;
|
|
7701
|
+
case "inlineReducer":
|
|
7702
|
+
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.`;
|
|
7703
|
+
break;
|
|
7704
|
+
case "updater":
|
|
7705
|
+
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.`;
|
|
7706
|
+
break;
|
|
7707
|
+
default: throw new Error("Unknown case.");
|
|
7708
|
+
}
|
|
7709
|
+
}
|
|
7710
|
+
reportProblem({
|
|
7711
|
+
node: declaredDependenciesNode,
|
|
7712
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + (getWarningMessage(missingDependencies, "a", "missing", "include") || getWarningMessage(unnecessaryDependencies, "an", "unnecessary", "exclude") || getWarningMessage(duplicateDependencies, "a", "duplicate", "omit")) + extraWarning,
|
|
7713
|
+
suggest: [{
|
|
7714
|
+
desc: `Update the dependencies array to be: [${suggestedDeps.map(formatDependency).join(", ")}]`,
|
|
7715
|
+
fix(fixer) {
|
|
7716
|
+
return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(", ")}]`);
|
|
7717
|
+
}
|
|
7718
|
+
}]
|
|
7719
|
+
});
|
|
7720
|
+
}
|
|
7721
|
+
function visitCallExpression(node) {
|
|
7722
|
+
const configuredHook = getReactiveHookConfig(node, options.hooks);
|
|
7723
|
+
const callbackIndex = configuredHook ? configuredHook.closureIndex : getReactiveHookCallbackIndex(node.callee, options);
|
|
7724
|
+
if (callbackIndex === -1) return;
|
|
7725
|
+
let callback = node.arguments[callbackIndex];
|
|
7726
|
+
const reactiveHook = node.callee;
|
|
7727
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook);
|
|
7728
|
+
const reactiveHookName = configuredHook?.name ?? ("name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "");
|
|
7729
|
+
const dependenciesIndex = configuredHook ? configuredHook.dependenciesIndex : callbackIndex + 1;
|
|
7730
|
+
const maybeNode = node.arguments[dependenciesIndex];
|
|
7731
|
+
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
7732
|
+
const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName);
|
|
7733
|
+
if (!callback) {
|
|
7734
|
+
if (configuredHook) {
|
|
7735
|
+
const builtInCallbackIndex = getReactiveHookCallbackIndex(reactiveHook, { additionalHooks: void 0 });
|
|
7736
|
+
const builtInCallback = builtInCallbackIndex === -1 ? null : node.arguments[builtInCallbackIndex];
|
|
7737
|
+
if (builtInCallbackIndex === -1 || builtInCallback != null) return;
|
|
7738
|
+
}
|
|
7739
|
+
reportProblem({
|
|
7740
|
+
node: reactiveHook,
|
|
7741
|
+
message: `React Hook ${reactiveHookName} requires an effect callback. Did you forget to pass a callback to the hook?`
|
|
7742
|
+
});
|
|
7743
|
+
return;
|
|
7744
|
+
}
|
|
7745
|
+
if (!maybeNode && isEffect && options.requireExplicitEffectDeps) reportProblem({
|
|
7746
|
+
node: reactiveHook,
|
|
7747
|
+
message: `React Hook ${reactiveHookName} always requires dependencies. Please add a dependency array or an explicit \`undefined\``
|
|
7748
|
+
});
|
|
7749
|
+
const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName);
|
|
7750
|
+
if ((!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) && !isEffect) {
|
|
7751
|
+
if (reactiveHookName === "useMemo" || reactiveHookName === "useCallback") reportProblem({
|
|
7752
|
+
node: reactiveHook,
|
|
7753
|
+
message: `React Hook ${reactiveHookName} does nothing when called with only one argument. Did you forget to pass an array of dependencies?`
|
|
7754
|
+
});
|
|
7755
|
+
return;
|
|
7756
|
+
}
|
|
7757
|
+
while (callback.type === "TSAsExpression" || callback.type === "AsExpression") callback = callback.expression;
|
|
7758
|
+
switch (callback.type) {
|
|
7759
|
+
case "FunctionExpression":
|
|
7760
|
+
case "ArrowFunctionExpression":
|
|
7761
|
+
visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7762
|
+
return;
|
|
7763
|
+
case "Identifier":
|
|
7764
|
+
if (!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
7765
|
+
if ("elements" in declaredDependenciesNode && declaredDependenciesNode.elements && declaredDependenciesNode.elements.some((el) => el && el.type === "Identifier" && el.name === callback.name)) return;
|
|
7766
|
+
const variable = getScope(callback).set.get(callback.name);
|
|
7767
|
+
if (variable == null || variable.defs == null) return;
|
|
7768
|
+
const def = variable.defs[0];
|
|
7769
|
+
if (!def || !def.node) break;
|
|
7770
|
+
if (def.type === "Parameter") {
|
|
7771
|
+
reportProblem({
|
|
7772
|
+
node: reactiveHook,
|
|
7773
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
7774
|
+
});
|
|
7775
|
+
return;
|
|
7776
|
+
}
|
|
7777
|
+
if (def.type !== "Variable" && def.type !== "FunctionName") break;
|
|
7778
|
+
switch (def.node.type) {
|
|
7779
|
+
case "FunctionDeclaration":
|
|
7780
|
+
visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7781
|
+
return;
|
|
7782
|
+
case "VariableDeclarator":
|
|
7783
|
+
const init = def.node.init;
|
|
7784
|
+
if (!init) break;
|
|
7785
|
+
switch (init.type) {
|
|
7786
|
+
case "ArrowFunctionExpression":
|
|
7787
|
+
case "FunctionExpression":
|
|
7788
|
+
visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7789
|
+
return;
|
|
7790
|
+
}
|
|
7791
|
+
}
|
|
7792
|
+
break;
|
|
7793
|
+
default:
|
|
7794
|
+
if (configuredHook) return;
|
|
7795
|
+
reportProblem({
|
|
7796
|
+
node: reactiveHook,
|
|
7797
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
7798
|
+
});
|
|
7799
|
+
return;
|
|
7800
|
+
}
|
|
7801
|
+
reportProblem({
|
|
7802
|
+
node: reactiveHook,
|
|
7803
|
+
message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. Either include it or remove the dependency array.`,
|
|
7804
|
+
suggest: [{
|
|
7805
|
+
desc: `Update the dependencies array to be: [${callback.name}]`,
|
|
7806
|
+
fix(fixer) {
|
|
7807
|
+
return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`);
|
|
7808
|
+
}
|
|
7809
|
+
}]
|
|
7810
|
+
});
|
|
7811
|
+
}
|
|
7812
|
+
return { CallExpression: visitCallExpression };
|
|
7813
|
+
}
|
|
7814
|
+
};
|
|
7815
|
+
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
7816
|
+
const depTree = createDepTree();
|
|
7817
|
+
function createDepTree() {
|
|
7818
|
+
return {
|
|
7819
|
+
isUsed: false,
|
|
7820
|
+
isSatisfiedRecursively: false,
|
|
7821
|
+
isSubtreeUsed: false,
|
|
7822
|
+
children: /* @__PURE__ */ new Map()
|
|
7823
|
+
};
|
|
7824
|
+
}
|
|
7825
|
+
dependencies.forEach((_, key) => {
|
|
7826
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7827
|
+
node.isUsed = true;
|
|
7828
|
+
markAllParentsByPath(depTree, key, (parent) => {
|
|
7829
|
+
parent.isSubtreeUsed = true;
|
|
7830
|
+
});
|
|
7831
|
+
});
|
|
7832
|
+
declaredDependencies.forEach(({ key }) => {
|
|
7833
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7834
|
+
node.isSatisfiedRecursively = true;
|
|
7835
|
+
});
|
|
7836
|
+
stableDependencies.forEach((key) => {
|
|
7837
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7838
|
+
node.isSatisfiedRecursively = true;
|
|
7839
|
+
});
|
|
7840
|
+
function getOrCreateNodeByPath(rootNode, path) {
|
|
7841
|
+
const keys = path.split(".");
|
|
7842
|
+
let node = rootNode;
|
|
7843
|
+
for (const key of keys) {
|
|
7844
|
+
let child = node.children.get(key);
|
|
7845
|
+
if (!child) {
|
|
7846
|
+
child = createDepTree();
|
|
7847
|
+
node.children.set(key, child);
|
|
7848
|
+
}
|
|
7849
|
+
node = child;
|
|
7850
|
+
}
|
|
7851
|
+
return node;
|
|
7852
|
+
}
|
|
7853
|
+
function markAllParentsByPath(rootNode, path, fn) {
|
|
7854
|
+
const keys = path.split(".");
|
|
7855
|
+
let node = rootNode;
|
|
7856
|
+
for (const key of keys) {
|
|
7857
|
+
const child = node.children.get(key);
|
|
7858
|
+
if (!child) return;
|
|
7859
|
+
fn(child);
|
|
7860
|
+
node = child;
|
|
7861
|
+
}
|
|
7862
|
+
}
|
|
7863
|
+
const missingDependencies = /* @__PURE__ */ new Set();
|
|
7864
|
+
const satisfyingDependencies = /* @__PURE__ */ new Set();
|
|
7865
|
+
scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, (key) => key);
|
|
7866
|
+
function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
|
|
7867
|
+
node.children.forEach((child, key) => {
|
|
7868
|
+
const path = keyToPath(key);
|
|
7869
|
+
if (child.isSatisfiedRecursively) {
|
|
7870
|
+
if (child.isSubtreeUsed) satisfyingPaths.add(path);
|
|
7871
|
+
return;
|
|
7872
|
+
}
|
|
7873
|
+
if (child.isUsed) {
|
|
7874
|
+
missingPaths.add(path);
|
|
7875
|
+
return;
|
|
7876
|
+
}
|
|
7877
|
+
scanTreeRecursively(child, missingPaths, satisfyingPaths, (childKey) => path + "." + childKey);
|
|
7878
|
+
});
|
|
7879
|
+
}
|
|
7880
|
+
const suggestedDependencies = [];
|
|
7881
|
+
const unnecessaryDependencies = /* @__PURE__ */ new Set();
|
|
7882
|
+
const duplicateDependencies = /* @__PURE__ */ new Set();
|
|
7883
|
+
declaredDependencies.forEach(({ key }) => {
|
|
7884
|
+
if (satisfyingDependencies.has(key)) {
|
|
7885
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
7886
|
+
else duplicateDependencies.add(key);
|
|
7887
|
+
} else if (isEffect && !key.endsWith(".current") && !externalDependencies.has(key)) {
|
|
7888
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
7889
|
+
} else unnecessaryDependencies.add(key);
|
|
7890
|
+
});
|
|
7891
|
+
missingDependencies.forEach((key) => {
|
|
7892
|
+
suggestedDependencies.push(key);
|
|
7893
|
+
});
|
|
7894
|
+
return {
|
|
7895
|
+
suggestedDependencies,
|
|
7896
|
+
unnecessaryDependencies,
|
|
7897
|
+
duplicateDependencies,
|
|
7898
|
+
missingDependencies
|
|
7899
|
+
};
|
|
7900
|
+
}
|
|
7901
|
+
function getConstructionExpressionType(node) {
|
|
7902
|
+
switch (node.type) {
|
|
7903
|
+
case "ObjectExpression": return "object";
|
|
7904
|
+
case "ArrayExpression": return "array";
|
|
7905
|
+
case "ArrowFunctionExpression":
|
|
7906
|
+
case "FunctionExpression": return "function";
|
|
7907
|
+
case "ClassExpression": return "class";
|
|
7908
|
+
case "ConditionalExpression":
|
|
7909
|
+
if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
|
|
7910
|
+
return null;
|
|
7911
|
+
case "LogicalExpression":
|
|
7912
|
+
if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
|
|
7913
|
+
return null;
|
|
7914
|
+
case "JSXFragment": return "JSX fragment";
|
|
7915
|
+
case "JSXElement": return "JSX element";
|
|
7916
|
+
case "AssignmentExpression":
|
|
7917
|
+
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
7918
|
+
return null;
|
|
7919
|
+
case "NewExpression": return "object construction";
|
|
7920
|
+
case "Literal":
|
|
7921
|
+
if (node.value instanceof RegExp) return "regular expression";
|
|
7922
|
+
return null;
|
|
7923
|
+
case "TypeCastExpression":
|
|
7924
|
+
case "AsExpression":
|
|
7925
|
+
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
7926
|
+
}
|
|
7927
|
+
return null;
|
|
7928
|
+
}
|
|
7929
|
+
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
7930
|
+
const constructions = declaredDependencies.map(({ key }) => {
|
|
7931
|
+
const ref = componentScope.variables.find((v) => v.name === key);
|
|
7932
|
+
if (ref == null) return null;
|
|
7933
|
+
const node = ref.defs[0];
|
|
7934
|
+
if (node == null) return null;
|
|
7935
|
+
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
7936
|
+
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
7937
|
+
if (constantExpressionType) return [ref, constantExpressionType];
|
|
7938
|
+
}
|
|
7939
|
+
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
7940
|
+
if (node.type === "ClassName" && node.node.type === "ClassDeclaration") return [ref, "class"];
|
|
7941
|
+
return null;
|
|
7942
|
+
}).filter(Boolean);
|
|
7943
|
+
function isUsedOutsideOfHook(ref) {
|
|
7944
|
+
let foundWriteExpr = false;
|
|
7945
|
+
for (const reference of ref.references) {
|
|
7946
|
+
if (reference.writeExpr) {
|
|
7947
|
+
if (foundWriteExpr) return true;
|
|
7948
|
+
else {
|
|
7949
|
+
foundWriteExpr = true;
|
|
7950
|
+
continue;
|
|
7951
|
+
}
|
|
7952
|
+
}
|
|
7953
|
+
let currentScope = reference.from;
|
|
7954
|
+
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
7955
|
+
if (currentScope !== scope) {
|
|
7956
|
+
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
7957
|
+
}
|
|
7958
|
+
}
|
|
7959
|
+
return false;
|
|
7960
|
+
}
|
|
7961
|
+
return constructions.map(([ref, depType]) => ({
|
|
7962
|
+
construction: ref.defs[0],
|
|
7963
|
+
depType,
|
|
7964
|
+
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
7965
|
+
}));
|
|
7966
|
+
}
|
|
7967
|
+
function getDependency(node) {
|
|
7968
|
+
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);
|
|
7969
|
+
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
7970
|
+
else return node;
|
|
7971
|
+
}
|
|
7972
|
+
function markNode(node, optionalChains, result) {
|
|
7973
|
+
if (optionalChains) {
|
|
7974
|
+
if ("optional" in node && node.optional) {
|
|
7975
|
+
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
7976
|
+
} else optionalChains.set(result, false);
|
|
7977
|
+
}
|
|
7978
|
+
}
|
|
7979
|
+
function analyzePropertyChain(node, optionalChains) {
|
|
7980
|
+
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
7981
|
+
const result = node.name;
|
|
7982
|
+
if (optionalChains) optionalChains.set(result, false);
|
|
7983
|
+
return result;
|
|
7984
|
+
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
7985
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
7986
|
+
markNode(node, optionalChains, result);
|
|
7987
|
+
return result;
|
|
7988
|
+
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
7989
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
7990
|
+
markNode(node, optionalChains, result);
|
|
7991
|
+
return result;
|
|
7992
|
+
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
7993
|
+
const expression = node.expression;
|
|
7994
|
+
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
7995
|
+
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
7996
|
+
markNode(expression, optionalChains, result);
|
|
7997
|
+
return result;
|
|
7998
|
+
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
7999
|
+
}
|
|
8000
|
+
function getNodeWithoutReactNamespace(node) {
|
|
8001
|
+
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
8002
|
+
return node;
|
|
8003
|
+
}
|
|
8004
|
+
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
8005
|
+
const node = getNodeWithoutReactNamespace(calleeNode);
|
|
8006
|
+
if (node.type !== "Identifier") return -1;
|
|
8007
|
+
switch (node.name) {
|
|
8008
|
+
case "useEffect":
|
|
8009
|
+
case "useLayoutEffect":
|
|
8010
|
+
case "useCallback":
|
|
8011
|
+
case "useMemo": return 0;
|
|
8012
|
+
case "useImperativeHandle": return 1;
|
|
8013
|
+
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
8014
|
+
let name;
|
|
8015
|
+
try {
|
|
8016
|
+
name = analyzePropertyChain(node, null);
|
|
8017
|
+
} catch (error) {
|
|
8018
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
8019
|
+
else throw error;
|
|
8020
|
+
}
|
|
8021
|
+
if (options.additionalHooks instanceof RegExp) options.additionalHooks.lastIndex = 0;
|
|
8022
|
+
return options.additionalHooks.test(name) ? 0 : -1;
|
|
8023
|
+
} else return -1;
|
|
8024
|
+
}
|
|
8025
|
+
}
|
|
8026
|
+
function fastFindReferenceWithParent(start, target) {
|
|
8027
|
+
const queue = [start];
|
|
8028
|
+
let item;
|
|
8029
|
+
while (queue.length) {
|
|
8030
|
+
item = queue.shift();
|
|
8031
|
+
if (isSameIdentifier(item, target)) return item;
|
|
8032
|
+
if (!isAncestorNodeOf(item, target)) continue;
|
|
8033
|
+
for (const [key, value] of Object.entries(item)) {
|
|
8034
|
+
if (key === "parent") continue;
|
|
8035
|
+
if (isNodeLike(value)) {
|
|
8036
|
+
value.parent = item;
|
|
8037
|
+
queue.push(value);
|
|
8038
|
+
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
8039
|
+
if (isNodeLike(val)) {
|
|
8040
|
+
val.parent = item;
|
|
8041
|
+
queue.push(val);
|
|
8042
|
+
}
|
|
8043
|
+
});
|
|
8044
|
+
}
|
|
8045
|
+
}
|
|
8046
|
+
return null;
|
|
8047
|
+
}
|
|
8048
|
+
function joinEnglish(arr) {
|
|
8049
|
+
let s = "";
|
|
8050
|
+
for (let i = 0; i < arr.length; i++) {
|
|
8051
|
+
s += arr[i];
|
|
8052
|
+
if (i === 0 && arr.length === 2) s += " and ";
|
|
8053
|
+
else if (i === arr.length - 2 && arr.length > 2) s += ", and ";
|
|
8054
|
+
else if (i < arr.length - 1) s += ", ";
|
|
8055
|
+
}
|
|
8056
|
+
return s;
|
|
8057
|
+
}
|
|
8058
|
+
function isNodeLike(val) {
|
|
8059
|
+
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
8060
|
+
}
|
|
8061
|
+
function isSameIdentifier(a, b) {
|
|
8062
|
+
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];
|
|
8063
|
+
}
|
|
8064
|
+
function isAncestorNodeOf(a, b) {
|
|
8065
|
+
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
8066
|
+
}
|
|
8067
|
+
function isUseEffectEventIdentifier(node) {
|
|
8068
|
+
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
8069
|
+
}
|
|
8070
|
+
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
8071
|
+
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
8072
|
+
}
|
|
8073
|
+
// src/rules/unsupported-syntax/lib.ts
|
|
8074
|
+
function isEvalCall(node) {
|
|
8075
|
+
const callee = Extract.unwrap(node.callee);
|
|
8076
|
+
switch (callee.type) {
|
|
8077
|
+
case AST_NODE_TYPES.Identifier: return callee.name === "eval";
|
|
8078
|
+
case AST_NODE_TYPES.MemberExpression:
|
|
8079
|
+
if (!Check.isIdentifier(Extract.unwrap(callee.object), "globalThis")) return false;
|
|
8080
|
+
return !callee.computed && Check.isIdentifier(callee.property, "eval");
|
|
8081
|
+
default: return false;
|
|
8082
|
+
}
|
|
8083
|
+
}
|
|
8084
|
+
var unsupported_syntax_default = createRule({
|
|
8085
|
+
meta: {
|
|
8086
|
+
type: "problem",
|
|
8087
|
+
docs: { description: "Validates against syntax that React Compiler does not support." },
|
|
8088
|
+
messages: {
|
|
8089
|
+
eval: "Do not use 'eval' inside components or hooks. 'eval' cannot be statically analyzed and is not supported by React Compiler.",
|
|
8090
|
+
with: "Do not use 'with' statements inside components or hooks. 'with' changes scope dynamically and is not supported by React Compiler."
|
|
8091
|
+
},
|
|
8092
|
+
schema: []
|
|
8093
|
+
},
|
|
8094
|
+
name: "unsupported-syntax",
|
|
8095
|
+
create: create$2
|
|
8096
|
+
});
|
|
8097
|
+
function create$2(context) {
|
|
8098
|
+
const hc = core.getHookCollector(context);
|
|
8099
|
+
const fc = core.getFunctionComponentCollector(context);
|
|
8100
|
+
const evalCalls = [];
|
|
8101
|
+
const withStmts = [];
|
|
8102
|
+
return merge(hc.visitor, fc.visitor, {
|
|
8103
|
+
CallExpression(node) {
|
|
8104
|
+
if (!isEvalCall(node)) return;
|
|
8105
|
+
const func = Traverse.findParent(node, Check.isFunction);
|
|
8106
|
+
if (func == null) return;
|
|
8107
|
+
evalCalls.push({
|
|
8108
|
+
func,
|
|
8109
|
+
node
|
|
8110
|
+
});
|
|
8111
|
+
},
|
|
8112
|
+
WithStatement(node) {
|
|
8113
|
+
const func = Traverse.findParent(node, Check.isFunction);
|
|
8114
|
+
if (func == null) return;
|
|
8115
|
+
withStmts.push({
|
|
8116
|
+
func,
|
|
8117
|
+
node
|
|
8118
|
+
});
|
|
8119
|
+
},
|
|
8120
|
+
"Program:exit"(node) {
|
|
8121
|
+
const comps = fc.api.getAllComponents(node);
|
|
8122
|
+
const hooks = hc.api.getAllHooks(node);
|
|
8123
|
+
const funcs = [...comps, ...hooks];
|
|
8124
|
+
for (const { func, node } of evalCalls) {
|
|
8125
|
+
if (!funcs.some((f) => f.node === func)) continue;
|
|
8126
|
+
context.report({
|
|
8127
|
+
messageId: "eval",
|
|
8128
|
+
node
|
|
8129
|
+
});
|
|
8130
|
+
}
|
|
8131
|
+
for (const { func, node } of withStmts) {
|
|
8132
|
+
if (!funcs.some((f) => f.node === func)) continue;
|
|
8133
|
+
context.report({
|
|
8134
|
+
messageId: "with",
|
|
8135
|
+
node
|
|
8136
|
+
});
|
|
8137
|
+
}
|
|
8138
|
+
}
|
|
8139
|
+
});
|
|
8140
|
+
}
|
|
8141
|
+
// src/rules/use-memo/helpers.ts
|
|
8142
|
+
function isResultUsed(node) {
|
|
8143
|
+
let parent = node.parent;
|
|
8144
|
+
while (Check.isTypeExpression(parent)) parent = parent.parent;
|
|
8145
|
+
return parent.type === AST_NODE_TYPES.VariableDeclarator || parent.type === AST_NODE_TYPES.AssignmentExpression || parent.type === AST_NODE_TYPES.AssignmentPattern || parent.type === AST_NODE_TYPES.Property || parent.type === AST_NODE_TYPES.ReturnStatement || parent.type === AST_NODE_TYPES.JSXExpressionContainer || parent.type === AST_NODE_TYPES.CallExpression || parent.type === AST_NODE_TYPES.NewExpression || parent.type === AST_NODE_TYPES.ArrayExpression || parent.type === AST_NODE_TYPES.ConditionalExpression || parent.type === AST_NODE_TYPES.LogicalExpression || parent.type === AST_NODE_TYPES.SequenceExpression || parent.type === AST_NODE_TYPES.SpreadElement || parent.type === AST_NODE_TYPES.TemplateLiteral || parent.type === AST_NODE_TYPES.BinaryExpression || parent.type === AST_NODE_TYPES.UnaryExpression || parent.type === AST_NODE_TYPES.MemberExpression || parent.type === AST_NODE_TYPES.TaggedTemplateExpression || parent.type === AST_NODE_TYPES.ChainExpression || parent.type === AST_NODE_TYPES.ArrowFunctionExpression || parent.type === AST_NODE_TYPES.ForOfStatement || parent.type === AST_NODE_TYPES.ForInStatement;
|
|
8146
|
+
}
|
|
8147
|
+
// src/rules/use-memo/collect.ts
|
|
8148
|
+
function createFactCollector(isUseMemoCall) {
|
|
8149
|
+
const facts = { calls: [] };
|
|
8150
|
+
function collectWrites(callback) {
|
|
8151
|
+
const writes = [];
|
|
8152
|
+
function pushWrite(node, target) {
|
|
8153
|
+
if (!Check.isIdentifier(target)) return;
|
|
8154
|
+
if (Traverse.hasParent(node, Check.isFunction, (n) => n === callback)) return;
|
|
8155
|
+
writes.push({
|
|
8156
|
+
node,
|
|
8157
|
+
target
|
|
8158
|
+
});
|
|
8159
|
+
}
|
|
8160
|
+
Traverse.simpleTraverse(callback.body, { enter(node) {
|
|
8161
|
+
switch (node.type) {
|
|
8162
|
+
case AST_NODE_TYPES.AssignmentExpression:
|
|
8163
|
+
for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
|
|
8164
|
+
return;
|
|
8165
|
+
case AST_NODE_TYPES.ForInStatement:
|
|
8166
|
+
case AST_NODE_TYPES.ForOfStatement:
|
|
8167
|
+
if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
|
|
8168
|
+
for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
|
|
8169
|
+
return;
|
|
8170
|
+
}
|
|
8171
|
+
} });
|
|
8172
|
+
return writes;
|
|
8173
|
+
}
|
|
8174
|
+
return {
|
|
8175
|
+
facts,
|
|
8176
|
+
visitor: { CallExpression(node) {
|
|
8177
|
+
if (!isUseMemoCall(node)) return;
|
|
8178
|
+
const callbackArg = node.arguments[0] ?? null;
|
|
8179
|
+
const callback = callbackArg != null ? Extract.unwrap(callbackArg) : null;
|
|
8180
|
+
const callbackFunction = callback != null && Check.isFunction(callback) ? callback : null;
|
|
8181
|
+
facts.calls.push({
|
|
8182
|
+
callback: callbackFunction,
|
|
8183
|
+
callbackArg,
|
|
8184
|
+
isResultUsed: isResultUsed(node),
|
|
8185
|
+
node,
|
|
8186
|
+
returnStatements: callbackFunction != null ? Collect.getReturnStatements(callbackFunction) : [],
|
|
8187
|
+
writes: callbackFunction != null ? collectWrites(callbackFunction) : []
|
|
8188
|
+
});
|
|
8189
|
+
} }
|
|
8190
|
+
};
|
|
8191
|
+
}
|
|
8192
|
+
// src/rules/use-memo/origins.ts
|
|
8193
|
+
function isDeclaredInsideCallback(variable, callback) {
|
|
8194
|
+
let scope = variable.scope;
|
|
8195
|
+
while (scope != null) {
|
|
7302
8196
|
if (scope.block === callback) return true;
|
|
7303
8197
|
scope = scope.upper;
|
|
7304
8198
|
}
|
|
@@ -7383,76 +8277,6 @@ const LAZY_INIT_ALLOW_LIST = [
|
|
|
7383
8277
|
"String",
|
|
7384
8278
|
"Number"
|
|
7385
8279
|
];
|
|
7386
|
-
const EXPRESSION_VISITOR_KEYS = {
|
|
7387
|
-
[AST_NODE_TYPES.ArrayExpression]: ["elements"],
|
|
7388
|
-
[AST_NODE_TYPES.ArrayPattern]: ["elements"],
|
|
7389
|
-
[AST_NODE_TYPES.AssignmentExpression]: ["left", "right"],
|
|
7390
|
-
[AST_NODE_TYPES.AssignmentPattern]: ["left", "right"],
|
|
7391
|
-
[AST_NODE_TYPES.AwaitExpression]: ["argument"],
|
|
7392
|
-
[AST_NODE_TYPES.BinaryExpression]: ["left", "right"],
|
|
7393
|
-
[AST_NODE_TYPES.CallExpression]: ["callee", "arguments"],
|
|
7394
|
-
[AST_NODE_TYPES.ChainExpression]: ["expression"],
|
|
7395
|
-
[AST_NODE_TYPES.ConditionalExpression]: [
|
|
7396
|
-
"test",
|
|
7397
|
-
"consequent",
|
|
7398
|
-
"alternate"
|
|
7399
|
-
],
|
|
7400
|
-
[AST_NODE_TYPES.Decorator]: ["expression"],
|
|
7401
|
-
[AST_NODE_TYPES.DoWhileStatement]: ["test"],
|
|
7402
|
-
[AST_NODE_TYPES.ExpressionStatement]: ["expression"],
|
|
7403
|
-
[AST_NODE_TYPES.ForInStatement]: ["left", "right"],
|
|
7404
|
-
[AST_NODE_TYPES.ForOfStatement]: ["left", "right"],
|
|
7405
|
-
[AST_NODE_TYPES.ForStatement]: ["test"],
|
|
7406
|
-
[AST_NODE_TYPES.IfStatement]: [
|
|
7407
|
-
"test",
|
|
7408
|
-
"consequent",
|
|
7409
|
-
"alternate"
|
|
7410
|
-
],
|
|
7411
|
-
[AST_NODE_TYPES.ImportExpression]: ["source"],
|
|
7412
|
-
[AST_NODE_TYPES.JSXExpressionContainer]: ["expression"],
|
|
7413
|
-
[AST_NODE_TYPES.JSXSpreadChild]: ["expression"],
|
|
7414
|
-
[AST_NODE_TYPES.LogicalExpression]: ["left", "right"],
|
|
7415
|
-
[AST_NODE_TYPES.MemberExpression]: ["object", "property"],
|
|
7416
|
-
[AST_NODE_TYPES.NewExpression]: ["callee", "arguments"],
|
|
7417
|
-
[AST_NODE_TYPES.ObjectExpression]: ["properties"],
|
|
7418
|
-
[AST_NODE_TYPES.ObjectPattern]: ["properties"],
|
|
7419
|
-
[AST_NODE_TYPES.Property]: ["value"],
|
|
7420
|
-
[AST_NODE_TYPES.SequenceExpression]: ["expressions"],
|
|
7421
|
-
[AST_NODE_TYPES.SpreadElement]: ["argument"],
|
|
7422
|
-
[AST_NODE_TYPES.SwitchCase]: ["test", "consequent"],
|
|
7423
|
-
[AST_NODE_TYPES.TaggedTemplateExpression]: ["tag", "quasi"],
|
|
7424
|
-
[AST_NODE_TYPES.TemplateLiteral]: ["expressions"],
|
|
7425
|
-
[AST_NODE_TYPES.TSAsExpression]: ["expression"],
|
|
7426
|
-
[AST_NODE_TYPES.TSClassImplements]: ["expression"],
|
|
7427
|
-
[AST_NODE_TYPES.TSExportAssignment]: ["expression"],
|
|
7428
|
-
[AST_NODE_TYPES.TSExternalModuleReference]: ["expression"],
|
|
7429
|
-
[AST_NODE_TYPES.TSInstantiationExpression]: ["expression"],
|
|
7430
|
-
[AST_NODE_TYPES.TSInterfaceHeritage]: ["expression"],
|
|
7431
|
-
[AST_NODE_TYPES.TSNonNullExpression]: ["expression"],
|
|
7432
|
-
[AST_NODE_TYPES.TSSatisfiesExpression]: ["expression"],
|
|
7433
|
-
[AST_NODE_TYPES.TSTypeAssertion]: ["expression"],
|
|
7434
|
-
[AST_NODE_TYPES.UnaryExpression]: ["argument"],
|
|
7435
|
-
[AST_NODE_TYPES.UpdateExpression]: ["argument"],
|
|
7436
|
-
[AST_NODE_TYPES.WhileStatement]: ["test"],
|
|
7437
|
-
[AST_NODE_TYPES.YieldExpression]: ["argument"]
|
|
7438
|
-
};
|
|
7439
|
-
function getExpressionsOfType(type) {
|
|
7440
|
-
const isNodeOfType = Check.is(type);
|
|
7441
|
-
const recurse = (node) => {
|
|
7442
|
-
const expressions = [];
|
|
7443
|
-
simpleTraverse(node, {
|
|
7444
|
-
enter(node, parent) {
|
|
7445
|
-
if (parent?.type === AST_NODE_TYPES.MemberExpression && !parent.computed && parent.property === node) return;
|
|
7446
|
-
if (isNodeOfType(node)) expressions.push(node);
|
|
7447
|
-
},
|
|
7448
|
-
visitorKeys: EXPRESSION_VISITOR_KEYS
|
|
7449
|
-
});
|
|
7450
|
-
return expressions;
|
|
7451
|
-
};
|
|
7452
|
-
return recurse;
|
|
7453
|
-
}
|
|
7454
|
-
const getNewExpressions = getExpressionsOfType(AST_NODE_TYPES.NewExpression);
|
|
7455
|
-
const getCallExpressions = getExpressionsOfType(AST_NODE_TYPES.CallExpression);
|
|
7456
8280
|
// src/rules/use-state/use-state.ts
|
|
7457
8281
|
const RULE_NAME = "use-state";
|
|
7458
8282
|
const defaultOptions = [{
|
|
@@ -7501,7 +8325,7 @@ function create(context) {
|
|
|
7501
8325
|
if (enforceLazyInitialization) {
|
|
7502
8326
|
const [useStateInput] = node.arguments;
|
|
7503
8327
|
if (useStateInput != null) {
|
|
7504
|
-
for (const expr of getNewExpressions(useStateInput)) {
|
|
8328
|
+
for (const expr of Collect.getNewExpressions(useStateInput)) {
|
|
7505
8329
|
if (!hasProperty(expr.callee, "name")) continue;
|
|
7506
8330
|
if (LAZY_INIT_ALLOW_LIST.includes(expr.callee.name)) continue;
|
|
7507
8331
|
if (Traverse.hasParent(expr, core.isUseCall(context))) continue;
|
|
@@ -7510,7 +8334,7 @@ function create(context) {
|
|
|
7510
8334
|
node: expr
|
|
7511
8335
|
});
|
|
7512
8336
|
}
|
|
7513
|
-
for (const expr of getCallExpressions(useStateInput)) {
|
|
8337
|
+
for (const expr of Collect.getCallExpressions(useStateInput)) {
|
|
7514
8338
|
if (!hasProperty(expr.callee, "name")) continue;
|
|
7515
8339
|
if (core.isHookName(expr.callee.name)) continue;
|
|
7516
8340
|
if (LAZY_INIT_ALLOW_LIST.includes(expr.callee.name)) continue;
|
|
@@ -7581,7 +8405,7 @@ const plugin = {
|
|
|
7581
8405
|
},
|
|
7582
8406
|
rules: {
|
|
7583
8407
|
"error-boundaries": error_boundaries_default,
|
|
7584
|
-
"exhaustive-deps": rule$
|
|
8408
|
+
"exhaustive-deps": rule$2,
|
|
7585
8409
|
globals: globals_default,
|
|
7586
8410
|
immutability: immutability_default,
|
|
7587
8411
|
"no-access-state-in-setstate": no_access_state_in_setstate_default,
|
|
@@ -7626,10 +8450,11 @@ const plugin = {
|
|
|
7626
8450
|
"no-use-context": no_use_context_default,
|
|
7627
8451
|
purity: purity_default,
|
|
7628
8452
|
refs: refs_default,
|
|
7629
|
-
"rules-of-hooks": rule,
|
|
8453
|
+
"rules-of-hooks": rule$1,
|
|
7630
8454
|
"set-state-in-effect": set_state_in_effect_default,
|
|
7631
8455
|
"set-state-in-render": set_state_in_render_default,
|
|
7632
8456
|
"static-components": static_components_default,
|
|
8457
|
+
"unstable-exhaustive-deps": rule,
|
|
7633
8458
|
"unsupported-syntax": unsupported_syntax_default,
|
|
7634
8459
|
"use-memo": use_memo_default,
|
|
7635
8460
|
"use-state": use_state_default
|