@eslint-react/eslint-plugin 5.30.0-beta.13 → 5.30.0-beta.14

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