@openrewrite/recipes-react 0.20.0 → 0.21.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 (86) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +10 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/search/find-enzyme-usage.d.ts +4 -0
  10. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  11. package/dist/search/find-enzyme-usage.js +30 -3
  12. package/dist/search/find-enzyme-usage.js.map +1 -1
  13. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  14. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  15. package/dist/search/find-hard-coded-strings.js +987 -0
  16. package/dist/search/find-hard-coded-strings.js.map +1 -0
  17. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  18. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  19. package/dist/search/find-missing-use-client-directive.js +1 -0
  20. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  21. package/dist/testing/enzyme-portals.d.ts +3 -5
  22. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  23. package/dist/testing/enzyme-portals.js +8 -39
  24. package/dist/testing/enzyme-portals.js.map +1 -1
  25. package/dist/testing/enzyme-render-blockers.d.ts +10 -0
  26. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  27. package/dist/testing/enzyme-render-blockers.js +119 -0
  28. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  29. package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
  30. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  31. package/dist/testing/enzyme-to-react-testing-library.js +80 -17
  32. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  33. package/dist/testing/enzyme-usage.d.ts +2 -0
  34. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  35. package/dist/testing/enzyme-usage.js +29 -3
  36. package/dist/testing/enzyme-usage.js.map +1 -1
  37. package/dist/testing/enzyme-wrapper-scope.d.ts +5 -1
  38. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  39. package/dist/testing/enzyme-wrapper-scope.js +12 -3
  40. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  41. package/dist/util/json-and-javascript.d.ts +4 -0
  42. package/dist/util/json-and-javascript.d.ts.map +1 -0
  43. package/dist/util/json-and-javascript.js +37 -0
  44. package/dist/util/json-and-javascript.js.map +1 -0
  45. package/dist/util/module-imports.d.ts +36 -0
  46. package/dist/util/module-imports.d.ts.map +1 -1
  47. package/dist/util/module-imports.js +216 -0
  48. package/dist/util/module-imports.js.map +1 -1
  49. package/dist/util/test-source.d.ts +2 -0
  50. package/dist/util/test-source.d.ts.map +1 -0
  51. package/dist/util/test-source.js +5 -0
  52. package/dist/util/test-source.js.map +1 -0
  53. package/dist/zustand/entry-store.d.ts +9 -0
  54. package/dist/zustand/entry-store.d.ts.map +1 -0
  55. package/dist/zustand/entry-store.js +136 -0
  56. package/dist/zustand/entry-store.js.map +1 -0
  57. package/dist/zustand/redux-stores.d.ts +5 -4
  58. package/dist/zustand/redux-stores.d.ts.map +1 -1
  59. package/dist/zustand/redux-stores.js +8 -5
  60. package/dist/zustand/redux-stores.js.map +1 -1
  61. package/dist/zustand/redux-to-zustand.d.ts +11 -2
  62. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  63. package/dist/zustand/redux-to-zustand.js +137 -42
  64. package/dist/zustand/redux-to-zustand.js.map +1 -1
  65. package/dist/zustand/zustand-plan.d.ts +7 -5
  66. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  67. package/dist/zustand/zustand-plan.js +87 -33
  68. package/dist/zustand/zustand-plan.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  71. package/src/index.ts +7 -0
  72. package/src/search/find-enzyme-usage.ts +30 -6
  73. package/src/search/find-hard-coded-strings.ts +1006 -0
  74. package/src/search/find-missing-use-client-directive.ts +1 -1
  75. package/src/testing/enzyme-portals.ts +4 -44
  76. package/src/testing/enzyme-render-blockers.ts +113 -0
  77. package/src/testing/enzyme-to-react-testing-library.ts +90 -18
  78. package/src/testing/enzyme-usage.ts +35 -2
  79. package/src/testing/enzyme-wrapper-scope.ts +13 -2
  80. package/src/util/json-and-javascript.ts +26 -0
  81. package/src/util/module-imports.ts +223 -0
  82. package/src/util/test-source.ts +2 -0
  83. package/src/zustand/entry-store.ts +131 -0
  84. package/src/zustand/redux-stores.ts +12 -7
  85. package/src/zustand/redux-to-zustand.ts +168 -48
  86. package/src/zustand/zustand-plan.ts +98 -32
@@ -8,9 +8,10 @@ import {create} from "mutative";
8
8
  import {minVersion, satisfies, valid, validRange} from "semver";
9
9
  import {check, not} from "@openrewrite/rewrite";
10
10
  import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
11
- import {importBindings, resolveRelative} from "../util/module-imports";
11
+ import {addPathsConfig, importBindings, isAliasSpecifier, PathsConfigs, Resolve, resolveModule} from "../util/module-imports";
12
12
  import {rewriteVersion, supportsResolvingGate} from "../testing/enzyme-to-react-testing-library";
