@openrewrite/recipes-react 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +10 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
  6. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
  7. package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
  8. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
  9. package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
  10. package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
  11. package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
  12. package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
  13. package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
  14. package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
  15. package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
  16. package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
  17. package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
  18. package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
  19. package/dist/migration/cra-to-vite/cra-script.js +82 -0
  20. package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
  21. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
  22. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
  23. package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
  24. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
  25. package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
  26. package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
  27. package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
  28. package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
  29. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  30. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +5 -6
  31. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  32. package/dist/migration/cra-to-vite/index.d.ts +8 -2
  33. package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
  34. package/dist/migration/cra-to-vite/index.js +17 -2
  35. package/dist/migration/cra-to-vite/index.js.map +1 -1
  36. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
  37. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
  38. package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
  39. package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
  40. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
  41. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
  42. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
  43. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
  44. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
  45. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
  46. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
  47. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
  48. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
  49. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
  50. package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
  51. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
  52. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
  53. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
  54. package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
  55. package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
  56. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
  57. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
  58. package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
  59. package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
  60. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
  61. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
  62. package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
  63. package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
  64. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
  65. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
  66. package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
  67. package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
  68. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
  69. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
  70. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
  71. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
  72. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
  73. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
  74. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  75. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
  76. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  77. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
  78. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
  79. package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
  80. package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
  81. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
  82. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
  83. package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
  84. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
  85. package/dist/migration/cra-to-vite/shared.d.ts +1 -1
  86. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  87. package/dist/migration/cra-to-vite/shared.js +19 -4
  88. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  89. package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
  90. package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
  91. package/dist/migration/cra-to-vite/svg-component.js +60 -0
  92. package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
  93. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  94. package/dist/migration/cra-to-vite/update-react-app-env-types.js +12 -3
  95. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  96. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
  97. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  98. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
  99. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  100. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  101. package/dist/react18/replace-reactdom-render.js +16 -8
  102. package/dist/react18/replace-reactdom-render.js.map +1 -1
  103. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  104. package/dist/react18/replace-unmount-component-at-node.js +8 -1
  105. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  106. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  107. package/dist/react19/find-legacy-context-api.js +21 -38
  108. package/dist/react19/find-legacy-context-api.js.map +1 -1
  109. package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
  110. package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
  111. package/dist/react19/remove-unstable-batched-updates.js +295 -0
  112. package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
  113. package/dist/react19/replace-default-props.d.ts +1 -0
  114. package/dist/react19/replace-default-props.d.ts.map +1 -1
  115. package/dist/react19/replace-default-props.js +198 -151
  116. package/dist/react19/replace-default-props.js.map +1 -1
  117. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  118. package/dist/react19/replace-react-shallow-renderer.js +10 -25
  119. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  120. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  121. package/dist/refactoring/class-to-functional.js +2 -0
  122. package/dist/refactoring/class-to-functional.js.map +1 -1
  123. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  124. package/dist/refactoring/create-class-to-es6.js +14 -49
  125. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  126. package/dist/search/find-function-component-default-props.d.ts.map +1 -1
  127. package/dist/search/find-function-component-default-props.js +6 -15
  128. package/dist/search/find-function-component-default-props.js.map +1 -1
  129. package/dist/search/find-redux-stores.d.ts +12 -0
  130. package/dist/search/find-redux-stores.d.ts.map +1 -0
  131. package/dist/search/find-redux-stores.js +87 -0
  132. package/dist/search/find-redux-stores.js.map +1 -0
  133. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  134. package/dist/simplify-object-pattern-property.js +14 -21
  135. package/dist/simplify-object-pattern-property.js.map +1 -1
  136. package/dist/simplify-react-imports.d.ts.map +1 -1
  137. package/dist/simplify-react-imports.js +10 -59
  138. package/dist/simplify-react-imports.js.map +1 -1
  139. package/dist/testing/enzyme-constant-strings.d.ts +12 -0
  140. package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
  141. package/dist/testing/enzyme-constant-strings.js +101 -0
  142. package/dist/testing/enzyme-constant-strings.js.map +1 -0
  143. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  144. package/dist/testing/enzyme-host-components.js +5 -2
  145. package/dist/testing/enzyme-host-components.js.map +1 -1
  146. package/dist/testing/enzyme-portals.d.ts +38 -0
  147. package/dist/testing/enzyme-portals.d.ts.map +1 -0
  148. package/dist/testing/enzyme-portals.js +226 -0
  149. package/dist/testing/enzyme-portals.js.map +1 -0
  150. package/dist/testing/enzyme-selector-names.d.ts +9 -0
  151. package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
  152. package/dist/testing/enzyme-selector-names.js +50 -0
  153. package/dist/testing/enzyme-selector-names.js.map +1 -0
  154. package/dist/testing/enzyme-to-react-testing-library.d.ts +80 -8
  155. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  156. package/dist/testing/enzyme-to-react-testing-library.js +384 -40
  157. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  158. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  159. package/dist/testing/enzyme-usage.js +27 -4
  160. package/dist/testing/enzyme-usage.js.map +1 -1
  161. package/dist/testing/enzyme-wrapper-scope.d.ts +14 -6
  162. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  163. package/dist/testing/enzyme-wrapper-scope.js +143 -16
  164. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  165. package/dist/util/java-recipe-proxy.d.ts +18 -0
  166. package/dist/util/java-recipe-proxy.d.ts.map +1 -0
  167. package/dist/util/java-recipe-proxy.js +97 -0
  168. package/dist/util/java-recipe-proxy.js.map +1 -0
  169. package/dist/util/module-imports.d.ts +1 -0
  170. package/dist/util/module-imports.d.ts.map +1 -1
  171. package/dist/util/module-imports.js +5 -1
  172. package/dist/util/module-imports.js.map +1 -1
  173. package/dist/util/reindent.d.ts +5 -0
  174. package/dist/util/reindent.d.ts.map +1 -0
  175. package/dist/util/reindent.js +44 -0
  176. package/dist/util/reindent.js.map +1 -0
  177. package/dist/zustand/redux-stores.d.ts +74 -0
  178. package/dist/zustand/redux-stores.d.ts.map +1 -0
  179. package/dist/zustand/redux-stores.js +402 -0
  180. package/dist/zustand/redux-stores.js.map +1 -0
  181. package/dist/zustand/redux-to-zustand.d.ts +76 -0
  182. package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
  183. package/dist/zustand/redux-to-zustand.js +653 -0
  184. package/dist/zustand/redux-to-zustand.js.map +1 -0
  185. package/dist/zustand/zustand-plan.d.ts +96 -0
  186. package/dist/zustand/zustand-plan.d.ts.map +1 -0
  187. package/dist/zustand/zustand-plan.js +822 -0
  188. package/dist/zustand/zustand-plan.js.map +1 -0
  189. package/package.json +2 -2
  190. package/src/index.ts +9 -4
  191. package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
  192. package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
  193. package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
  194. package/src/migration/cra-to-vite/cra-script.ts +61 -0
  195. package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
  196. package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
  197. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +5 -6
  198. package/src/migration/cra-to-vite/index.ts +10 -2
  199. package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
  200. package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
  201. package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
  202. package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
  203. package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
  204. package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
  205. package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
  206. package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
  207. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
  208. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
  209. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
  210. package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
  211. package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
  212. package/src/migration/cra-to-vite/shared.ts +20 -10
  213. package/src/migration/cra-to-vite/svg-component.ts +39 -0
  214. package/src/migration/cra-to-vite/update-react-app-env-types.ts +13 -6
  215. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
  216. package/src/react18/replace-reactdom-render.ts +17 -8
  217. package/src/react18/replace-unmount-component-at-node.ts +13 -2
  218. package/src/react19/find-legacy-context-api.ts +21 -42
  219. package/src/react19/remove-unstable-batched-updates.ts +301 -0
  220. package/src/react19/replace-default-props.ts +212 -159
  221. package/src/react19/replace-react-shallow-renderer.ts +13 -36
  222. package/src/refactoring/class-to-functional.ts +3 -1
  223. package/src/refactoring/create-class-to-es6.ts +12 -63
  224. package/src/search/find-function-component-default-props.ts +8 -10
  225. package/src/search/find-redux-stores.ts +76 -0
  226. package/src/simplify-object-pattern-property.ts +22 -49
  227. package/src/simplify-react-imports.ts +12 -66
  228. package/src/testing/enzyme-constant-strings.ts +95 -0
  229. package/src/testing/enzyme-host-components.ts +6 -2
  230. package/src/testing/enzyme-portals.ts +279 -0
  231. package/src/testing/enzyme-selector-names.ts +59 -0
  232. package/src/testing/enzyme-to-react-testing-library.ts +517 -57
  233. package/src/testing/enzyme-usage.ts +29 -4
  234. package/src/testing/enzyme-wrapper-scope.ts +186 -30
  235. package/src/util/java-recipe-proxy.ts +94 -0
  236. package/src/util/module-imports.ts +6 -1
  237. package/src/util/reindent.ts +35 -0
  238. package/src/zustand/redux-stores.ts +409 -0
  239. package/src/zustand/redux-to-zustand.ts +657 -0
  240. package/src/zustand/zustand-plan.ts +843 -0
  241. package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
  242. package/dist/react18/remove-unstable-batched-updates.js +0 -170
  243. package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
  244. package/src/react18/remove-unstable-batched-updates.ts +0 -192