13
- import {caseReducers, Finding, legacyEnhancer, localSlices, objectProperties, preloadedValue, REDUX_STORES_TABLE, ReduxStoreRow, REDUX, RTK, SliceModule, storeFunctions, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
13
+ import {ENTRY_STORE_MODULE, EntrySplit, splitEntryStore} from "./entry-store";
14
+ import {caseReducers, Finding, importedAs, legacyEnhancer, localSlices, objectProperties, preloadedValue, REDUX_STORES_TABLE, ReduxStoreRow, REDUX, RTK, SliceModule, storeFunctions, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
14
15
  import {
15
16
  actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild, providerChildren,
16
17
  REACT_REDUX, readSelector, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, StoreFacts, storeFacts
@@ -52,6 +53,9 @@ interface PackageFacts {
52
53
  reactNative?: string;
53
54
  zustand?: string;
54
55
  immer?: string;
56
+ redux?: string;
57
+ toolkit?: string;
58
+ reactRedux?: string;
55
59
  }
56
60
 
57
61
  interface Scanned {
@@ -59,8 +63,23 @@ interface Scanned {
59
63
  modules: Map<string, SliceModule>;
60
64
  sliceSources: Map<string, SliceSource>;
61
65
  packages: Map<string, PackageFacts>;
66
+ /** The `paths` of each directory's `tsconfig.json`, or else its `jsconfig.json`, by the directory. */
67
+ configs: PathsConfigs;
62
68
  }
63
69
 
70
+ /** Resolves a specifier among the scanned sources, an alias through the nearest config's `paths`. */
71
+ function resolverOf(scanned: Scanned): Resolve {
72
+ return (from, specifier) => resolveModule(from, specifier, scanned.sources, scanned.configs);
73
+ }
74
+
75
+ /** Whether a source's import of a specifier is one the conversion follows: react-redux's, or one that may name a source. */
76
+ function followsImport(module: string): boolean {
77
+ return module === REACT_REDUX || module.startsWith(".") || isAliasSpecifier(module);
78
+ }
79
+
80
+ /** A source split so that the store it creates and doesn't export moves to `modulePath`. */
81
+ type Split = EntrySplit & {modulePath: string};
82
+
64
83
  /** Adds a dependency to the package whose Redux store converts, with the gates of Java's `AddDependency`. */
65
84
  abstract class ZustandDependency extends JavaDependencyRecipe {
66
85
  /** The package roots whose `package.json` declares the dependency once this run's edit lands. Mutated in place. */
@@ -258,7 +277,8 @@ const ADDS_DEPENDENCIES = (() => {
258
277
  * slice's, a thunk that reaches the rest of the store or a dispatch whose result is used, moves whole instead:
259
278
  *
260
279
  * - the store's reducer, combined as `configureStore` combines it, runs on one zustand store, `useAppStore`, whose
261
- * `dispatch` runs a thunk as Redux Toolkit's default middleware does and any other action through the reducer;
280
+ * `dispatch` runs a thunk as Redux Toolkit's default middleware does, and any other action through the reducer
281
+ * once it is a plain object with a `type`, a string on Redux 5, and throws otherwise, as Redux does;
262
282
  * - the store's variable keeps the store's `getState` and `dispatch`, so their uses stay as they are, in the store's
263
283
  * source too, as do the slices, their action creators and thunks;
264
284
  * - where the store's source or another calls `store.subscribe(listener)`, the store keeps a `subscribe` too, whose
@@ -274,8 +294,8 @@ const ADDS_DEPENDENCIES = (() => {
274
294
  * each read, `useAppStoreSelector(selector)`, a hook the store's source declares that keeps it.
275
295
  *
276
296
  * A legacy `createStore(reducer)` or `createStore(reducer, preloadedState)`, of a preloaded state written as a value,
277
- * moves whole the same way. It has no middleware, so its `dispatch` runs only plain-object actions with a `type`
278
- * through the reducer and throws on any other, as Redux's does, and its state starts from the preloaded state. One
297
+ * moves whole the same way. It has no middleware, so its `dispatch` runs no thunk, and its state starts from the
298
+ * preloaded state. One
279
299
  * whose enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, also runs a function it is
280
300
  * dispatched with `dispatch` and `getState`, as redux-thunk does; DevTools is dropped.
281
301
  *
@@ -293,7 +313,7 @@ const ADDS_DEPENDENCIES = (() => {
293
313
  export class ReduxToZustand extends ScanningRecipe<Scanned> {
294
314
  readonly name = "org.openrewrite.react.migrate.redux-to-zustand";
295
315
  readonly displayName = "Migrate Redux Toolkit slices to zustand";
296
- readonly description = "Moves a repository's one Redux Toolkit store to zustand when it is a `configureStore` of `createSlice` reducers with no other option, its sources are JavaScript, and every use of it converts: each slice becomes a zustand store whose action creators keep their names and run the slice's reducers through immer's `produce`, `useSelector` reads of one slice become the slice's zustand hook, `dispatch` and `store.dispatch` of the slices' action creators become calls of them, `store.getState()` reads become the slice store's `getState()`, and the react-redux `Provider`, replaced with its children, and the store's source are removed. A slice's own `createAsyncThunk`s, whose stages its `extraReducers` handles, keep running on Redux Toolkit and send their actions to the slice's zustand store. A store of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no slice's, thunks that reach the rest of the store or dispatches whose result is used, moves whole: its reducer runs on one zustand store whose `dispatch` runs thunks as Redux Toolkit's default middleware does, its selectors run on that store, through a hook of the store's source that keeps each selection per state where zustand 5 would run the selector on each read, and the store keeps its `getState` and `dispatch`, and its `subscribe`, whose listeners its `dispatch` calls after every action as Redux does, where a source subscribes to it. A legacy `createStore` of a reducer, and perhaps a preloaded state, moves whole too, its `dispatch` taking plain actions only, as Redux's does without middleware, or thunks as well where its enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, which is dropped. Components connected with `connect`, with no `mergeProps` and no option but `forwardRef`, move with a store that moves whole: its source declares a `connect` for the zustand store that passes the same props, copies the same statics and skips the same re-renders as react-redux's, and the store batches its updates as react-redux does. Adds `zustand`, and `immer` where slices move one by one, where they are missing. Stores with any other use, such as `connect` with `mergeProps`, other middleware or enhancers, other uses of the store object such as `persistStore(store)`, selectors with their own equality function or several stores, stay in Redux and are recorded for review.";
316
+ readonly description = "Moves a repository's one Redux Toolkit store to zustand when it is a `configureStore` of `createSlice` reducers with no other option, its sources are JavaScript, and every use of it converts: each slice becomes a zustand store whose action creators keep their names and run the slice's reducers through immer's `produce`, `useSelector` reads of one slice become the slice's zustand hook, `dispatch` and `store.dispatch` of the slices' action creators become calls of them, `store.getState()` reads become the slice store's `getState()`, and the react-redux `Provider`, replaced with its children, and the store's source are removed. A slice's own `createAsyncThunk`s, whose stages its `extraReducers` handles, keep running on Redux Toolkit and send their actions to the slice's zustand store. A store of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no slice's, thunks that reach the rest of the store or dispatches whose result is used, moves whole: its reducer runs on one zustand store whose `dispatch` runs thunks as Redux Toolkit's default middleware does, its selectors run on that store, through a hook of the store's source that keeps each selection per state where zustand 5 would run the selector on each read, and the store keeps its `getState` and `dispatch`, and its `subscribe`, whose listeners its `dispatch` calls after every action as Redux does, where a source subscribes to it. A legacy `createStore` of a reducer, and perhaps a preloaded state, moves whole too, its `dispatch` taking plain actions only, as Redux's does without middleware, or thunks as well where its enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, which is dropped. Components connected with `connect`, with no `mergeProps` and no option but `forwardRef`, move with a store that moves whole: its source declares a `connect` for the zustand store that passes the same props, copies the same statics and skips the same re-renders as react-redux's, and the store batches its updates as react-redux does. A store that moves whole but is created, and not exported, at the top level of an application's entry source, such as the one that renders the `Provider`, moves to an `appStore` module beside that source, with the imports and top-level `const`s and `let`s only it uses, and the source imports back what it still uses. A store's source may export it in its declaration, as its default export or in an export list such as `export {store}`, and other sources may import it, and its slices, by relative paths or by aliases such as `@/store` that the `paths` of the nearest `tsconfig.json` or `jsconfig.json` declare. Adds `zustand`, and `immer` where slices move one by one, where they are missing. Stores with any other use, such as `connect` with `mergeProps`, other middleware or enhancers, other uses of the store object such as `persistStore(store)`, selectors with their own equality function or several stores, stay in Redux and are recorded for review.";
297
317
 
298
318
  @Option({
299
319
  displayName: "Move stores whole",
@@ -322,7 +342,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
322
342
 
323
343
  initialValue(): Scanned {
324
344
  this.storeSources.length = 0;
325
- return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map()};
345
+ return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map(), configs: new Map()};
326
346
  }
327
347
 
328
348
  async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
@@ -351,8 +371,9 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
351
371
  if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
352
372
  const declared = findNodeResolutionResult(doc) ? undefined : await declaredDependencies(doc);
353
373
  const get = (name: string) => declared ? declared[name] : version(doc, name);
354
- scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER)});
374
+ scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER), redux: get("redux"), toolkit: get(RTK), reactRedux: get("react-redux")});
355
375
  }
376
+ await addPathsConfig(scanned.configs, doc);
356
377
  return doc;
357
378
  }
358
379
  }();
@@ -370,6 +391,12 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
370
391
  return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
371
392
  }
372
393
 
394
+ /** The rows reported for each scan's stores. */
395
+ private reported = new WeakMap<Scanned, Set<string>>();
396
+
397
+ /** The sources split by `split`, by path, kept out of the accumulator, which keeps no trees. */
398
+ private splits = new WeakMap<Scanned, Map<string, Split>>();
399
+
373
400
  /** The plan, once every source is scanned. `forecast` assumes that zustand and immer land wherever they're missing. */
374
401
  private plans = new WeakMap<Scanned, Promise<Plan[]>>();
375
402
 
@@ -380,9 +407,11 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
380
407
  if (cached) return cached;
381
408
  }
382
409
  const result = (async () => {
410
+ const splits = await this.split(scanned);
383
411
  for (const cu of this.storeSources) {
384
- const facts = scanned.sources.get(cu.sourcePath);
385
- if (facts) facts.stores = await storeFacts(cu, scanned.modules);
412
+ const source = splits.get(cu.sourcePath)?.module ?? cu;
413
+ const facts = scanned.sources.get(source.sourcePath);
414
+ if (facts) facts.stores = await storeFacts(source, scanned.modules, resolverOf(scanned));
386
415
  }
387
416
  return planPackages(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path),
388
417
  (storePath, immer) => this.dependencies(scanned, storePath, forecast, immer), this.wholeStores !== false, storePath => {
@@ -392,12 +421,56 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
392
421
  // zustand 5's hook, which the package declares or gets on React 18, runs the selector on each read
393
422
  const facts = scanned.packages.get(packageOf(scanned.packages, storePath) ?? "");
394
423
  return facts?.zustand !== undefined ? (major(facts.zustand) ?? 0) >= 5 : (major(facts?.react) ?? 0) >= 18;
395
- });
424
+ }, resolverOf(scanned));
396
425
  })();
397
426
  if (!forecast) this.plans.set(scanned, result);
398
427
  return result;
399
428
  }
400
429
 
430
+ /**
431
+ * Splits each source that creates one store it doesn't export, at the top level of an application source, so that
432
+ * the store moves to a module of its own beside it, which its consumers can import, and the source imports it back.
433
+ * The split replaces the source's facts and adds the module's; the sources change only once the store converts.
434
+ */
435
+ private async split(scanned: Scanned): Promise<Map<string, Split>> {
436
+ const known = this.splits.get(scanned);
437
+ if (known) return known;
438
+ const splits = new Map<string, Split>();
439
+ this.splits.set(scanned, splits);
440
+ const paths = [...scanned.sources.keys()];
441
+ const created = new Map<JS.CompilationUnit, Awaited<ReturnType<typeof storeFacts>>>();
442
+ for (const cu of this.storeSources) created.set(cu, await storeFacts(cu, scanned.modules, resolverOf(scanned)));
443
+ // A package with several stores keeps them in Redux, so none of its sources needs to split
444
+ const storesIn = (root: string | undefined) => [...created].filter(([cu]) => packageOf(scanned.packages, cu.sourcePath) === root).reduce((n, [, stores]) => n + stores.length, 0);
445
+ for (const [cu, stores] of created) {
446
+ if (/\.(?:ts|tsx|mts|cts)$/.test(cu.sourcePath) || TEST_SOURCE.test(cu.sourcePath)) continue;
447
+ if (stores.length !== 1 || stores[0].exportedAs || storesIn(packageOf(scanned.packages, cu.sourcePath)) !== 1) continue;
448
+ const directory = cu.sourcePath.includes("/") ? cu.sourcePath.slice(0, cu.sourcePath.lastIndexOf("/") + 1) : "";
449
+ const base = directory + ENTRY_STORE_MODULE;
450
+ // A module of that name, or a directory, would take the imports of the other
451
+ if (paths.some(path => path.startsWith(base + ".") || path.startsWith(base + "/"))) continue;
452
+ const split = await splitEntryStore(cu, stores[0].store, base + ".js", new ExecutionContext());
453
+ if (!split) continue;
454
+ splits.set(cu.sourcePath, {...split, modulePath: base + ".js"});
455
+ paths.push(base + ".js");
456
+ for (const source of [split.entry, split.module]) {
457
+ const {reducers, slices} = localSlices(source);
458
+ scanned.modules.set(source.sourcePath, {reducers, slices});
459
+ scanned.sources.set(source.sourcePath, await sourceFacts(source));
460
+ const slice = sliceSource(source);
461
+ if (slice) scanned.sliceSources.set(source.sourcePath, slice);
462
+ else scanned.sliceSources.delete(source.sourcePath);
463
+ }
464
+ }
465
+ return splits;
466
+ }
467
+
468
+ override async generate(scanned: Scanned, ctx: ExecutionContext): Promise<SourceFile[]> {
469
+ const plans = await this.planned(scanned, true);
470
+ // Slices that move one by one take the store's source with them, so only a store that moves whole needs the module
471
+ return [...(await this.split(scanned)).values()].filter(split => plans.some(p => p.store?.path === split.modulePath && p.reducerStore)).map(split => split.module);
472
+ }
473
+
401
474
  /** Why the package of the store can't take zustand and immer, if it can't. */