@@ -0,0 +1,843 @@
1
+ import {Cursor, ExecutionContext} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, JS, JSX, namesReferencedWithin} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {posix} from "path";
5
+ import {ImportBinding, importBindings, isRelativeSpecifier, resolveRelative} from "../util/module-imports";
6
+ import {Finding, localSlices, objectProperties, RTK, SliceFacts, SliceModule, storeFindings, storeFunctions, TEST_SOURCE} from "./redux-stores";
7
+
8
+ export const REACT_REDUX = "react-redux";
9
+
10
+ /** How a source uses a name it imports, as far as a conversion to zustand needs to know. */
11
+ export type UseKind =
12
+ /** `x` is the action creator called in `dispatch(x(...))` or `store.dispatch(x(...))`, whose result is unused. */
13
+ "dispatched" |
14
+ /** `store` in `<Provider store={store}>` with no other prop and one element child. */
15
+ "provider" |
16
+ /** `store` in `store.getState().key...`. */
17
+ "getState" |
18
+ /** `store` in `store.dispatch(x(...))`, whose result is unused. */
19
+ "storeDispatch" |
20
+ /** `useSelector(state => state.key...)`, a read of one slice's state. */
21
+ "selector" |
22
+ /** `const dispatch = useDispatch()`, each of whose uses dispatches an imported action creator. */
23
+ "dispatcher" |
24
+ /** The `Provider` tag itself. */
25
+ "providerTag" |
26
+ /** Anything else, which keeps the store from converting. */
27
+ "other";
28
+
29
+ export interface Use {
30
+ local: string;
31
+ kind: UseKind;
32
+ /** The slice key a selector or `getState()` read starts with. */
33
+ key?: string;
34
+ /** For `dispatched`, the import the dispatch goes through: a dispatcher from `useDispatch`, or the store. */
35
+ via?: string;
36
+ /** What `other` was, for the review row. */
37
+ detail?: string;
38
+ /** The reason an `other` use is recorded under, when it is more precise than the kind of import it uses. */
39
+ reason?: string;
40
+ }
41
+
42
+ /** What one source tells the plan. */
43
+ export interface SourceFacts {
44
+ path: string;
45
+ typescript: boolean;
46
+ test: boolean;
47
+ bindings: ImportBinding[];
48
+ /** The names the source declares other than by importing them, which a name it imports must not be. */
49
+ declared: ReadonlySet<string>;
50
+ uses: Use[];
51
+ /** Imports and re-exports the uses can't follow: namespace imports, `export ... from`, `require` and module mocks, by module. */
52
+ unfollowed: {module: string, detail: string}[];
53
+ /** The Redux stores the source creates. */
54
+ stores: StoreFacts[];
55
+ }
56
+
57
+ export interface StoreFacts {
58
+ path: string;
59
+ api: string;
60
+ store: string;
61
+ findings: Finding[];
62
+ slices: Map<string, SliceFacts>;
63
+ /** The name the store module exports the store as, `default`, or undefined when it isn't exported at the top level. */
64
+ exportedAs?: string;
65
+ }
66
+
67
+ /** The parent tree of the node at `cursor`, past paddings and containers. */
68
+ export function parentTree(cursor: Cursor): J | undefined {
69
+ for (let c = cursor.parent; c; c = c.parent) {
70
+ const value = c.value as J;
71
+ if (value && typeof value === "object" && "kind" in value && typeof value.kind === "string" && !value.kind.endsWith("RightPadded") &&
72
+ !value.kind.endsWith("LeftPadded") && !value.kind.endsWith("Container")) return value;
73
+ }
74
+ return undefined;
75
+ }
76
+
77
+ function ancestors(cursor: Cursor): J[] {
78
+ const trees: J[] = [];
79
+ for (let c: Cursor | undefined = cursor; c; c = c.parent) {
80
+ const value = c.value as J;
81
+ if (value && typeof value === "object" && "kind" in value && typeof value.kind === "string" && !/Padded$|Container$/.test(value.kind)) trees.push(value);
82
+ }
83
+ return trees;
84
+ }
85
+
86
+ const STATEMENT_PARENTS = new Set<string>([J.Kind.Block, J.Kind.If, J.Kind.IfElse, J.Kind.WhileLoop, J.Kind.DoWhileLoop, J.Kind.ForLoop,
87
+ J.Kind.ForEachLoop, J.Kind.Case, JS.Kind.CompilationUnit]);
88
+
89
+ /** Whether the call `node`, whose parent is `parent`, is a statement of its own, so that its result is unused. */
90
+ export function isStatement(node: J, parent: J | undefined): boolean {
91
+ if (!parent) return false;
92
+ if (parent.kind === JS.Kind.ExpressionStatement) return true;
93
+ if (parent.kind === J.Kind.Lambda && (parent as J.Lambda).body === node) return false;
94
+ return STATEMENT_PARENTS.has(parent.kind);
95
+ }
96
+
97
+ /** React's hooks whose last argument lists the values they depend on. */
98
+ const DEPENDENCY_HOOKS = new Set(["useEffect", "useLayoutEffect", "useInsertionEffect", "useCallback", "useMemo", "useImperativeHandle"]);
99
+
100
+ /**
101
+ * Whether `array`, an argument of `call`, is the dependency list of one of React's hooks, `useEffect(f, [a])` or
102
+ * `React.useEffect(f, [a])`, which `react`, the source's imports of React, import.
103
+ */
104
+ export function isReactDependencies(array: J, call: J | undefined, react: readonly ImportBinding[]): boolean {
105
+ if (array.kind !== J.Kind.NewArray || call?.kind !== J.Kind.MethodInvocation) return false;
106
+ const invocation = call as J.MethodInvocation;
107
+ const args = argumentsOf(invocation);
108
+ const name = invocation.name.simpleName;
109
+ if (args.length < 2 || args[args.length - 1] !== array || !DEPENDENCY_HOOKS.has(name)) return false;
110
+ if (!invocation.select) return react.some(binding => binding.module === "react" && binding.local === name && binding.name === name);
111
+ const select = invocation.select.element;
112
+ return isIdentifier(select) && react.some(binding => binding.module === "react" && binding.local === select.simpleName && binding.name === "default");
113
+ }
114
+
115
+ /** The arguments of a call, without the empty one of `f()`. */
116
+ export function argumentsOf(call: J.MethodInvocation): J[] {
117
+ return call.arguments.elements.map(arg => arg.element).filter(arg => arg.kind !== J.Kind.Empty);
118
+ }
119
+
120
+ /** The lambda of an arrow function or a lambda. */
121
+ export function lambdaOf(node: J | undefined): J.Lambda | undefined {
122
+ if (node?.kind === JS.Kind.ArrowFunction) return (node as JS.ArrowFunction).lambda;
123
+ return node?.kind === J.Kind.Lambda ? node as J.Lambda : undefined;
124
+ }
125
+
126
+ /**
127
+ * The innermost read of `state.key...` in a selector `state => state.key...`: the field access whose target is the
128
+ * parameter, with the key it names. Undefined unless the body is a chain of property reads and literal indexes on
129
+ * the parameter alone.
130
+ */
131
+ export function selectorRead(node: J | undefined): {key: string, read: J.FieldAccess, lambda: J.Lambda} | undefined {
132
+ const lambda = lambdaOf(node);
133
+ if (!lambda || (node!.kind === JS.Kind.ArrowFunction && ((node as JS.ArrowFunction).modifiers.length > 0 || (node as JS.ArrowFunction).returnTypeExpression))) return undefined;
134
+ const parameters = lambda.parameters.parameters.map(p => p.element).filter(p => p.kind !== J.Kind.Empty);
135
+ const parameter = parameters.length === 1 ? parameterName(parameters[0]) : undefined;
136
+ if (!parameter) return undefined;
137
+ let expression = lambda.body as J;
138
+ let read: J.FieldAccess | undefined;
139
+ for (; ;) {
140
+ if (expression.kind === J.Kind.FieldAccess) {
141
+ const access = expression as J.FieldAccess;
142
+ if (isIdentifier(access.target) && access.target.simpleName === parameter) {
143
+ read = access;
144
+ break;
145
+ }
146
+ expression = access.target;
147
+ } else if (expression.kind === J.Kind.ArrayAccess) {
148
+ const access = expression as J.ArrayAccess;
149
+ if (access.dimension.index.element.kind !== J.Kind.Literal) return undefined;
150
+ expression = access.indexed;
151
+ } else return undefined;
152
+ }
153
+ return {key: read.name.element.simpleName, read, lambda};
154
+ }
155
+
156
+ /** The name of a plain parameter, `state` but not `{a}`, `state = {}` or `state: State`. */
157
+ export function parameterName(node: J): string | undefined {
158
+ if (isIdentifier(node)) return node.simpleName;
159
+ if (node.kind !== J.Kind.VariableDeclarations) return undefined;
160
+ const declarations = node as J.VariableDeclarations;
161
+ const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
162
+ return variable && !declarations.typeExpression && !declarations.varargs && !variable.initializer && isIdentifier(variable.name) ? variable.name.simpleName : undefined;
163
+ }
164
+
165
+ /** `store.getState().key`, the read of one slice's state, for a call `getState()` whose parent is `parent`. */
166
+ export function getStateRead(call: J.MethodInvocation, parent: J | undefined): {key: string, read: J.FieldAccess} | undefined {
167
+ if (call.name.simpleName !== "getState" || argumentsOf(call).length > 0) return undefined;
168
+ if (parent?.kind !== J.Kind.FieldAccess || (parent as J.FieldAccess).target !== call) return undefined;
169
+ return {key: (parent as J.FieldAccess).name.element.simpleName, read: parent as J.FieldAccess};
170
+ }
171
+
172
+ /** The callee of the one argument of `dispatch(x(...))`, when that argument is a call of a name. */
173
+ export function dispatchedAction(call: J.MethodInvocation): J.MethodInvocation | undefined {
174
+ const args = argumentsOf(call);
175
+ if (args.length !== 1 || args[0].kind !== J.Kind.MethodInvocation) return undefined;
176
+ const action = args[0] as J.MethodInvocation;
177
+ return action.select ? undefined : action;
178
+ }
179
+
180
+ /** The names a source declares, other than by importing them: variables, parameters, functions and classes. */
181
+ function declaredNames(cu: JS.CompilationUnit): Map<string, number> {
182
+ const names = new Map<string, number>();
183
+ const count = (name: string) => names.set(name, (names.get(name) ?? 0) + 1);
184
+ walk(cu, node => {
185
+ if (node.kind === JS.Kind.Import) return false;
186
+ if (node.kind === J.Kind.NamedVariable && isIdentifier((node as J.VariableDeclarations.NamedVariable).name)) count(((node as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName);
187
+ if (node.kind === JS.Kind.BindingElement && isIdentifier((node as JS.BindingElement).name)) count(((node as JS.BindingElement).name as J.Identifier).simpleName);
188
+ if (node.kind === J.Kind.MethodDeclaration) count((node as J.MethodDeclaration).name.simpleName);
189
+ if (node.kind === J.Kind.ClassDeclaration) count((node as J.ClassDeclaration).name.simpleName);
190
+ if (node.kind === J.Kind.LambdaParameters) {
191
+ for (const {element} of (node as J.Lambda.Parameters).parameters) if (isIdentifier(element)) count(element.simpleName);
192
+ }
193
+ return true;
194
+ });
195
+ return names;
196
+ }
197
+
198
+ /** Calls `visit` on every tree below `node`, descending while it returns true. */
199
+ export function walk(node: unknown, visit: (tree: J) => boolean): void {
200
+ if (!node || typeof node !== "object") return;
201
+ if (Array.isArray(node)) {
202
+ for (const element of node) walk(element, visit);
203
+ return;
204
+ }
205
+ const value = node as Record<string, unknown>;
206
+ if (typeof value.kind === "string" && /\.tree\.JS?X?\$/.test(value.kind) && !visit(value as unknown as J)) return;
207
+ for (const [key, child] of Object.entries(value)) {
208
+ if (SKIPPED.has(key)) continue;
209
+ if (child && typeof child === "object") walk(child, visit);
210
+ }
211
+ }
212
+
213
+ const SKIPPED = new Set(["markers", "prefix", "type", "methodType", "fieldType", "variableType", "constructorType", "javaType", "before", "after"]);
214
+
215
+ /** The facts of one source, read once while scanning. */
216
+ export async function sourceFacts(cu: JS.CompilationUnit): Promise<SourceFacts> {
217
+ const bindings = importBindings(cu);
218
+ const declared = declaredNames(cu);
219
+ const facts: SourceFacts = {
220
+ path: cu.sourcePath, typescript: /\.(?:ts|tsx|mts|cts)$/.test(cu.sourcePath), test: TEST_SOURCE.test(cu.sourcePath),
221
+ bindings, declared: new Set(declared.keys()), uses: [], unfollowed: [], stores: []
222
+ };
223
+ const followed = new Map(bindings.filter(binding => binding.module === REACT_REDUX || isRelativeSpecifier(binding.module))
224
+ .map(binding => [binding.local, binding]));
225
+ for (const {element} of cu.statements) {
226
+ if (element.kind === JS.Kind.Import) {
227
+ const imp = element as JS.Import;
228
+ const specifier = imp.moduleSpecifier?.element;
229
+ const module = specifier?.kind === J.Kind.Literal ? String((specifier as J.Literal).value) : "";
230
+ if (imp.importClause?.namedBindings?.kind === JS.Kind.Alias) facts.unfollowed.push({module, detail: "namespace import"});
231
+ // An import for its side effects only, which a removed store's source would leave unresolved
232
+ if (!imp.importClause && module) facts.unfollowed.push({module, detail: "import for side effects"});
233
+ }
234
+ if (element.kind === JS.Kind.ExportDeclaration) {
235
+ const specifier = (element as JS.ExportDeclaration).moduleSpecifier?.element;
236
+ if (specifier?.kind === J.Kind.Literal) facts.unfollowed.push({module: String((specifier as J.Literal).value), detail: "re-export"});
237
+ }
238
+ }
239
+ const dispatchers = new Set<string>();
240
+ const collector = new class extends JavaScriptVisitor<ExecutionContext> {
241
+ override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
242
+ // `require('react-redux')`, `jest.mock('./store')` and `import('./store')` load a module the uses can't follow
243
+ const first = argumentsOf(call)[0];
244
+ if (first?.kind === J.Kind.Literal && typeof (first as J.Literal).value === "string" &&
245
+ (!call.select && call.name.simpleName === "require" ||
246
+ ["mock", "doMock", "unmock", "requireActual"].includes(call.name.simpleName) && call.select)) {
247
+ facts.unfollowed.push({module: String((first as J.Literal).value), detail: call.name.simpleName});
248
+ }
249
+ return super.visitMethodInvocation(call, ctx);
250
+ }
251
+
252
+ override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
253
+ const binding = followed.get(identifier.simpleName);
254
+ if (!binding && dispatchers.has(identifier.simpleName)) {
255
+ const use = dispatcherUse(identifier, this.cursor, followed, bindings);
256
+ if (use) facts.uses.push(use);
257
+ }
258
+ if (binding) {
259
+ const use = classify(identifier, binding, this.cursor, followed, dispatchers, declared);
260
+ if (use) facts.uses.push(use);
261
+ }
262
+ return identifier;
263
+ }
264
+ }();
265
+ // Dispatchers are found first, as a component declares its dispatcher before it uses it
266
+ walkDispatchers(cu, followed, dispatchers);
267
+ await collector.visit(cu, new ExecutionContext());
268
+ for (const name of dispatchers) {
269
+ if ((declared.get(name) ?? 0) > dispatcherCount(cu, followed, name)) facts.uses.push({local: name, kind: "other", detail: `\`${name}\` is declared otherwise too`});
270
+ }
271
+ for (const [local] of followed) {
272
+ if (declared.has(local)) facts.uses.push({local, kind: "other", detail: `\`${local}\` is shadowed`});
273
+ }
274
+ return facts;
275
+ }
276
+
277
+ /** The Redux stores `cu` creates, read once every slice of the repository is known. */
278
+ export async function storeFacts(cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule>): Promise<StoreFacts[]> {
279
+ const stores: StoreFacts[] = [];
280
+ const functions = storeFunctions(cu);
281
+ if (functions.legacy.size === 0 && functions.configure.size === 0) return stores;
282
+ await new class extends JavaScriptVisitor<ExecutionContext> {
283
+ override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
284
+ const store = storeFindings(call, cu, modules, functions);
285
+ if (store) {
286
+ stores.push({path: cu.sourcePath, api: store.api, store: storeNameAt(this.cursor), findings: store.findings,
287
+ slices: store.slices, exportedAs: exportedStore(cu, this.cursor)});
288
+ }
289
+ return super.visitMethodInvocation(call, ctx);
290
+ }
291
+ }().visit(cu, new ExecutionContext());
292
+ return stores;
293
+ }
294
+
295
+ /** `const dispatch = useDispatch()`: whether `variable` declares a dispatcher of the `useDispatch` that `followed` imports. */
296
+ export function isDispatcherDeclaration(variable: J.VariableDeclarations.NamedVariable, followed: ReadonlyMap<string, ImportBinding>): boolean {
297
+ const init = variable.initializer?.element;
298
+ if (!isIdentifier(variable.name) || init?.kind !== J.Kind.MethodInvocation) return false;
299
+ const call = init as J.MethodInvocation;
300
+ const binding = followed.get(call.name.simpleName);
301
+ return !call.select && binding?.module === REACT_REDUX && binding.name === "useDispatch" && argumentsOf(call).length === 0 && !call.typeParameters;
302
+ }
303
+
304
+ function walkDispatchers(cu: JS.CompilationUnit, followed: ReadonlyMap<string, ImportBinding>, dispatchers: Set<string>): void {
305
+ walk(cu, node => {
306
+ if (node.kind === J.Kind.VariableDeclarations) {
307
+ const declarations = node as J.VariableDeclarations;
308
+ for (const {element} of declarations.variables) {
309
+ if (isDispatcherDeclaration(element, followed) && declarations.variables.length === 1) dispatchers.add((element.name as J.Identifier).simpleName);
310
+ }
311
+ }
312
+ return true;
313
+ });
314
+ }
315
+
316
+ function dispatcherCount(cu: JS.CompilationUnit, followed: ReadonlyMap<string, ImportBinding>, name: string): number {
317
+ let count = 0;
318
+ walk(cu, node => {
319
+ if (node.kind === J.Kind.NamedVariable && isDispatcherDeclaration(node as J.VariableDeclarations.NamedVariable, followed) &&
320
+ ((node as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName === name) count++;
321
+ return true;
322
+ });
323
+ return count;
324
+ }
325
+
326
+ /** How the identifier at `cursor`, which names the import `binding`, is used; undefined where it is no use, such as a property name. */
327
+ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Cursor, followed: ReadonlyMap<string, ImportBinding>,
328
+ dispatchers: ReadonlySet<string>, declared: ReadonlyMap<string, number>): Use | undefined {
329
+ const trees = ancestors(cursor);
330
+ if (trees.some(tree => tree.kind === JS.Kind.Import)) return undefined;
331
+ const parent = parentTree(cursor);
332
+ const local = identifier.simpleName;
333
+ const other = (detail: string): Use => ({local, kind: "other", detail});
334
+ // Names of members, properties and attributes are no use of the import
335
+ if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).name.element === identifier) return undefined;
336
+ if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier && (parent as J.MethodInvocation).select) return undefined;
337
+ if (parent?.kind === JS.Kind.JsxAttribute && (parent as JSX.Attribute).key === identifier) return undefined;
338
+ if (parent?.kind === JS.Kind.PropertyAssignment && (parent as JS.PropertyAssignment).name.element === identifier &&
339
+ (parent as JS.PropertyAssignment).initializer) return undefined;
340
+ if (parent?.kind === J.Kind.MethodDeclaration && (parent as J.MethodDeclaration).name === identifier) return undefined;
341
+ if (parent?.kind === JS.Kind.JsxTag) {
342
+ const tag = parent as JSX.Tag;
343
+ if (tag.closingName?.element === identifier) return undefined;
344
+ if (tag.openName.element !== identifier) return other("JSX");
345
+ if (binding.module !== REACT_REDUX || binding.name !== "Provider") return undefined;
346
+ return providerUse(tag, followed, local);
347
+ }
348
+ if (binding.module === REACT_REDUX) {
349
+ if (parent?.kind !== J.Kind.MethodInvocation || (parent as J.MethodInvocation).name !== identifier) return other(`\`${binding.name}\` from react-redux`);
350
+ const call = parent as J.MethodInvocation;
351
+ if (binding.name === "useSelector") {
352
+ const args = argumentsOf(call);
353
+ const read = args.length === 1 && !call.typeParameters ? selectorRead(args[0]) : undefined;
354
+ return read ? {local, kind: "selector", key: read.key} : {...other("a selector that isn't a read of one slice's state"), reason: "SELECTOR"};
355
+ }
356
+ if (binding.name === "useDispatch") {
357
+ const variable = parentTree(cursorOf(cursor, call));
358
+ return variable?.kind === J.Kind.NamedVariable && dispatchers.has(((variable as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName)
359
+ ? {local, kind: "dispatcher"} : other("`useDispatch` not held in a variable of its own");
360
+ }
361
+ return other(`\`${binding.name}\` from react-redux`);
362
+ }
363
+ // A relative import: an action creator, the store, a slice or anything else of the repository
364
+ if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier) {
365
+ const action = parent as J.MethodInvocation;
366
+ const dispatch = parentTree(cursorOf(cursor, action));
367
+ if (dispatch?.kind !== J.Kind.MethodInvocation || dispatchedAction(dispatch as J.MethodInvocation) !== action) return other("called outside a dispatch");
368
+ const call = dispatch as J.MethodInvocation;
369
+ const via = call.select ? isIdentifier(call.select.element) && call.name.simpleName === "dispatch" ? call.select.element.simpleName : undefined :
370
+ dispatchers.has(call.name.simpleName) ? call.name.simpleName : undefined;
371
+ if (!via) return other("passed to a call that isn't a dispatch");
372
+ if (!isStatement(call, parentTree(cursorOf(cursor, call)))) return {...other("the dispatch's result is used"), reason: "DISPATCH"};
373
+ return {local, kind: "dispatched", via};
374
+ }
375
+ if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).select?.element === identifier) {
376
+ const call = parent as J.MethodInvocation;
377
+ const outer = parentTree(cursorOf(cursor, call));
378
+ const read = getStateRead(call, outer);
379
+ if (read) return {local, kind: "getState", key: read.key};
380
+ if (call.name.simpleName === "dispatch" && dispatchedAction(call)) {
381
+ return isStatement(call, outer) ? {local, kind: "storeDispatch"} : {...other("the dispatch's result is used"), reason: "DISPATCH"};
382
+ }
383
+ return other(`\`${local}.${call.name.simpleName}\``);
384
+ }
385
+ if (parent?.kind === JS.Kind.JsxEmbeddedExpression) {
386
+ const attribute = trees[2];
387
+ const tag = trees[3];
388
+ if (attribute?.kind === JS.Kind.JsxAttribute && tag?.kind === JS.Kind.JsxTag && isIdentifier((attribute as JSX.Attribute).key) &&
389
+ ((attribute as JSX.Attribute).key as J.Identifier).simpleName === "store") {
390
+ const name = (tag as JSX.Tag).openName.element;
391
+ const provider = isIdentifier(name) ? followed.get(name.simpleName) : undefined;
392
+ if (provider?.module === REACT_REDUX && provider.name === "Provider") return {local, kind: "provider"};
393
+ }
394
+ }
395
+ return other("referenced");
396
+ }
397
+
398
+ /** A use of a dispatcher from `useDispatch`: only `dispatch(x(...))` of an imported `x`, whose result is unused, converts. */
399
+ function dispatcherUse(identifier: J.Identifier, cursor: Cursor, followed: ReadonlyMap<string, ImportBinding>,
400
+ bindings: readonly ImportBinding[]): Use | undefined {
401
+ const parent = parentTree(cursor);
402
+ const local = identifier.simpleName;
403
+ // `useDispatch` returns the store's own `dispatch`, which never changes, so a hook listing it never reruns for it
404
+ if (parent && isReactDependencies(parent, parentTree(cursorOf(cursor, parent)), bindings)) return undefined;
405
+ if (parent?.kind === J.Kind.NamedVariable && (parent as J.VariableDeclarations.NamedVariable).name === identifier) return undefined;
406
+ if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).name.element === identifier) return undefined;
407
+ if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier && !(parent as J.MethodInvocation).select) {
408
+ const call = parent as J.MethodInvocation;
409
+ const action = dispatchedAction(call);
410
+ const binding = action && followed.get(action.name.simpleName);
411
+ if (binding && binding.module !== REACT_REDUX) return undefined;
412
+ return {local, kind: "other", detail: "dispatches what isn't an imported action creator", reason: "DISPATCH"};
413
+ }
414
+ return {local, kind: "other", detail: "the dispatcher is used other than to dispatch", reason: "DISPATCH"};
415
+ }
416
+
417
+ /** `<Provider store={store}>` with one element child and no other prop. */
418
+ function providerUse(tag: JSX.Tag, followed: ReadonlyMap<string, ImportBinding>, local: string): Use {
419
+ const other = (detail: string): Use => ({local, kind: "other", detail});
420
+ const attributes = tag.attributes.map(a => a.element);
421
+ if (attributes.length !== 1 || attributes[0].kind !== JS.Kind.JsxAttribute) return other("`Provider` with props other than `store`");
422
+ const value = (attributes[0] as JSX.Attribute).value?.element;
423
+ const expression = value?.kind === JS.Kind.JsxEmbeddedExpression ? (value as JSX.EmbeddedExpression).expression.element : undefined;
424
+ if (!isIdentifier(expression) || !followed.has(expression.simpleName)) return other("`Provider` of a store that isn't imported");
425
+ if (!providerChild(tag)) return other("`Provider` without exactly one element child");
426
+ return {local, kind: "providerTag"};
427
+ }
428
+
429
+ /** The one element child of a tag, with only whitespace around it. */
430
+ export function providerChild(tag: JSX.Tag): JSX.Tag | undefined {
431
+ const children = (tag.children ?? []).filter(child => !(child.kind === J.Kind.Literal && String((child as J.Literal).value ?? "").trim() === "") &&
432
+ child.kind !== J.Kind.Empty);
433
+ return children.length === 1 && children[0].kind === JS.Kind.JsxTag ? children[0] as JSX.Tag : undefined;
434
+ }
435
+
436
+ /** A cursor whose value is `node`, an ancestor of the value of `cursor`. */
437
+ function cursorOf(cursor: Cursor, node: J): Cursor {
438
+ for (let c: Cursor | undefined = cursor; c; c = c.parent) if (c.value === node) return c;
439
+ return cursor;
440
+ }
441
+
442
+ function storeNameAt(cursor: Cursor): string {
443
+ for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
444
+ const node = c.value as J;
445
+ if (node?.kind === J.Kind.NamedVariable && isIdentifier((node as J.VariableDeclarations.NamedVariable).name)) {
446
+ return ((node as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName;
447
+ }
448
+ if (node?.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
449
+ }
450
+ return "<module>";
451
+ }
452
+
453
+ /**
454
+ * The name a store module exports the store created at `cursor` as: `default` for `export default configureStore(...)`
455
+ * or a default export of its variable, or the variable's name for `export const store = configureStore(...)`.
456
+ * Undefined unless the store is created by a top-level statement.
457
+ */
458
+ function exportedStore(cu: JS.CompilationUnit, cursor: Cursor): string | undefined {
459
+ const statement = cu.statements.map(s => s.element).find(s => ancestors(cursor).includes(s));
460
+ if (!statement) return undefined;
461
+ if (statement.kind === JS.Kind.ExportAssignment) {
462
+ return (statement as JS.ExportAssignment).expression.element === cursor.value ? "default" : undefined;
463
+ }
464
+ if (statement.kind !== J.Kind.VariableDeclarations) return undefined;
465
+ const declarations = statement as J.VariableDeclarations;
466
+ const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
467
+ if (!variable || variable.initializer?.element !== cursor.value || !isIdentifier(variable.name)) return undefined;
468
+ const name = variable.name.simpleName;
469
+ if (declarations.modifiers.some(m => m.keyword === "export")) return name;
470
+ const exported = cu.statements.map(s => s.element).find(s => s.kind === JS.Kind.ExportAssignment &&
471
+ isIdentifier((s as JS.ExportAssignment).expression.element) && ((s as JS.ExportAssignment).expression.element as J.Identifier).simpleName === name);
472
+ return exported ? "default" : undefined;
473
+ }
474
+
475
+ /** A slice of the store, with what the conversion writes for it. */
476
+ export interface PlannedSlice extends SliceFacts {
477
+ key: string;
478
+ hook: string;
479
+ reducers: string;
480
+ action: string;
481
+ /** The reducer names the slice exports action creators for. */
482
+ actions: Set<string>;
483
+ /** The names it exports from `slice.actions` that no reducer has, which are `undefined` in RTK too. */
484
+ unknown: Set<string>;
485
+ /** The `createAsyncThunk`s whose stages `extraReducers` handle, each with the name RTK's thunk is kept under. */
486
+ thunkVariables: Map<string, string>;
487
+ /** The object of `extraReducers` cases by action type, and the function that dispatches a thunk's actions to them. */
488
+ caseObject: string;
489
+ dispatch: string;
490
+ }
491
+
492
+ export interface Plan {
493
+ /** The store that converts, or undefined when none does. */
494
+ store?: StoreFacts;
495
+ slices: Map<string, PlannedSlice>;
496
+ /** The sources that change: the store's, the slices' and every source using them. */
497
+ sources: Set<string>;
498
+ /** Why each store doesn't convert, by store; the converting store has no entry. */
499
+ blocked: Map<StoreFacts, Finding[]>;
500
+ }
501
+
502
+ /** The hook a slice under `key` becomes, such as `useCounterStore` for `counter`. */
503
+ export const hookName = (key: string) => `use${key.charAt(0).toUpperCase()}${key.slice(1)}Store`;
504
+
505
+ /**
506
+ * Decides which store converts: the repository's one store, when it is a candidate, its sources are JavaScript, its
507
+ * slices can be rewritten, and every use of the store, its slices, their action creators and react-redux converts.
508
+ */
509
+ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>,
510
+ dependencies: (storePath: string) => Finding | undefined, scope: (path: string) => boolean = () => true): Plan {
511
+ const stores = [...facts.values()].filter(source => scope(source.path)).flatMap(source => source.stores);
512
+ const result: Plan = {slices: new Map(), sources: new Set(), blocked: new Map()};
513
+ if (stores.length === 0) return result;
514
+ if (stores.length > 1) {
515
+ for (const store of stores) result.blocked.set(store, [...store.findings, {reason: "MULTIPLE_STORES", detail: `${stores.length} stores`}]);
516
+ return result;
517
+ }
518
+ const store = stores[0];
519
+ const findings: Finding[] = [...store.findings];
520
+ const block = (reason: string, detail: string) => findings.push({reason, detail});
521
+ // Slices that stay in Redux for a reason of their own, already recorded: their uses add nothing to it
522
+ const held = new Map<string, string>();
523
+ if (findings.length === 0) {
524
+ if (!store.exportedAs) block("STORE_NOT_MODULE_LEVEL", store.store);
525
+ const storeSource = sliceSources.get(store.path);
526
+ if (storeSource && !storeSource.storeOnly) block("STORE_SOURCE", "the store's source declares more than the store");
527
+ const dependency = dependencies(store.path);
528
+ if (dependency) findings.push(dependency);
529
+ for (const [key, slice] of store.slices) {
530
+ const source = sliceSources.get(slice.path);
531
+ const reducers = source?.slices.get(slice.variable);
532
+ if (!source || !reducers) {
533
+ block("SLICE_SOURCE", key);
534
+ continue;
535
+ }
536
+ if (reducers.blocker) {
537
+ findings.push(reducers.blocker);
538
+ held.set(key, slice.path);
539
+ continue;
540
+ }
541
+ const hook = hookName(key);
542
+ // The helpers are the slice source's own, so a name it already has, such as an action's, gives way to another
543
+ const free = (...names: string[]) => names.find(name => !source.names.has(name) && name !== hook) ?? names[0];
544
+ const planned: PlannedSlice = {...slice, key, hook, reducers: free(`${key}Reducers`, `${key}SliceReducers`),
545
+ action: free(`${key}Action`, `${key}SliceAction`), actions: reducers.actions, unknown: reducers.unknown,
546
+ thunkVariables: new Map([...reducers.thunks].map(thunk => [thunk, free(`${thunk}Thunk`, `${thunk}AsyncThunk`)])),
547
+ caseObject: free(`${key}Cases`, `${key}SliceCases`), dispatch: free(`${key}Dispatch`, `${key}SliceDispatch`)};
548
+ if (!/^[A-Za-z_$][\w$]*$/.test(key)) block("SLICE_KEY", key);
549
+ const thunkNames = planned.thunkVariables.size > 0 ? [planned.caseObject, planned.dispatch, ...planned.thunkVariables.values()] : [];
550
+ for (const name of [hook, planned.reducers, planned.action, "create", "produce", "freeze", ...thunkNames]) {
551
+ if (source.names.has(name)) block("NAME_TAKEN", `${name} in ${slice.path}`);
552
+ }
553
+ if ([...result.slices.values()].some(other => other.path === slice.path)) block("SLICE_SOURCE", `${key} shares its source with another slice`);
554
+ // The other package's own uses of the slice aren't planned here
555
+ if (!scope(slice.path)) block("SLICE_SOURCE", `${key} is declared in another package, ${slice.path}`);
556
+ result.slices.set(key, planned);
557
+ }
558
+ }
559
+ const slicePaths = new Map([...result.slices.values()].map(slice => [slice.path, slice]));
560
+ const sources = new Set<string>([store.path, ...slicePaths.keys()]);
561
+ for (const source of facts.values()) {
562
+ const resolve = (module: string) => resolveRelative(source.path, module, facts);
563
+ const touches = (module: string) => {
564
+ const path = resolve(module);
565
+ return path === store.path || (path !== undefined && slicePaths.has(path));
566
+ };
567
+ if (!scope(source.path)) {
568
+ // A source of another package, whose package isn't converted with this one, may use the store only not at all
569
+ for (const binding of source.bindings) {
570
+ const path = binding.module === REACT_REDUX ? undefined : resolve(binding.module);
571
+ if (path === store.path) block("STORE_USE", `${binding.local} in ${source.path}, of another package`);
572
+ else if (path !== undefined && slicePaths.has(path)) block("SLICE_USE", `${binding.local} in ${source.path}, of another package`);
573
+ }
574
+ for (const {module, detail} of source.unfollowed) {
575
+ if (touches(module)) block("UNFOLLOWED_IMPORT", `${detail} of ${module} in ${source.path}, of another package`);
576
+ }
577
+ continue;
578
+ }
579
+ for (const {module, detail} of source.unfollowed) {
580
+ if (module === REACT_REDUX || touches(module)) block("UNFOLLOWED_IMPORT", `${detail} of ${module} in ${source.path}`);
581
+ }
582
+ // An export without a reducer converts to `undefined` only while nothing imports it
583
+ for (const binding of source.bindings) {
584
+ const path = binding.module === REACT_REDUX ? undefined : resolve(binding.module);
585
+ const slice = path !== undefined ? slicePaths.get(path) : undefined;
586
+ if (slice?.unknown.has(binding.name)) block("UNKNOWN_ACTION", `${binding.local} in ${source.path}: \`${binding.name}\` is no reducer of the slice`);
587
+ }
588
+ let changes = false;
589
+ for (const use of source.uses) {
590
+ const binding = source.bindings.find(b => b.local === use.local);
591
+ const path = binding && binding.module !== REACT_REDUX ? resolve(binding.module) : undefined;
592
+ const isStore = path === store.path && binding?.name === store.exportedAs;
593
+ const slice = path !== undefined ? slicePaths.get(path) : undefined;
594
+ const isReactRedux = binding?.module === REACT_REDUX || !binding;
595
+ // A dispatch of anything but an action creator, such as a thunk, is the store's use however it's imported
596
+ if (!isReactRedux && !isStore && !slice && path !== store.path && use.kind !== "dispatched") continue;
597
+ if (path !== undefined && [...held.values()].includes(path) || (use.kind === "selector" || use.kind === "getState") && held.has(use.key!)) continue;
598
+ // The store's source goes, with its imports of the slices' reducers
599
+ if (source.path === store.path && slice && use.kind === "other") continue;
600
+ changes = true;
601
+ const where = `${use.local} in ${source.path}`;
602
+ if (use.kind === "other") {
603
+ block(use.reason ?? (isStore ? "STORE_USE" : slice ? "SLICE_USE" : !binding ? "DISPATCH" : isReactRedux ? "REACT_REDUX_USE" : "STORE_USE"), `${where}: ${use.detail}`);
604
+ } else if (use.kind === "selector" || use.kind === "getState") {
605
+ if (!result.slices.has(use.key!)) block("SELECTOR", `${where} reads \`${use.key}\`, which is no slice of the store`);
606
+ } else if (use.kind === "dispatched") {
607
+ // An import without a reducer is recorded once, as UNKNOWN_ACTION
608
+ if (!slice || !binding || !slice.actions.has(binding.name) && !slice.unknown.has(binding.name) && !slice.thunkVariables.has(binding.name)) block("DISPATCH", `${where} dispatches what isn't an action creator of a slice`);
609
+ const via = source.bindings.find(b => b.local === use.via);
610
+ if (via && !(resolve(via.module) === store.path && via.name === store.exportedAs)) block("DISPATCH", `${where} is dispatched through \`${use.via}\``);
611
+ } else if ((use.kind === "provider" || use.kind === "storeDispatch") && !isStore) {
612
+ block("STORE_USE", `${where} isn't the store`);
613
+ }
614
+ // An `other` use is recorded above with what it was
615
+ if (slice && use.kind !== "dispatched" && use.kind !== "other") block("SLICE_USE", `${where}: ${use.kind}`);
616
+ if (path === store.path && !isStore && source.path !== store.path) block("STORE_USE", `${where} imports more of the store's source`);
617
+ }
618
+ // The store's source is removed, so each import of it goes too, even one nothing uses
619
+ for (const binding of source.bindings) {
620
+ if (source.path === store.path || binding.module === REACT_REDUX || resolve(binding.module) !== store.path) continue;
621
+ changes = true;
622
+ if (binding.name !== store.exportedAs) block("STORE_USE", `${binding.local} in ${source.path} imports more of the store's source`);
623
+ }
624
+ if (changes && source.path !== store.path) {
625
+ if (source.typescript) block("TYPESCRIPT", source.path);
626
+ for (const slice of result.slices.values()) {
627
+ if (source.bindings.some(b => b.local === slice.hook) || source.declared.has(slice.hook)) {
628
+ block("NAME_TAKEN", `${slice.hook} in ${source.path}`);
629
+ }
630
+ }
631
+ sources.add(source.path);
632
+ }
633
+ }
634
+ if ([store.path, ...slicePaths.keys()].some(path => /\.(?:ts|tsx|mts|cts)$/.test(path))) block("TYPESCRIPT", store.path);
635
+ if (findings.length > 0) {
636
+ result.blocked.set(store, dedupe(findings));
637
+ result.slices.clear();
638
+ return result;
639
+ }
640
+ result.store = store;
641
+ result.sources = sources;
642
+ return result;
643
+ }
644
+
645
+ /**
646
+ * A plan for each package that creates a store, by `packageOf`, the root of the package a source is in. A package's
647
+ * one store converts with its own sources; what another package imports of it keeps it in Redux.
648
+ */
649
+ export function planPackages(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>,
650
+ packageOf: (path: string) => string | undefined, dependencies: (storePath: string) => Finding | undefined): Plan[] {
651
+ const root = (path: string) => packageOf(path) ?? "";
652
+ const roots = new Set([...facts.values()].filter(source => source.stores.length > 0).map(source => root(source.path)));
653
+ return [...roots].map(packageRoot => plan(facts, sliceSources, dependencies, path => root(path) === packageRoot));
654
+ }
655
+
656
+ function dedupe(findings: Finding[]): Finding[] {
657
+ const seen = new Set<string>();
658
+ return findings.filter(f => !seen.has(f.reason + "\0" + f.detail) && seen.add(f.reason + "\0" + f.detail));
659
+ }
660
+
661
+ /** A source that declares slices, or the store, as the conversion needs to rewrite it. */
662
+ export interface SliceSource {
663
+ path: string;
664
+ /** The names the source declares or imports, which generated names must not take. */
665
+ names: Set<string>;
666
+ /** Each slice by variable, with the reducers it exports actions for, or why it can't be rewritten. */
667
+ slices: Map<string, {actions: Set<string>, unknown: Set<string>, thunks: Set<string>, blocker?: Finding}>;
668
+ /** Whether the source holds only imports and the store, so that it can be removed. */
669
+ storeOnly: boolean;
670
+ }
671
+
672
+ /** What a source declaring slices, or the store, holds. */
673
+ export function sliceSource(cu: JS.CompilationUnit): SliceSource | undefined {
674
+ const createSlice = new Set(importBindings(cu).filter(b => b.module === RTK && b.name === "createSlice").map(b => b.local));
675
+ const functions = storeFunctions(cu);
676
+ if (createSlice.size === 0 && functions.configure.size === 0) return undefined;
677
+ const names = new Set<string>([...declaredNames(cu).keys(), ...importBindings(cu).map(b => b.local)]);
678
+ const result: SliceSource = {path: cu.sourcePath, names, slices: new Map(), storeOnly: false};
679
+ const local = localSlices(cu);
680
+ const statements = cu.statements.map(s => s.element);
681
+ // The store's source may hold its imports, the store and a default export of the store's variable
682
+ result.storeOnly = statements.every(s => s.kind === JS.Kind.Import || s.kind === JS.Kind.ExportAssignment ||
683
+ s.kind === J.Kind.VariableDeclarations && (s as J.VariableDeclarations).variables.every(v => v.element.initializer?.element.kind === J.Kind.MethodInvocation &&
684
+ functions.configure.has((v.element.initializer.element as J.MethodInvocation).name.simpleName)));
685
+ for (const [variable, facts] of local.localSlices) {
686
+ const slice = {actions: new Set<string>(), unknown: new Set<string>(), thunks: new Set(facts.thunks?.keys()), blocker: facts.blocker} as
687
+ {actions: Set<string>, unknown: Set<string>, thunks: Set<string>, blocker?: Finding};
688
+ result.slices.set(variable, slice);
689
+ if (slice.blocker) continue;
690
+ slice.blocker = sliceBlocker(cu, variable, slice.actions, slice.unknown, slice.thunks, local.localReducers);
691
+ }
692
+ return result;
693
+ }
694
+
695
+ /**
696
+ * Why the slice in `variable` can't be rewritten, filling `actions` with the reducers it exports action creators for,
697
+ * and `unknown` with the names it exports from `slice.actions` that no reducer has.
698
+ */
699
+ function sliceBlocker(cu: JS.CompilationUnit, variable: string, actions: Set<string>, unknown: Set<string>, thunks: ReadonlySet<string>,
700
+ reducerVariables: ReadonlyMap<string, SliceFacts>): Finding | undefined {
701
+ const block = (reason: string, detail: string): Finding => ({reason, detail: `${variable}: ${detail}`});
702
+ const statements = cu.statements.map(s => s.element);
703
+ const declaration = statements.find(s => s.kind === J.Kind.VariableDeclarations &&
704
+ (s as J.VariableDeclarations).variables.some(v => isIdentifier(v.element.name) && v.element.name.simpleName === variable)) as J.VariableDeclarations | undefined;
705
+ if (!declaration || declaration.variables.length !== 1) return block("SLICE_SOURCE", "declared with other variables");
706
+ const call = declaration.variables[0].element.initializer!.element as J.MethodInvocation;
707
+ const options = objectProperties(argumentsOf(call)[0])!;
708
+ for (const key of options.keys()) {
709
+ // `extraReducers` reached here only as cases of the source's own thunks
710
+ if (!["name", "initialState", "reducers", "extraReducers"].includes(key)) return block("SLICE_OPTION", key);
711
+ }
712
+ const name = options.get("name");
713
+ if (name?.kind !== J.Kind.Literal || typeof (name as J.Literal).value !== "string") return block("SLICE_NAME", "the name isn't a string literal");
714
+ const initial = options.get("initialState");
715
+ if (!initial || !isInitialState(initial, statements)) return block("INITIAL_STATE", "the initial state may be a function");
716
+ const reducers = (options.get("reducers") as J.NewClass | undefined)?.body?.statements.map(s => s.element) ?? [];
717
+ const reducerNames = new Set<string>();
718
+ for (const reducer of reducers) {
719
+ let key: string | undefined;
720
+ let value: J | undefined;
721
+ if (reducer.kind === J.Kind.MethodDeclaration) {
722
+ key = (reducer as J.MethodDeclaration).name.simpleName;
723
+ value = reducer;
724
+ } else {
725
+ const property = reducer as JS.PropertyAssignment;
726
+ key = isIdentifier(property.name.element) ? property.name.element.simpleName : undefined;
727
+ value = property.initializer ?? property.name.element;
728
+ }
729
+ if (!key) return block("REDUCER", "a reducer with a computed name");
730
+ if (!isReducerFunction(value!, statements)) return block("REDUCER", `\`${key}\` isn't a function, such as one with \`prepare\``);
731
+ if (usesThis(value!)) return block("REDUCER", `\`${key}\` uses \`this\``);
732
+ reducerNames.add(key);
733
+ }
734
+ // Every reference to the slice must be `slice.actions` destructured into exports, or `slice.reducer`
735
+ // The exported names are collected first, as a statement above their export, such as a thunk, may use them
736
+ const rest: J[] = [];
737
+ for (const statement of statements) {
738
+ if (statement === declaration) continue;
739
+ const actionExport = actionsExport(statement, variable);
740
+ if (!actionExport) {
741
+ rest.push(statement);
742
+ continue;
743
+ }
744
+ for (const element of actionExport) {
745
+ if (!element.plain) return block("ACTIONS_EXPORT", "an action creator exported under another name or with a default");
746
+ (reducerNames.has(element.name) ? actions : unknown).add(element.name);
747
+ }
748
+ }
749
+ // Only a reference counts, not a property's name such as `loading` in `{...state, loading: action.payload}`
750
+ const used = (node: J | undefined) => node &&
751
+ [...namesReferencedWithin(node)].find(n => n === variable || actions.has(n) || unknown.has(n) || thunks.has(n));
752
+ const use = (name: string) => block("SLICE_USE", `\`${name}\` is used in its own source`);
753
+ // A reducer's body, such as one calling `slice.caseReducers`, is a use too
754
+ for (const reducer of reducers) {
755
+ const name = used(reducer.kind === J.Kind.MethodDeclaration ? (reducer as J.MethodDeclaration).body : (reducer as JS.PropertyAssignment).initializer);
756
+ if (name) return use(name);
757
+ }
758
+ for (const statement of rest) {
759
+ if (isReducerExport(statement, variable, reducerVariables)) continue;
760
+ // A thunk's own declaration is no use of it, but its payload creator mustn't use the slice's actions, which create no action once converted
761
+ const thunk = statement.kind === J.Kind.VariableDeclarations ? (statement as J.VariableDeclarations).variables[0]?.element : undefined;
762
+ const declared = thunk && isIdentifier(thunk.name) && thunks.has(thunk.name.simpleName) ? thunk : undefined;
763
+ const name = used(declared ? declared.initializer?.element : statement);
764
+ if (name) return use(name);
765
+ }
766
+ return undefined;
767
+ }
768
+
769
+ /** Whether `node` is an initial state rather than a function that returns one, which RTK calls lazily. */
770
+ function isInitialState(node: J, statements: J[]): boolean {
771
+ if ([J.Kind.Literal, J.Kind.NewClass, J.Kind.NewArray].includes(node.kind as any)) return node.kind !== J.Kind.NewClass || !(node as J.NewClass).class;
772
+ if (!isIdentifier(node)) return false;
773
+ const init = constInitializer(node.simpleName, statements);
774
+ return init !== undefined && init.kind !== JS.Kind.ArrowFunction && init.kind !== J.Kind.Lambda && isInitialState(init, statements);
775
+ }
776
+
777
+ function isReducerFunction(node: J, statements: J[]): boolean {
778
+ if (node.kind === J.Kind.MethodDeclaration || node.kind === JS.Kind.ArrowFunction || node.kind === J.Kind.Lambda) return true;
779
+ if (!isIdentifier(node)) return false;
780
+ const init = constInitializer(node.simpleName, statements);
781
+ if (init) return init.kind === JS.Kind.ArrowFunction || init.kind === J.Kind.Lambda;
782
+ return statements.some(s => s.kind === J.Kind.MethodDeclaration && (s as J.MethodDeclaration).name.simpleName === node.simpleName);
783
+ }
784
+
785
+ /** The initializer of a top-level `const name = ...` of the source. */
786
+ function constInitializer(name: string, statements: J[]): J | undefined {
787
+ for (const statement of statements) {
788
+ if (statement.kind !== J.Kind.VariableDeclarations) continue;
789
+ const declarations = statement as J.VariableDeclarations;
790
+ if (!declarations.modifiers.some(m => m.keyword === "const")) continue;
791
+ for (const {element} of declarations.variables) {
792
+ if (isIdentifier(element.name) && element.name.simpleName === name) return element.initializer?.element;
793
+ }
794
+ }
795
+ return undefined;
796
+ }
797
+
798
+ function usesThis(node: J): boolean {
799
+ let found = false;
800
+ walk(node, tree => {
801
+ if (isIdentifier(tree) && tree.simpleName === "this") found = true;
802
+ return !found;
803
+ });
804
+ return found;
805
+ }
806
+
807
+ /** The names of `export const {a, b} = slice.actions`, or undefined when `statement` is no such export. */
808
+ export function actionsExport(statement: J, variable: string): {name: string, plain: boolean}[] | undefined {
809
+ if (statement.kind !== J.Kind.VariableDeclarations) return undefined;
810
+ const declarations = statement as J.VariableDeclarations;
811
+ if (declarations.variables.length !== 1) return undefined;
812
+ const declared = declarations.variables[0].element;
813
+ const init = declared.initializer?.element;
814
+ if (init?.kind !== J.Kind.FieldAccess || (init as J.FieldAccess).name.element.simpleName !== "actions" ||
815
+ !isIdentifier((init as J.FieldAccess).target) || ((init as J.FieldAccess).target as J.Identifier).simpleName !== variable) return undefined;
816
+ if (declared.name.kind !== JS.Kind.ObjectBindingPattern || !declarations.modifiers.some(m => m.keyword === "export")) return [{name: "", plain: false}];
817
+ return (declared.name as JS.ObjectBindingPattern).bindings.elements.map(({element}) => {
818
+ const binding = element as JS.BindingElement;
819
+ return binding.kind === JS.Kind.BindingElement && !binding.propertyName && !binding.initializer && isIdentifier(binding.name)
820
+ ? {name: binding.name.simpleName, plain: true} : {name: "", plain: false};
821
+ });
822
+ }
823
+
824
+ /** `export default slice.reducer`, or `export const reducer = slice.reducer`: what only the store reads. */
825
+ export function isReducerExport(statement: J, variable: string, reducerVariables: ReadonlyMap<string, SliceFacts>): boolean {
826
+ const isReducer = (node: J | undefined) => node?.kind === J.Kind.FieldAccess && (node as J.FieldAccess).name.element.simpleName === "reducer" &&
827
+ isIdentifier((node as J.FieldAccess).target) && ((node as J.FieldAccess).target as J.Identifier).simpleName === variable;
828
+ if (statement.kind === JS.Kind.ExportAssignment) {
829
+ const expression = (statement as JS.ExportAssignment).expression.element;
830
+ return isReducer(expression) || isIdentifier(expression) && reducerVariables.get(expression.simpleName)?.variable === variable;
831
+ }
832
+ if (statement.kind !== J.Kind.VariableDeclarations) return false;
833
+ const variables = (statement as J.VariableDeclarations).variables;
834
+ return variables.length === 1 && isReducer(variables[0].element.initializer?.element);
835
+ }
836
+
837
+ /** The module specifier that imports `target` from `from`, such as `./store/counterSlice` for a source beside the store's folder. */
838
+ export function relativeSpecifier(from: string, target: string): string {
839
+ const withoutExtension = target.replace(/\.(?:js|jsx|mjs|cjs)$/, "");
840
+ let specifier = posix.relative(posix.dirname(from), withoutExtension);
841
+ if (!specifier.startsWith(".")) specifier = `./${specifier}`;
842
+ return specifier;
843
+ }