402
475
  private dependencies(scanned: Scanned, storePath: string, forecast: boolean, needsImmer = true): Finding | undefined {
403
476
  const root = packageOf(scanned.packages, storePath);
@@ -420,32 +493,41 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
420
493
  async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
421
494
  const recipe = this;
422
495
  const stores = this.stores;
423
- const reported = new Set<string>();
496
+ // The editor that visits a generated source may be another, which reports none of the same rows again
497
+ let reported = this.reported.get(scanned);
498
+ if (!reported) this.reported.set(scanned, reported = new Set<string>());
424
499
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
425
500
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
426
501
  const plans = await recipe.planned(scanned);
427
502
  const facts = scanned.sources.get(cu.sourcePath);
428
- for (const store of facts?.stores ?? []) {
503
+ const splits = await recipe.split(scanned);
504
+ const split = splits.get(cu.sourcePath);
505
+ const entryOf = (path: string) => [...splits].find(([, s]) => s.modulePath === path)?.[0] ?? path;
506
+ // A store that moves to a module of its own is reported for the source it was created in
507
+ for (const store of [...facts?.stores ?? [], ...split ? scanned.sources.get(split.modulePath)?.stores ?? [] : []]) {
429
508
  const key = `${store.path}\0${store.store}\0${store.api}`;
430
509
  if (reported.has(key)) continue;
431
510
  reported.add(key);
432
511
  const p = plans.find(candidate => candidate.store === store) ?? plans.find(candidate => candidate.blocked.has(store));
433
512
  const findings = p?.store === store ? [] : p?.blocked.get(store) ?? store.findings;
434
513
  const rows = findings.length === 0 ? [{reason: p?.reducerStore ? "REDUCER_STORE" : "SLICE_STORE", detail: ""}] : findings;
435
- for (const {reason, detail} of rows) {
514
+ for (const {reason, detail, action} of rows as Finding[]) {
436
515
  stores.insertRow(ctx, {
437
- sourcePath: store.path, store: store.store, api: store.api,
516
+ sourcePath: entryOf(store.path), store: store.store, api: store.api,
438
517
  status: p?.store === store ? "CONVERTED" : "REVIEW", reason, detail,
439
- testSource: TEST_SOURCE.test(store.path), suggestedAction: SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
518
+ testSource: TEST_SOURCE.test(entryOf(store.path)), suggestedAction: action ?? SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
440
519
  });
441
520
  }
442
521
  }
443
522
  const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
444
- if (!p?.store) return cu;
445
- if (p.reducerStore) return cu.sourcePath === p.store.path ? convertReducerStore(cu, p, ctx) : convertReducerConsumer(cu, p, scanned, ctx);
523
+ // A module the store would have moved to goes again where the store stays
524
+ const generated = [...splits.values()].some(s => s.modulePath === cu.sourcePath);
525
+ if (!p?.store) return generated ? undefined : cu;
526
+ if (p.reducerStore) return cu.sourcePath === p.store.path ? convertReducerStore(cu, p, scanned.packages.get(packageOf(scanned.packages, cu.sourcePath) ?? ""), ctx) : convertReducerConsumer(split?.entry ?? cu, p, scanned, ctx);
446
527
  if (cu.sourcePath === p.store.path) return undefined;
447
528
  const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
448
- const converted = slice ? await convertSlice(this, cu, slice, scanned, ctx) : cu;
529
+ const source = split?.entry ?? cu;
530
+ const converted = slice ? await convertSlice(this, source, slice, scanned, ctx) : source;
449
531
  return convertConsumer(converted, p, scanned, ctx);
450
532
  }
451
533
  }());
@@ -459,7 +541,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
459
541
 
460
542
  const CONVERSION_ACTIONS: Readonly<Record<string, string>> = {
461
543
  MULTIPLE_STORES: "Convert by hand, or one store at a time: the uses of react-redux can't be told apart by store.",
462
- STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module; a zustand store is a module-level singleton.",
544
+ STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module, and export it; a zustand store is a module-level singleton. A store its source creates at the top level moves to a module of its own where only imports and top-level `const`s and `let`s it uses move with it, nothing that stays uses them, and no `appStore` module is beside the source already.",
463
545
  STORE_SOURCE: "Move what else the store's source declares, such as types or helpers, to another module.",
464
546
  SLICE_SOURCE: "Declare each slice in a source of its own, held in a `const` of its own.",
465
547
  SLICE_KEY: "Use a reducer key that is a JavaScript identifier, which names the zustand hook.",
@@ -675,10 +757,10 @@ function withPrefix<T extends J>(node: T, prefix: J.Space): T {
675
757
  /** Rewrites the uses of react-redux, the store and its slices in a source. */
676
758
  async function convertConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned, ctx: ExecutionContext): Promise<J | undefined> {
677
759
  const bindings = importBindings(cu);
678
- const followed = new Map(bindings.filter(b => b.module === REACT_REDUX || b.module.startsWith(".")).map(b => [b.local, b]));
760
+ const followed = new Map(bindings.filter(b => followsImport(b.module)).map(b => [b.local, b]));
679
761
  const isStore = (name: string) => {
680
762
  const binding = followed.get(name);
681
- return !!binding && binding.module !== REACT_REDUX && resolveRelative(cu.sourcePath, binding.module, scanned.sources) === p.store!.path &&
763
+ return !!binding && binding.module !== REACT_REDUX && resolverOf(scanned)(cu.sourcePath, binding.module) === p.store!.path &&
682
764
  binding.name === p.store!.exportedAs;
683
765
  };
684
766
  const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
@@ -870,12 +952,6 @@ async function withoutUnused(cu: JS.CompilationUnit, names: Set<string>): Promis
870
952
  return cu;
871
953
  }
872
954
 
873
- /**
874
- * Rewrites the store's source for a store that moves whole: its reducer runs on one zustand store, whose `dispatch`
875
- * runs a thunk as Redux Toolkit's default middleware does and any other action through the reducer, and the store's
876
- * variable keeps the store's `getState` and `dispatch`. A legacy `createStore` has no middleware, so its `dispatch`
877
- * takes only plain-object actions with a `type`, as Redux's own does, and its state starts from its preloaded state.
878
- */
879
955
  /**
880
956
  * react-redux's `connect` for a store that moves to zustand whole: the props it passes, the statics it copies and the
881
957
  * re-renders it skips are react-redux's, for any `mapStateToProps` and `mapDispatchToProps` and the `forwardRef` option.
@@ -898,7 +974,21 @@ export const SELECTOR = `export function SELECTOR_HOOK(selector) {
898
974
  return useSyncExternalStore(HOOK.subscribe, select, select);
899
975
  }`;
900
976
 
901
- export const CONNECT = `export function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) {
977
+ /** What `connect` does when `mapStateToProps` throws on the state of a store update, by react-redux's major version. */
978
+ const STORE_UPDATE_ERROR = {
979
+ // react-redux 8 maps a store update in its subscription, which drops the error and keeps the props from before
980
+ swallowed: `if (!update) throw error;`,
981
+ // react-redux 7 throws it again on every render until the next update
982
+ rethrown: `if (update) cache.error = error;
983
+ throw error;`
984
+ };
985
+
986
+ /** The `connect` that the store's source declares for its hook `hook`, as the react-redux of range `reactRedux` behaves. */
987
+ export function connectSource(hook: string, reactRedux: string | undefined): string {
988
+ return CONNECT.split("HOOK").join(hook).replace("STORE_UPDATE_ERROR", STORE_UPDATE_ERROR[(major(reactRedux) ?? 8) >= 8 ? "swallowed" : "rethrown"]);
989
+ }
990
+
991
+ const CONNECT = `export function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) {
902
992
  const forwardsRef = Boolean(options && options.forwardRef);
903
993
  const selectState = mapStateToProps ? state => state : () => undefined;
904
994
  const dependsOnOwnProps = map => map.dependsOnOwnProps !== undefined && map.dependsOnOwnProps !== null ? Boolean(map.dependsOnOwnProps) : map.length !== 1;
@@ -961,17 +1051,34 @@ export const CONNECT = `export function connect(mapStateToProps, mapDispatchToPr
961
1051
  }
962
1052
  }
963
1053
  const ownProps = cache.ownProps;
964
- if (!cache.stateProps || (mapState && (cache.state !== state || (mapState.dependsOnOwnProps() && cache.stateOwnProps !== ownProps)))) {
965
- cache.stateProps = mapState ? mapState.map(state, ownProps) : {};
1054
+ // Own props compare shallowly with those of the last render, whether that render finished or not
1055
+ const ownPropsChanged = !cache.seenOwnProps || !shallowEqual(cache.seenOwnProps, ownProps);
1056
+ cache.seenOwnProps = ownProps;
1057
+ const propsChanged = Boolean(mapState) && mapState.dependsOnOwnProps() && !(cache.stateOwnProps && shallowEqual(cache.stateOwnProps, ownProps));
1058
+ if (!cache.stateProps || (mapState && (cache.state !== state || propsChanged))) {
1059
+ // The state and props count as mapped before the map runs, so a render React retries after the map
1060
+ // throws keeps the props from before
1061
+ const update = cache.stateProps !== undefined && cache.state !== state && !propsChanged;
966
1062
  cache.state = state;
967
1063
  cache.stateOwnProps = ownProps;
1064
+ cache.error = undefined;
1065
+ try {
1066
+ cache.stateProps = mapState ? mapState.map(state, ownProps) : {};
1067
+ cache.kept = false;
1068
+ } catch (error) {
1069
+ // The props passed last stay, own props too, until the map returns again
1070
+ cache.kept = true;
1071
+ STORE_UPDATE_ERROR
1072
+ }
1073
+ } else if (cache.error) {
1074
+ throw cache.error;
968
1075
  }
969
1076
  if (!cache.dispatchProps || (mapDispatch && mapDispatch.dependsOnOwnProps() && cache.dispatchOwnProps !== ownProps)) {
970
1077
  cache.dispatchProps = mapDispatch ? mapDispatch.map(HOOK.dispatch, ownProps) : mapDispatchToProps ? bound(mapDispatchToProps) : {dispatch: HOOK.dispatch};
971
1078
  cache.dispatchOwnProps = ownProps;
972
1079
  }
973
1080
  const merged = {...ownProps, ...cache.stateProps, ...cache.dispatchProps};
974
- if (!cache.merged || !shallowEqual(cache.merged, merged)) cache.merged = merged;
1081
+ if (!cache.merged || (!cache.kept || ownPropsChanged) && !shallowEqual(cache.merged, merged)) cache.merged = merged;
975
1082
  if (!cache.element || cache.rendered !== cache.merged || cache.ref !== props.reactReduxForwardedRef) {
976
1083
  cache.rendered = cache.merged;
977
1084
  cache.ref = props.reactReduxForwardedRef;
@@ -992,7 +1099,24 @@ export const CONNECT = `export function connect(mapStateToProps, mapDispatchToPr
992
1099
  }`;
993
1100
 
994
1101
 
995
- async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: ExecutionContext): Promise<J | undefined> {
1102
+ /**
1103
+ * Whether the Redux that creates a store is 5 or later, whose `dispatch` rejects a type that isn't a string: for a
1104
+ * store of Redux Toolkit, the Redux that Toolkit 2 depends on, and otherwise the Redux the package declares, or else
1105
+ * the one its Toolkit brings.
1106
+ */
1107
+ function typedByString(facts: PackageFacts | undefined, fromToolkit: boolean): boolean {
1108
+ const redux = fromToolkit ? undefined : major(facts?.redux);
1109
+ if (redux !== undefined) return redux >= 5;
1110
+ return (major(facts?.toolkit) ?? 0) >= 2;
1111
+ }
1112
+
1113
+ /**
1114
+ * Rewrites the store's source for a store that moves whole: its reducer runs on one zustand store, whose `dispatch`
1115
+ * runs a thunk as Redux Toolkit's default middleware does and any other plain-object action with a `type` through the
1116
+ * reducer, as Redux does, and the store's variable keeps the store's `getState` and `dispatch`. A legacy `createStore`
1117
+ * has no middleware, so its `dispatch` runs no thunk, and its state starts from its preloaded state.
1118
+ */
1119
+ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, facts: PackageFacts | undefined, ctx: ExecutionContext): Promise<J | undefined> {
996
1120
  const store = p.store!;
997
1121
  const {hook, reducer, renderer, selectorHook, listeners} = p.reducerStore!;
998
1122
  const found = storeStatement(cu, store);
@@ -1005,6 +1129,10 @@ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: Executi
1005
1129
  const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
1006
1130
  // redux-thunk runs a function with `dispatch` and `getState`, and passes any other action on to the store
1007
1131
  const thunk = store.reducerStore === "legacyThunk";
1132
+ // Redux rejects what isn't a plain object with a type before a reducer sees it
1133
+ const checks = `if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
1134
+ if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");` +
1135
+ (typedByString(facts, importedAs(cu, RTK, "configureStore", "createStore", "legacy_createStore").has(store.api)) ? `\n if (typeof action.type !== "string") throw new Error("Action 'type' property must be a string.");` : "");
1008
1136
  // react-redux batches a store's updates, so that a parent renders before the children it may remove
1009
1137
  // Redux calls the listeners of `subscribe` after every dispatch, as they were when it began, before react-redux renders
1010
1138
  const update = `${hook}.setState(${reducer}(${hook}.getState(), action), true);`;
@@ -1025,23 +1153,15 @@ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: Executi
1025
1153
  await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(${found.preloaded}, {type: "@@redux/INIT"}));`.apply(statement, cursor) :
1026
1154
  await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(undefined, {type: "@@redux/INIT"}));`.apply(statement, cursor),
1027
1155
  ...listeners ? [await template`const ${raw(listeners)} = new Map();`.apply(statement, cursor)] : [],
1028
- thunk ?
1029
- await template`${raw(hook)}.dispatch = action => {
1030
- if (typeof action === "function") return action(${raw(hook)}.dispatch, ${raw(hook)}.getState, undefined);
1031
- if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
1032
- if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");
1033
- ${raw(setState)}
1034
- return action;
1035
- };`.apply(statement, cursor) :
1036
- legacy ?
1156
+ legacy && !thunk ?
1037
1157
  await template`${raw(hook)}.dispatch = action => {
1038
- if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
1039
- if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");
1158
+ ${raw(checks)}
1040
1159
  ${raw(setState)}
1041
1160
  return action;
1042
1161
  };`.apply(statement, cursor) :
1043
1162
  await template`${raw(hook)}.dispatch = action => {
1044
1163
  if (typeof action === "function") return action(${raw(hook)}.dispatch, ${raw(hook)}.getState, undefined);
1164
+ ${raw(checks)}
1045
1165
  ${raw(setState)}
1046
1166
  return action;
1047
1167
  };`.apply(statement, cursor),
@@ -1049,7 +1169,7 @@ async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: Executi
1049
1169
  await template`export default {${raw(members)}};`.apply(statement, cursor) :
1050
1170
  await template`${raw((statement as J.VariableDeclarations).modifiers.some(m => m.keyword === "export") ? "export " : "")}const ${raw(store.store)} = {${raw(members)}};`.apply(statement, cursor),
1051
1171
  ...selectorHook ? [await template`${raw(SELECTOR.split("SELECTOR_HOOK").join(selectorHook).split("HOOK").join(hook))}`.apply(statement, cursor)] : [],
1052
- ...renderer ? [await template`${raw(CONNECT.split("HOOK").join(hook))}`.apply(statement, cursor)] : []
1172
+ ...renderer ? [await template`${raw(connectSource(hook, facts?.reactRedux))}`.apply(statement, cursor)] : []
1053
1173
  ];
1054
1174
  const statements: J.RightPadded<Statement>[] = [...cu.statements.slice(0, found.index)];
1055
1175
  for (let i = 0; i < generated.length; i++) {
@@ -1106,9 +1226,9 @@ async function convertReducerConsumer(cu: JS.CompilationUnit, p: Plan, scanned:
1106
1226
  const source = scanned.sources.get(cu.sourcePath);
1107
1227
  // A read of the state keeps the store's own hook; another selector, on zustand 5, goes through the store's selector hook
1108
1228
  const reads = (selector: J | undefined) => !!selectorRead(selector) ||
1109
- isIdentifier(selector) && !!source && readSelector(source, selector.simpleName, scanned.sources);
1229
+ isIdentifier(selector) && !!source && readSelector(source, selector.simpleName, scanned.sources, resolverOf(scanned));
1110
1230
  const bindings = importBindings(cu);
1111
- const followed = new Map(bindings.filter(b => b.module === REACT_REDUX || b.module.startsWith(".")).map(b => [b.local, b]));
1231
+ const followed = new Map(bindings.filter(b => followsImport(b.module)).map(b => [b.local, b]));
1112
1232
  const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
1113
1233
  const removed = new Set<string>();
1114
1234
  // The store's hooks the source now calls
@@ -1169,7 +1289,7 @@ async function convertReducerConsumer(cu: JS.CompilationUnit, p: Plan, scanned:
1169
1289
  // The store's variable stays, so its import goes only where nothing uses it any more
1170
1290
  if (removed.has("Provider")) {
1171
1291
  for (const binding of bindings) {
1172
- if (binding.module !== REACT_REDUX && resolveRelative(cu.sourcePath, binding.module, scanned.sources) === p.store!.path) maybeRemoveImport(this, binding.module, binding.name);
1292
+ if (binding.module !== REACT_REDUX && resolverOf(scanned)(cu.sourcePath, binding.module) === p.store!.path) maybeRemoveImport(this, binding.module, binding.name);
1173
1293
  }
1174
1294
  }
1175
1295
  for (const member of [hook, selectorHook]) {