@openrewrite/recipes-react 0.19.0 → 0.20.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.
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +34 -1
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
- package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
- package/dist/testing/enzyme-shared-wrapper.js +213 -0
- package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +276 -0
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +3 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +19 -3
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +2 -0
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +12 -6
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/zustand/redux-stores.d.ts +10 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +147 -5
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +20 -5
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +518 -26
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +27 -4
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +250 -15
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/search/find-enzyme-usage.ts +32 -3
- package/src/testing/enzyme-shared-wrapper.ts +224 -0
- package/src/testing/enzyme-to-react-testing-library.ts +265 -2
- package/src/testing/enzyme-usage.ts +27 -3
- package/src/testing/enzyme-wrapper-scope.ts +11 -4
- package/src/zustand/redux-stores.ts +160 -5
- package/src/zustand/redux-to-zustand.ts +555 -34
- package/src/zustand/zustand-plan.ts +267 -12
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {Cursor, DataTable, emptyMarkers, ExecutionContext, Markup, MarkersKind, or, randomId, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
1
|
+
import {Cursor, DataTable, emptyMarkers, ExecutionContext, Markup, MarkersKind, Option, or, randomId, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
2
|
import {
|
|
3
|
-
AddDependencyOptions, autoFormat, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, raw, template
|
|
3
|
+
AddDependencyOptions, autoFormat, ChangeImport, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, raw, template
|
|
4
4
|
} from "@openrewrite/rewrite/javascript";
|
|
5
|
-
import {isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
|
|
5
|
+
import {emptySpace, isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
|
|
6
6
|
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
7
7
|
import {create} from "mutative";
|
|
8
8
|
import {minVersion, satisfies, valid, validRange} from "semver";
|
|
@@ -10,19 +10,21 @@ import {check, not} from "@openrewrite/rewrite";
|
|
|
10
10
|
import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
|
|
11
11
|
import {importBindings, resolveRelative} from "../util/module-imports";
|
|
12
12
|
import {rewriteVersion, supportsResolvingGate} from "../testing/enzyme-to-react-testing-library";
|
|
13
|
-
import {caseReducers, Finding, localSlices, REDUX_STORES_TABLE, ReduxStoreRow, RTK, SliceModule, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
|
|
13
|
+
import {caseReducers, Finding, legacyEnhancer, localSlices, objectProperties, preloadedValue, REDUX_STORES_TABLE, ReduxStoreRow, REDUX, RTK, SliceModule, storeFunctions, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
|
|
14
14
|
import {
|
|
15
|
-
actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild,
|
|
16
|
-
REACT_REDUX, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, storeFacts
|
|
15
|
+
actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild, providerChildren,
|
|
16
|
+
REACT_REDUX, readSelector, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, StoreFacts, storeFacts
|
|
17
17
|
} from "./zustand-plan";
|
|
18
18
|
|
|
19
19
|
const ZUSTAND = "zustand";
|
|
20
20
|
const IMMER = "immer";
|
|
21
21
|
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* zustand 5 needs React 18; zustand 4 supports React 16.8 and up. No `onlyIfDeclaring`: only a package whose store
|
|
24
|
+
* converts reaches the Java recipe, and one with a legacy `createStore`, or Redux from a workspace root, declares no RTK.
|
|
25
|
+
*/
|
|
23
26
|
const ZUSTAND_5: AddDependencyOptions = {
|
|
24
|
-
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies",
|
|
25
|
-
onlyIfResolving: ["react@>=18.0.0"]
|
|
27
|
+
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies", onlyIfResolving: ["react@>=18.0.0"]
|
|
26
28
|
};
|
|
27
29
|
const ZUSTAND_4: AddDependencyOptions = {...ZUSTAND_5, version: "^4.5.7", onlyIfResolving: ["react@>=16.8.0 <18"]};
|
|
28
30
|
const IMMER_10: AddDependencyOptions = {...ZUSTAND_5, packageName: IMMER, version: "^10.1.3", onlyIfResolving: ["react@>=16.8.0"]};
|
|
@@ -37,6 +39,8 @@ export interface ZustandForecast {
|
|
|
37
39
|
refused?: Map<string, {message: string, lock: string}>;
|
|
38
40
|
/** The React range a package root declares, which picks the zustand step as Java's resolution gate can't where nothing resolved. */
|
|
39
41
|
react?: (root: string) => string | undefined;
|
|
42
|
+
/** The converting package roots whose store moves whole, which need no immer. Filled as `converting` resolves. */
|
|
43
|
+
withoutImmer?: Set<string>;
|
|
40
44
|
}
|
|
41
45
|
|
|
42
46
|
const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lock)$/;
|
|
@@ -44,6 +48,8 @@ const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm
|
|
|
44
48
|
/** A package's dependencies, as far as the conversion needs them. */
|
|
45
49
|
interface PackageFacts {
|
|
46
50
|
react?: string;
|
|
51
|
+
reactDom?: string;
|
|
52
|
+
reactNative?: string;
|
|
47
53
|
zustand?: string;
|
|
48
54
|
immer?: string;
|
|
49
55
|
}
|
|
@@ -61,10 +67,15 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
61
67
|
readonly landed = new Set<string>();
|
|
62
68
|
private readonly held: Json.Document[] = [];
|
|
63
69
|
private readonly locks: SourceFile[] = [];
|
|
70
|
+
/** The lockfiles of the packages whose dependency is forwarded; the Java recipe's edit of any other lockfile is dropped. */
|
|
71
|
+
private readonly owned = new Set<string>();
|
|
72
|
+
/** Each workspace root's package globs, from `workspaces` in its `package.json` or from `pnpm-workspace.yaml`. */
|
|
73
|
+
private readonly workspaces = new Map<string, string[]>();
|
|
74
|
+
private readonly pending: SourceFile[] = [];
|
|
64
75
|
/** The converting package roots whose declared React this step's version doesn't support, left alone. */
|
|
65
76
|
private readonly unfit = new Set<string>();
|
|
66
77
|
|
|
67
|
-
protected constructor(private readonly addition: AddDependencyOptions,
|
|
78
|
+
protected constructor(private readonly addition: AddDependencyOptions, protected readonly forecast: ZustandForecast) {
|
|
68
79
|
super("org.openrewrite.javascript.AddDependency", addition);
|
|
69
80
|
}
|
|
70
81
|
|
|
@@ -73,6 +84,9 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
73
84
|
this.unfit.clear();
|
|
74
85
|
this.held.length = 0;
|
|
75
86
|
this.locks.length = 0;
|
|
87
|
+
this.owned.clear();
|
|
88
|
+
this.workspaces.clear();
|
|
89
|
+
this.pending.length = 0;
|
|
76
90
|
this.forecast.refused?.clear();
|
|
77
91
|
return super.initialValue();
|
|
78
92
|
}
|
|
@@ -82,6 +96,7 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
82
96
|
this.held.push(manifest as Json.Document);
|
|
83
97
|
return false;
|
|
84
98
|
}
|
|
99
|
+
if (/(^|\/)pnpm-workspace\.yaml$/.test(manifest.sourcePath)) this.pending.push(manifest);
|
|
85
100
|
if (LOCKFILE.test(manifest.sourcePath)) this.locks.push(manifest);
|
|
86
101
|
return true;
|
|
87
102
|
}
|
|
@@ -90,12 +105,20 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
90
105
|
if (/(^|\/)package\.json$/.test(manifest.sourcePath) && this.unfit.has(packageRoot(manifest.sourcePath))) return false;
|
|
91
106
|
// The package's own lockfile stays too; a workspace's lockfile is the other packages' as well
|
|
92
107
|
if (LOCKFILE.test(manifest.sourcePath) && this.unfit.has(manifest.sourcePath.slice(0, manifest.sourcePath.lastIndexOf("/") + 1))) return false;
|
|
108
|
+
// NOTE: Java's AddDependency regenerates the lockfile of the nearest directory above even where that lockfile
|
|
109
|
+
// installs a workspace the package isn't in, and the new lockfile then holds this package alone
|
|
110
|
+
if (LOCKFILE.test(manifest.sourcePath) && !this.owned.has(manifest.sourcePath)) return false;
|
|
93
111
|
const refused = this.forecast.refused;
|
|
94
112
|
if (!refused?.size) return true;
|
|
95
113
|
if (/(^|\/)package\.json$/.test(manifest.sourcePath)) return !refused.has(packageRoot(manifest.sourcePath));
|
|
96
114
|
return ![...refused.values()].some(refusal => refusal.lock === manifest.sourcePath);
|
|
97
115
|
}
|
|
98
116
|
|
|
117
|
+
/** The converting package roots this step leaves alone. */
|
|
118
|
+
protected skipped(): Iterable<string> {
|
|
119
|
+
return [];
|
|
120
|
+
}
|
|
121
|
+
|
|
99
122
|
/** Whether the React range the package at `root` declares is one this step's version supports, as `onlyIfResolving` asks. */
|
|
100
123
|
private fits(root: string): boolean {
|
|
101
124
|
const declared = this.forecast.react?.(root);
|
|
@@ -108,26 +131,49 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
108
131
|
/** The lockfile that installs the package at `root`: its own, or that of the workspace it is in. */
|
|
109
132
|
private lockOf(root: string): SourceFile | undefined {
|
|
110
133
|
const directory = (path: string) => path.slice(0, path.lastIndexOf("/") + 1);
|
|
111
|
-
return this.locks.filter(lock =>
|
|
112
|
-
|
|
134
|
+
return this.locks.filter(lock => {
|
|
135
|
+
const base = directory(lock.sourcePath);
|
|
136
|
+
return root === base || root.startsWith(base) && member(this.workspaces.get(base) ?? [], root.slice(base.length, -1));
|
|
137
|
+
}).sort((a, b) => b.sourcePath.length - a.sourcePath.length)[0];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Reads the workspace globs of each scanned `package.json` and `pnpm-workspace.yaml`. */
|
|
141
|
+
private async readWorkspaces(): Promise<void> {
|
|
142
|
+
for (const manifest of this.held) {
|
|
143
|
+
const globs = workspaceGlobs(await parsed(manifest));
|
|
144
|
+
if (globs.length) this.workspaces.set(packageRoot(manifest.sourcePath), globs);
|
|
145
|
+
}
|
|
146
|
+
for (const file of this.pending) {
|
|
147
|
+
const root = file.sourcePath.slice(0, -"pnpm-workspace.yaml".length);
|
|
148
|
+
this.workspaces.set(root, [...this.workspaces.get(root) ?? [], ...pnpmPackages(await TreePrinters.print(file))]);
|
|
149
|
+
}
|
|
113
150
|
}
|
|
114
151
|
|
|
115
152
|
override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
116
|
-
const converting = await this.forecast.converting?.() ??
|
|
153
|
+
const converting = new Set(await this.forecast.converting?.() ?? []);
|
|
154
|
+
for (const root of this.skipped()) converting.delete(root);
|
|
117
155
|
// NOTE: Java's `onlyIfResolving` passes where nothing resolved React, such as a package without a lockfile
|
|
118
156
|
for (const root of converting) if (!this.fits(root)) this.unfit.add(root);
|
|
119
157
|
const forwarded = this.held.filter(manifest => converting.has(packageRoot(manifest.sourcePath)) && !this.unfit.has(packageRoot(manifest.sourcePath)));
|
|
158
|
+
await this.readWorkspaces();
|
|
120
159
|
const scanner = await this.java.scanner(acc);
|
|
121
160
|
for (const manifest of forwarded) await scanner.visit(manifest, ctx);
|
|
122
161
|
const generated = await super.generate(acc, ctx);
|
|
123
162
|
const editor = await this.java.editorWithData(acc);
|
|
124
163
|
for (const manifest of forwarded) {
|
|
125
164
|
const edited = await editor.visit<Json.Document>(manifest, ctx);
|
|
126
|
-
if (!edited || edited === manifest
|
|
127
|
-
// NOTE: where the package manager's lock can't be reproduced, `AddDependency` still declares the package
|
|
128
|
-
// and only warns on the lockfile, which an install from the lockfile, as in CI, would then refuse
|
|
165
|
+
if (!edited || edited === manifest) continue;
|
|
129
166
|
const root = packageRoot(manifest.sourcePath);
|
|
167
|
+
if (!await declares(edited, this.addition.packageName)) {
|
|
168
|
+
// NOTE: a current `AddDependency` takes its edit back where the lockfile can't be regenerated, and says why on the manifest
|
|
169
|
+
const warning = newWarning(manifest, edited);
|
|
170
|
+
if (warning) this.forecast.refused?.set(root, {message: warning.message, lock: this.lockOf(root)?.sourcePath ?? manifest.sourcePath});
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
// NOTE: where the package manager's lock can't be reproduced, `AddDependency` 8.94 still declares the package
|
|
174
|
+
// and only warns on the lockfile, which an install from the lockfile, as in CI, would then refuse
|
|
130
175
|
const lock = this.lockOf(root);
|
|
176
|
+
if (lock) this.owned.add(lock.sourcePath);
|
|
131
177
|
const regenerated = lock ? await editor.visit<SourceFile>(lock, ctx) : undefined;
|
|
132
178
|
const warning = regenerated?.markers.markers.find(marker => marker.kind === MarkersKind.MarkupWarn || marker.kind === MarkersKind.MarkupError) as Markup | undefined;
|
|
133
179
|
if (warning) this.forecast.refused?.set(root, {message: warning.message, lock: lock!.sourcePath});
|
|
@@ -138,11 +184,18 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
138
184
|
}
|
|
139
185
|
}
|
|
140
186
|
|
|
187
|
+
/** The warning or error the Java recipe put on `after` that `before` didn't carry. */
|
|
188
|
+
function newWarning(before: SourceFile, after: SourceFile): Markup | undefined {
|
|
189
|
+
const had = new Set(before.markers.markers.map(marker => marker.id));
|
|
190
|
+
return after.markers.markers.find(marker => !had.has(marker.id) &&
|
|
191
|
+
(marker.kind === MarkersKind.MarkupWarn || marker.kind === MarkersKind.MarkupError)) as Markup | undefined;
|
|
192
|
+
}
|
|
193
|
+
|
|
141
194
|
/** Adds zustand 5 where a store of a package on React 18 or later converts. */
|
|
142
195
|
export class AddZustand extends ZustandDependency {
|
|
143
196
|
readonly name = "org.openrewrite.react.migrate.add-zustand";
|
|
144
197
|
readonly displayName = "Add `zustand` where a Redux store is migrated";
|
|
145
|
-
readonly description = "Adds `zustand` 5 to packages that
|
|
198
|
+
readonly description = "Adds `zustand` 5 to packages that resolve React 18 or later, where a Redux store moves to zustand.";
|
|
146
199
|
|
|
147
200
|
constructor(forecast: ZustandForecast = {}) {
|
|
148
201
|
super(ZUSTAND_5, forecast);
|
|
@@ -153,7 +206,7 @@ export class AddZustand extends ZustandDependency {
|
|
|
153
206
|
export class AddZustand4 extends ZustandDependency {
|
|
154
207
|
readonly name = "org.openrewrite.react.migrate.add-zustand-4";
|
|
155
208
|
readonly displayName = "Add `zustand` 4 where a Redux store is migrated on React 16.8 to 17";
|
|
156
|
-
readonly description = "Adds `zustand` 4 to packages that
|
|
209
|
+
readonly description = "Adds `zustand` 4 to packages that resolve React 16.8 to 17, where a Redux store moves to zustand.";
|
|
157
210
|
|
|
158
211
|
constructor(forecast: ZustandForecast = {}) {
|
|
159
212
|
super(ZUSTAND_4, forecast);
|
|
@@ -164,11 +217,15 @@ export class AddZustand4 extends ZustandDependency {
|
|
|
164
217
|
export class AddImmer extends ZustandDependency {
|
|
165
218
|
readonly name = "org.openrewrite.react.migrate.add-immer";
|
|
166
219
|
readonly displayName = "Add `immer` where a Redux store is migrated";
|
|
167
|
-
readonly description = "Adds `immer` 10 to packages that
|
|
220
|
+
readonly description = "Adds `immer` 10 to packages that resolve React 16.8 or later, where a Redux store moves to zustand and its slices' reducers run through `produce`.";
|
|
168
221
|
|
|
169
222
|
constructor(forecast: ZustandForecast = {}) {
|
|
170
223
|
super(IMMER_10, forecast);
|
|
171
224
|
}
|
|
225
|
+
|
|
226
|
+
protected override skipped(): Iterable<string> {
|
|
227
|
+
return this.forecast.withoutImmer ?? [];
|
|
228
|
+
}
|
|
172
229
|
}
|
|
173
230
|
|
|
174
231
|
/** Older hosts drop `onlyIfResolving`, which would add zustand 5 to packages on React 17, so the steps run only where the host has it. */
|
|
@@ -192,21 +249,66 @@ const ADDS_DEPENDENCIES = (() => {
|
|
|
192
249
|
* - `dispatch(increment())` and `store.dispatch(increment())`, whose result is unused, become `increment()`, and
|
|
193
250
|
* `const dispatch = useDispatch()` goes;
|
|
194
251
|
* - `store.getState().counter` becomes `useCounterStore.getState()`;
|
|
195
|
-
* - `<Provider store={store}>` is replaced with its one child, and the store's
|
|
252
|
+
* - `<Provider store={store}>` is replaced with its one child, or a fragment `<>` of its children, and the store's
|
|
253
|
+
* source is removed;
|
|
196
254
|
* - a `createAsyncThunk` of the slice's source whose stages `extraReducers` handles stays RTK's, and runs its actions
|
|
197
255
|
* through those cases on the slice's zustand store; a dispatch of it becomes a call.
|
|
198
256
|
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
257
|
+
* A `configureStore` of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no
|
|
258
|
+
* slice's, a thunk that reaches the rest of the store or a dispatch whose result is used, moves whole instead:
|
|
259
|
+
*
|
|
260
|
+
* - 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;
|
|
262
|
+
* - the store's variable keeps the store's `getState` and `dispatch`, so their uses stay as they are, in the store's
|
|
263
|
+
* source too, as do the slices, their action creators and thunks;
|
|
264
|
+
* - where the store's source or another calls `store.subscribe(listener)`, the store keeps a `subscribe` too, whose
|
|
265
|
+
* listeners its `dispatch` calls after every action, changed state or not, as they were when the dispatch began, as
|
|
266
|
+
* Redux does. They are called before the components render, as Redux calls the listeners that subscribe before
|
|
267
|
+
* react-redux's `Provider` does; one that subscribes once they are mounted, which Redux calls after they render, is too;
|
|
268
|
+
* - `useSelector(state => state.counter.value)` becomes `useAppStore(state => state.counter.value)`, as does
|
|
269
|
+
* `useSelector(selectValue)` of a top-level `const selectValue = state => state.counter.value`, declared in the source
|
|
270
|
+
* or imported from another, `const dispatch = useDispatch()` becomes `const dispatch = useAppStore.dispatch`, and
|
|
271
|
+
* the `Provider` goes, as above;
|
|
272
|
+
* - any other `useSelector(selector)`, such as one that builds a value, becomes `useAppStore(selector)` on zustand 4,
|
|
273
|
+
* whose hook keeps the selection per state as react-redux's does, and on zustand 5, whose hook runs the selector on
|
|
274
|
+
* each read, `useAppStoreSelector(selector)`, a hook the store's source declares that keeps it.
|
|
275
|
+
*
|
|
276
|
+
* 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
|
|
279
|
+
* whose enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, also runs a function it is
|
|
280
|
+
* dispatched with `dispatch` and `getState`, as redux-thunk does; DevTools is dropped.
|
|
281
|
+
*
|
|
282
|
+
* A store that moves whole also takes its components connected with `connect`, with no `mergeProps` and no option
|
|
283
|
+
* but `forwardRef`: the store's source declares a `connect` that passes the props, copies the statics and skips the
|
|
284
|
+
* re-renders react-redux's does, reading the zustand store, and each source imports it from there. The store then
|
|
285
|
+
* batches its updates with `unstable_batchedUpdates`, as react-redux does, so that before React 18 a parent renders
|
|
286
|
+
* before a child it removes.
|
|
287
|
+
*
|
|
288
|
+
* Any other use, such as `connect` with `mergeProps`, `persistStore(store)`, or a selector with its own equality function, keeps the
|
|
289
|
+
* store in Redux, recorded in the `ReduxStores` table with the reason.
|
|
201
290
|
*
|
|
202
291
|
* @see https://zustand.docs.pmnd.rs/guides/migrating-to-zustand
|
|
203
292
|
*/
|
|
204
293
|
export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
205
294
|
readonly name = "org.openrewrite.react.migrate.redux-to-zustand";
|
|
206
295
|
readonly displayName = "Migrate Redux Toolkit slices to zustand";
|
|
207
|
-
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
|
|
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.";
|
|
297
|
+
|
|
298
|
+
@Option({
|
|
299
|
+
displayName: "Move stores whole",
|
|
300
|
+
description: "Whether a store whose slices can't move to zustand one by one moves whole: one zustand store driven by the store's own reducer. Defaults to true.",
|
|
301
|
+
required: false,
|
|
302
|
+
type: "Boolean"
|
|
303
|
+
})
|
|
304
|
+
wholeStores?: boolean;
|
|
208
305
|
|
|
209
|
-
|
|
306
|
+
constructor(options?: {wholeStores?: boolean}) {
|
|
307
|
+
super(options);
|
|
308
|
+
this.wholeStores ??= true;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
private readonly forecast: ZustandForecast = {refused: new Map(), withoutImmer: new Set()};
|
|
210
312
|
private readonly storeSources: JS.CompilationUnit[] = [];
|
|
211
313
|
/** The packages the dependency steps were asked to change, once they ask. */
|
|
212
314
|
private asked?: ReadonlySet<string>;
|
|
@@ -228,8 +330,11 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
228
330
|
let forecast: Promise<ReadonlySet<string>> | undefined;
|
|
229
331
|
this.asked = undefined;
|
|
230
332
|
this.forecast.react = root => scanned.packages.get(root)?.react;
|
|
231
|
-
this.forecast.converting = () => forecast ??= this.planned(scanned, true)
|
|
232
|
-
|
|
333
|
+
this.forecast.converting = () => forecast ??= this.planned(scanned, true).then(plans => {
|
|
334
|
+
this.forecast.withoutImmer!.clear();
|
|
335
|
+
for (const p of plans) if (p.reducerStore) this.forecast.withoutImmer!.add(packageOf(scanned.packages, p.store!.path)!);
|
|
336
|
+
return this.asked = new Set(plans.filter(p => p.store).map(p => packageOf(scanned.packages, p.store!.path)!));
|
|
337
|
+
});
|
|
233
338
|
const sources = await check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
234
339
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
235
340
|
const {reducers, slices} = localSlices(cu);
|
|
@@ -246,7 +351,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
246
351
|
if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
|
|
247
352
|
const declared = findNodeResolutionResult(doc) ? undefined : await declaredDependencies(doc);
|
|
248
353
|
const get = (name: string) => declared ? declared[name] : version(doc, name);
|
|
249
|
-
scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), zustand: get(ZUSTAND), immer: get(IMMER)});
|
|
354
|
+
scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER)});
|
|
250
355
|
}
|
|
251
356
|
return doc;
|
|
252
357
|
}
|
|
@@ -280,14 +385,21 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
280
385
|
if (facts) facts.stores = await storeFacts(cu, scanned.modules);
|
|
281
386
|
}
|
|
282
387
|
return planPackages(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path),
|
|
283
|
-
storePath => this.dependencies(scanned, storePath, forecast)
|
|
388
|
+
(storePath, immer) => this.dependencies(scanned, storePath, forecast, immer), this.wholeStores !== false, storePath => {
|
|
389
|
+
const facts = scanned.packages.get(packageOf(scanned.packages, storePath) ?? "");
|
|
390
|
+
return facts?.reactNative ? "react-native" : facts?.reactDom ? "react-dom" : undefined;
|
|
391
|
+
}, storePath => {
|
|
392
|
+
// zustand 5's hook, which the package declares or gets on React 18, runs the selector on each read
|
|
393
|
+
const facts = scanned.packages.get(packageOf(scanned.packages, storePath) ?? "");
|
|
394
|
+
return facts?.zustand !== undefined ? (major(facts.zustand) ?? 0) >= 5 : (major(facts?.react) ?? 0) >= 18;
|
|
395
|
+
});
|
|
284
396
|
})();
|
|
285
397
|
if (!forecast) this.plans.set(scanned, result);
|
|
286
398
|
return result;
|
|
287
399
|
}
|
|
288
400
|
|
|
289
401
|
/** Why the package of the store can't take zustand and immer, if it can't. */
|
|
290
|
-
private dependencies(scanned: Scanned, storePath: string, forecast: boolean): Finding | undefined {
|
|
402
|
+
private dependencies(scanned: Scanned, storePath: string, forecast: boolean, needsImmer = true): Finding | undefined {
|
|
291
403
|
const root = packageOf(scanned.packages, storePath);
|
|
292
404
|
const facts = root !== undefined ? scanned.packages.get(root) : undefined;
|
|
293
405
|
if (root === undefined || !facts) return {reason: "NO_PACKAGE", detail: storePath};
|
|
@@ -300,7 +412,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
300
412
|
const zustand = facts.zustand !== undefined ? (major(facts.zustand) ?? 0) >= (react >= 18 ? 4 : 4) && (react >= 18 || major(facts.zustand) === 4)
|
|
301
413
|
: landed(react >= 18 ? this.steps?.zustand : this.steps?.zustand4);
|
|
302
414
|
if (!zustand) return {reason: "DEPENDENCY", detail: facts.zustand ? `zustand ${facts.zustand} doesn't support React ${react}` : "zustand can't be added"};
|
|
303
|
-
const immer = facts.immer !== undefined ? (major(facts.immer) ?? 0) >= 9 : landed(this.steps?.immer);
|
|
415
|
+
const immer = !needsImmer || (facts.immer !== undefined ? (major(facts.immer) ?? 0) >= 9 : landed(this.steps?.immer));
|
|
304
416
|
if (!immer) return {reason: "DEPENDENCY", detail: facts.immer ? `immer ${facts.immer} is older than 9` : "immer can't be added"};
|
|
305
417
|
return undefined;
|
|
306
418
|
}
|
|
@@ -319,7 +431,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
319
431
|
reported.add(key);
|
|
320
432
|
const p = plans.find(candidate => candidate.store === store) ?? plans.find(candidate => candidate.blocked.has(store));
|
|
321
433
|
const findings = p?.store === store ? [] : p?.blocked.get(store) ?? store.findings;
|
|
322
|
-
const rows = findings.length === 0 ? [{reason: "SLICE_STORE", detail: ""}] : findings;
|
|
434
|
+
const rows = findings.length === 0 ? [{reason: p?.reducerStore ? "REDUCER_STORE" : "SLICE_STORE", detail: ""}] : findings;
|
|
323
435
|
for (const {reason, detail} of rows) {
|
|
324
436
|
stores.insertRow(ctx, {
|
|
325
437
|
sourcePath: store.path, store: store.store, api: store.api,
|
|
@@ -330,6 +442,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
330
442
|
}
|
|
331
443
|
const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
|
|
332
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);
|
|
333
446
|
if (cu.sourcePath === p.store.path) return undefined;
|
|
334
447
|
const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
|
|
335
448
|
const converted = slice ? await convertSlice(this, cu, slice, scanned, ctx) : cu;
|
|
@@ -359,10 +472,10 @@ const CONVERSION_ACTIONS: Readonly<Record<string, string>> = {
|
|
|
359
472
|
ACTIONS_EXPORT: "Export the action creators as `export const {a, b} = slice.actions`, under their own names.",
|
|
360
473
|
UNKNOWN_ACTION: "Remove the import of an action creator that has no reducer, which is `undefined`.",
|
|
361
474
|
SLICE_USE: "Use the slice only through its action creators and the store; other uses of the slice object are converted by hand.",
|
|
362
|
-
STORE_USE: "Use the store only in `<Provider store>`, `store.getState().key` and `store.dispatch(action())`.",
|
|
363
|
-
REACT_REDUX_USE: "Replace `
|
|
475
|
+
STORE_USE: "Use the store only in `<Provider store>`, `store.getState().key` and `store.dispatch(action())`, or, where it moves whole, in calls of its `getState`, `dispatch` and `subscribe`.",
|
|
476
|
+
REACT_REDUX_USE: "Replace `useStore`, `connect` with `mergeProps` or options other than `forwardRef`, and other react-redux APIs with `useSelector` and `useDispatch`, or convert by hand.",
|
|
364
477
|
DISPATCH: "Dispatch only the slices' action creators and their own thunks, as a statement of its own; other thunks and dispatches whose result is used are converted by hand.",
|
|
365
|
-
SELECTOR: "
|
|
478
|
+
SELECTOR: "Pass `useSelector` the selector alone, with no equality function or type arguments; where the slices would move one by one, read one slice's state in each selector, such as `state => state.counter.value` or a top-level `const` of one.",
|
|
366
479
|
UNFOLLOWED_IMPORT: "Import the store, its slices and react-redux with named or default imports; namespace imports, re-exports and module mocks are converted by hand.",
|
|
367
480
|
TYPESCRIPT: "TypeScript sources are not converted yet.",
|
|
368
481
|
NO_PACKAGE: "Add a `package.json` for the store's package.",
|
|
@@ -374,6 +487,43 @@ function packageRoot(manifestPath: string): string {
|
|
|
374
487
|
return manifestPath.slice(0, -"package.json".length);
|
|
375
488
|
}
|
|
376
489
|
|
|
490
|
+
async function parsed(doc: Json.Document): Promise<any> {
|
|
491
|
+
try {
|
|
492
|
+
return JSON.parse(await TreePrinters.print(doc));
|
|
493
|
+
} catch {
|
|
494
|
+
return {};
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** The package globs of `workspaces`, as an array or as Yarn's `{packages: [...]}`. */
|
|
499
|
+
function workspaceGlobs(manifest: any): string[] {
|
|
500
|
+
const workspaces = Array.isArray(manifest?.workspaces) ? manifest.workspaces : manifest?.workspaces?.packages;
|
|
501
|
+
return Array.isArray(workspaces) ? workspaces.filter((glob: unknown): glob is string => typeof glob === "string") : [];
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** The entries of the `packages` list of a `pnpm-workspace.yaml`. */
|
|
505
|
+
function pnpmPackages(yaml: string): string[] {
|
|
506
|
+
const globs: string[] = [];
|
|
507
|
+
let inPackages = false;
|
|
508
|
+
for (const line of yaml.split(/\r?\n/)) {
|
|
509
|
+
if (/^\S/.test(line)) inPackages = /^packages\s*:/.test(line);
|
|
510
|
+
// REGEX: an indented `- entry`, the entry perhaps quoted, perhaps followed by a `# comment`
|
|
511
|
+
const entry = inPackages && /^\s+-\s*(?:'([^']*)'|"([^"]*)"|([^#\s]+))/.exec(line);
|
|
512
|
+
if (entry) globs.push(entry[1] ?? entry[2] ?? entry[3]);
|
|
513
|
+
}
|
|
514
|
+
return globs;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Whether `path`, relative to a workspace root, matches its globs, where a `!glob` excludes what it matches. */
|
|
518
|
+
function member(globs: string[], path: string): boolean {
|
|
519
|
+
const matches = (glob: string) => {
|
|
520
|
+
const pattern = glob.replace(/^\.\//, "").replace(/\/+$/, "").replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
521
|
+
.replace(/\*\*\/?|\*|\?/g, token => token.startsWith("**") ? "(?:.*/)?" + (token.endsWith("/") ? "" : ".*") : token === "*" ? "[^/]*" : "[^/]");
|
|
522
|
+
return new RegExp(`^${pattern}$`).test(path);
|
|
523
|
+
};
|
|
524
|
+
return globs.some(glob => !glob.startsWith("!") && matches(glob)) && !globs.some(glob => glob.startsWith("!") && matches(glob.slice(1)));
|
|
525
|
+
}
|
|
526
|
+
|
|
377
527
|
/** The root of the innermost package that holds `sourcePath`. */
|
|
378
528
|
function packageOf(packages: ReadonlyMap<string, PackageFacts>, sourcePath: string): string | undefined {
|
|
379
529
|
return [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length)[0];
|
|
@@ -619,6 +769,11 @@ async function convertConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned
|
|
|
619
769
|
removed.add("store");
|
|
620
770
|
return withPrefix(await this.visit(child, q, this.cursor) as JSX.Tag, tag.prefix);
|
|
621
771
|
}
|
|
772
|
+
if (providerChildren(tag)) {
|
|
773
|
+
removed.add("Provider");
|
|
774
|
+
removed.add("store");
|
|
775
|
+
return fragment(await super.visitJsxTag(tag, q) as JSX.Tag);
|
|
776
|
+
}
|
|
622
777
|
}
|
|
623
778
|
return super.visitJsxTag(tag, q);
|
|
624
779
|
}
|
|
@@ -658,3 +813,369 @@ function replaceTree(root: J, target: J, replacement: J): J {
|
|
|
658
813
|
replace(draft);
|
|
659
814
|
}) as J;
|
|
660
815
|
}
|
|
816
|
+
|
|
817
|
+
/** The statement of the store's source that creates the store, and the store's `reducer` option. */
|
|
818
|
+
function storeStatement(cu: JS.CompilationUnit, store: StoreFacts): {index: number, call: J.MethodInvocation, reducer: J, preloaded?: J, consts?: Set<string>} | undefined {
|
|
819
|
+
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
820
|
+
const functions = storeFunctions(cu);
|
|
821
|
+
const names = legacy ? functions.legacy : functions.configure;
|
|
822
|
+
const isStoreCall = (node: J | undefined): node is J.MethodInvocation => node?.kind === J.Kind.MethodInvocation &&
|
|
823
|
+
!(node as J.MethodInvocation).select && names.has((node as J.MethodInvocation).name.simpleName);
|
|
824
|
+
for (let index = 0; index < cu.statements.length; index++) {
|
|
825
|
+
const statement = cu.statements[index].element;
|
|
826
|
+
const call = statement.kind === JS.Kind.ExportAssignment ? (statement as JS.ExportAssignment).expression.element :
|
|
827
|
+
statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.length === 1 &&
|
|
828
|
+
isIdentifier((statement as J.VariableDeclarations).variables[0].element.name) &&
|
|
829
|
+
((statement as J.VariableDeclarations).variables[0].element.name as J.Identifier).simpleName === store.store
|
|
830
|
+
? (statement as J.VariableDeclarations).variables[0].element.initializer?.element : undefined;
|
|
831
|
+
if (!isStoreCall(call)) continue;
|
|
832
|
+
if (legacy) {
|
|
833
|
+
// The preloaded state is the second of three arguments, or the second of two that is no enhancer
|
|
834
|
+
const args = argumentsOf(call);
|
|
835
|
+
const preloaded = args.length === 3 || args.length === 2 && preloadedValue(args[1], cu) ? args[1] : undefined;
|
|
836
|
+
const enhancer = args.length === 3 || args.length === 2 && !preloaded ? legacyEnhancer(args[args.length - 1], cu) : undefined;
|
|
837
|
+
// NOTE: the arguments are moved into new calls, so they drop the line breaks they had in the store's call
|
|
838
|
+
return {index, call, reducer: {...args[0], prefix: emptySpace}, preloaded: preloaded && {...preloaded, prefix: emptySpace}, consts: enhancer && !("unsupported" in enhancer) ? enhancer.consts : new Set()};
|
|
839
|
+
}
|
|
840
|
+
const reducer = objectProperties(argumentsOf(call)[0])?.get("reducer");
|
|
841
|
+
return reducer ? {index, call, reducer} : undefined;
|
|
842
|
+
}
|
|
843
|
+
return undefined;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* Removes the top-level `const`s among `names` that nothing else in the source refers to any more, such as those the
|
|
848
|
+
* store's enhancer was written with, and then those that only they referred to.
|
|
849
|
+
*/
|
|
850
|
+
async function withoutUnused(cu: JS.CompilationUnit, names: Set<string>): Promise<JS.CompilationUnit> {
|
|
851
|
+
const declared = (statement: J) => statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.length === 1 &&
|
|
852
|
+
isIdentifier((statement as J.VariableDeclarations).variables[0].element.name) ?
|
|
853
|
+
((statement as J.VariableDeclarations).variables[0].element.name as J.Identifier).simpleName : undefined;
|
|
854
|
+
for (let removed = true; removed;) {
|
|
855
|
+
const counts = new Map<string, number>();
|
|
856
|
+
await new class extends JavaScriptVisitor<undefined> {
|
|
857
|
+
override async visitIdentifier(identifier: J.Identifier, p: undefined): Promise<J | undefined> {
|
|
858
|
+
counts.set(identifier.simpleName, (counts.get(identifier.simpleName) ?? 0) + 1);
|
|
859
|
+
return super.visitIdentifier(identifier, p);
|
|
860
|
+
}
|
|
861
|
+
}().visit(cu, undefined);
|
|
862
|
+
// NOTE: a name counted once is the declaration's own; a property key of the same name only keeps the `const`
|
|
863
|
+
const statements = cu.statements.filter(padded => {
|
|
864
|
+
const name = declared(padded.element);
|
|
865
|
+
return !name || !names.has(name) || counts.get(name) !== 1;
|
|
866
|
+
});
|
|
867
|
+
removed = statements.length < cu.statements.length;
|
|
868
|
+
cu = {...cu, statements};
|
|
869
|
+
}
|
|
870
|
+
return cu;
|
|
871
|
+
}
|
|
872
|
+
|
|
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
|
+
/**
|
|
880
|
+
* react-redux's `connect` for a store that moves to zustand whole: the props it passes, the statics it copies and the
|
|
881
|
+
* re-renders it skips are react-redux's, for any `mapStateToProps` and `mapDispatchToProps` and the `forwardRef` option.
|
|
882
|
+
* `HOOK` stands for the zustand store's hook.
|
|
883
|
+
*/
|
|
884
|
+
/**
|
|
885
|
+
* The selector hook of a whole store on zustand 5, whose own hook runs the selector on each read: as react-redux's
|
|
886
|
+
* `useSelector`, it runs the selector once per state and selector, so a selector that builds a value renders once.
|
|
887
|
+
*/
|
|
888
|
+
export const SELECTOR = `export function SELECTOR_HOOK(selector) {
|
|
889
|
+
const last = useRef(undefined);
|
|
890
|
+
const select = () => {
|
|
891
|
+
const state = HOOK.getState();
|
|
892
|
+
const kept = last.current;
|
|
893
|
+
if (kept && kept.state === state && kept.selector === selector) return kept.selection;
|
|
894
|
+
const selection = selector(state);
|
|
895
|
+
last.current = {state, selector, selection};
|
|
896
|
+
return selection;
|
|
897
|
+
};
|
|
898
|
+
return useSyncExternalStore(HOOK.subscribe, select, select);
|
|
899
|
+
}`;
|
|
900
|
+
|
|
901
|
+
export const CONNECT = `export function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) {
|
|
902
|
+
const forwardsRef = Boolean(options && options.forwardRef);
|
|
903
|
+
const selectState = mapStateToProps ? state => state : () => undefined;
|
|
904
|
+
const dependsOnOwnProps = map => map.dependsOnOwnProps !== undefined && map.dependsOnOwnProps !== null ? Boolean(map.dependsOnOwnProps) : map.length !== 1;
|
|
905
|
+
// A map that returns a function on its first call is a factory of the map to use
|
|
906
|
+
const mapper = map => {
|
|
907
|
+
let actual = map;
|
|
908
|
+
let first = true;
|
|
909
|
+
const run = (value, ownProps) => dependsOnOwnProps(actual) ? actual(value, ownProps) : actual(value);
|
|
910
|
+
return {
|
|
911
|
+
map(value, ownProps) {
|
|
912
|
+
let props = run(value, ownProps);
|
|
913
|
+
if (first) {
|
|
914
|
+
first = false;
|
|
915
|
+
if (typeof props === "function") {
|
|
916
|
+
actual = props;
|
|
917
|
+
props = run(value, ownProps);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return props;
|
|
921
|
+
},
|
|
922
|
+
dependsOnOwnProps: () => dependsOnOwnProps(actual)
|
|
923
|
+
};
|
|
924
|
+
};
|
|
925
|
+
const bound = actionCreators => {
|
|
926
|
+
const props = {};
|
|
927
|
+
for (const key of Object.keys(actionCreators)) {
|
|
928
|
+
const actionCreator = actionCreators[key];
|
|
929
|
+
if (typeof actionCreator === "function") props[key] = (...args) => HOOK.dispatch(actionCreator(...args));
|
|
930
|
+
}
|
|
931
|
+
return props;
|
|
932
|
+
};
|
|
933
|
+
const shallowEqual = (a, b) => {
|
|
934
|
+
const keys = Object.keys(a);
|
|
935
|
+
return keys.length === Object.keys(b).length && keys.every(key => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
|
|
936
|
+
};
|
|
937
|
+
const notHoisted = ["$$typeof", "render", "compare", "type", "childContextTypes", "contextType", "contextTypes", "defaultProps", "displayName",
|
|
938
|
+
"getDefaultProps", "getDerivedStateFromError", "getDerivedStateFromProps", "mixins", "propTypes", "name", "length", "prototype", "caller",
|
|
939
|
+
"callee", "arguments", "arity"];
|
|
940
|
+
const hoistStatics = (target, source) => {
|
|
941
|
+
for (let from = source; from && from !== Function.prototype && from !== Object.prototype; from = Object.getPrototypeOf(from)) {
|
|
942
|
+
for (const key of [...Object.getOwnPropertyNames(from), ...Object.getOwnPropertySymbols(from)]) {
|
|
943
|
+
if (!notHoisted.includes(key) && !Object.prototype.hasOwnProperty.call(target, key)) Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(from, key));
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
return target;
|
|
947
|
+
};
|
|
948
|
+
return WrappedComponent => {
|
|
949
|
+
const displayName = \`Connect(\${WrappedComponent.displayName || WrappedComponent.name || "Component"})\`;
|
|
950
|
+
function ConnectFunction(props) {
|
|
951
|
+
const cache = useRef({}).current;
|
|
952
|
+
const state = HOOK(selectState);
|
|
953
|
+
if (!cache.mappers) cache.mappers = {state: mapStateToProps ? mapper(mapStateToProps) : undefined, dispatch: typeof mapDispatchToProps === "function" ? mapper(mapDispatchToProps) : undefined};
|
|
954
|
+
const {state: mapState, dispatch: mapDispatch} = cache.mappers;
|
|
955
|
+
if (cache.props !== props) {
|
|
956
|
+
cache.props = props;
|
|
957
|
+
cache.ownProps = props;
|
|
958
|
+
if (forwardsRef) {
|
|
959
|
+
cache.ownProps = {};
|
|
960
|
+
for (const key of Object.keys(props)) if (key !== "reactReduxForwardedRef") cache.ownProps[key] = props[key];
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
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) : {};
|
|
966
|
+
cache.state = state;
|
|
967
|
+
cache.stateOwnProps = ownProps;
|
|
968
|
+
}
|
|
969
|
+
if (!cache.dispatchProps || (mapDispatch && mapDispatch.dependsOnOwnProps() && cache.dispatchOwnProps !== ownProps)) {
|
|
970
|
+
cache.dispatchProps = mapDispatch ? mapDispatch.map(HOOK.dispatch, ownProps) : mapDispatchToProps ? bound(mapDispatchToProps) : {dispatch: HOOK.dispatch};
|
|
971
|
+
cache.dispatchOwnProps = ownProps;
|
|
972
|
+
}
|
|
973
|
+
const merged = {...ownProps, ...cache.stateProps, ...cache.dispatchProps};
|
|
974
|
+
if (!cache.merged || !shallowEqual(cache.merged, merged)) cache.merged = merged;
|
|
975
|
+
if (!cache.element || cache.rendered !== cache.merged || cache.ref !== props.reactReduxForwardedRef) {
|
|
976
|
+
cache.rendered = cache.merged;
|
|
977
|
+
cache.ref = props.reactReduxForwardedRef;
|
|
978
|
+
cache.element = createElement(WrappedComponent, forwardsRef ? {...cache.merged, ref: cache.ref} : cache.merged);
|
|
979
|
+
}
|
|
980
|
+
return cache.element;
|
|
981
|
+
}
|
|
982
|
+
ConnectFunction.displayName = displayName;
|
|
983
|
+
const Connect = memo(ConnectFunction);
|
|
984
|
+
Connect.displayName = displayName;
|
|
985
|
+
Connect.WrappedComponent = WrappedComponent;
|
|
986
|
+
if (!forwardsRef) return hoistStatics(Connect, WrappedComponent);
|
|
987
|
+
const Forwarded = forwardRef((props, ref) => createElement(Connect, {...props, reactReduxForwardedRef: ref}));
|
|
988
|
+
Forwarded.displayName = displayName;
|
|
989
|
+
Forwarded.WrappedComponent = WrappedComponent;
|
|
990
|
+
return hoistStatics(Forwarded, WrappedComponent);
|
|
991
|
+
};
|
|
992
|
+
}`;
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, ctx: ExecutionContext): Promise<J | undefined> {
|
|
996
|
+
const store = p.store!;
|
|
997
|
+
const {hook, reducer, renderer, selectorHook, listeners} = p.reducerStore!;
|
|
998
|
+
const found = storeStatement(cu, store);
|
|
999
|
+
if (!found) return cu;
|
|
1000
|
+
const padded = cu.statements[found.index];
|
|
1001
|
+
const statement = padded.element;
|
|
1002
|
+
const cursor = new Cursor(statement, new Cursor(cu, undefined));
|
|
1003
|
+
// `configureStore` combines an object of reducers as `combineReducers` does
|
|
1004
|
+
const combined = store.reducerStore === "combined";
|
|
1005
|
+
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
1006
|
+
// redux-thunk runs a function with `dispatch` and `getState`, and passes any other action on to the store
|
|
1007
|
+
const thunk = store.reducerStore === "legacyThunk";
|
|
1008
|
+
// react-redux batches a store's updates, so that a parent renders before the children it may remove
|
|
1009
|
+
// Redux calls the listeners of `subscribe` after every dispatch, as they were when it began, before react-redux renders
|
|
1010
|
+
const update = `${hook}.setState(${reducer}(${hook}.getState(), action), true);`;
|
|
1011
|
+
const notified = listeners ? `${update}\n for (const listener of [...${listeners}.values()]) listener();` : update;
|
|
1012
|
+
const setState = renderer ? listeners ? `unstable_batchedUpdates(() => {\n ${notified}\n });` : `unstable_batchedUpdates(() => ${update.slice(0, -1)});` : notified;
|
|
1013
|
+
const members = `getState: ${hook}.getState, dispatch: ${hook}.dispatch` + (listeners ? `, subscribe: listener => {
|
|
1014
|
+
if (typeof listener !== "function") throw new Error("Expected the listener to be a function. Instead, received: '" + (listener === null ? "null" : Array.isArray(listener) ? "array" : typeof listener) + "'");
|
|
1015
|
+
const id = Symbol();
|
|
1016
|
+
${listeners}.set(id, listener);
|
|
1017
|
+
return () => {
|
|
1018
|
+
${listeners}.delete(id);
|
|
1019
|
+
};
|
|
1020
|
+
}` : "");
|
|
1021
|
+
const generated = [
|
|
1022
|
+
combined ? await template`const ${raw(reducer)} = combineReducers(${found.reducer});`.apply(statement, cursor) :
|
|
1023
|
+
await template`const ${raw(reducer)} = ${found.reducer};`.apply(statement, cursor),
|
|
1024
|
+
found.preloaded ?
|
|
1025
|
+
await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(${found.preloaded}, {type: "@@redux/INIT"}));`.apply(statement, cursor) :
|
|
1026
|
+
await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(undefined, {type: "@@redux/INIT"}));`.apply(statement, cursor),
|
|
1027
|
+
...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 ?
|
|
1037
|
+
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.");
|
|
1040
|
+
${raw(setState)}
|
|
1041
|
+
return action;
|
|
1042
|
+
};`.apply(statement, cursor) :
|
|
1043
|
+
await template`${raw(hook)}.dispatch = action => {
|
|
1044
|
+
if (typeof action === "function") return action(${raw(hook)}.dispatch, ${raw(hook)}.getState, undefined);
|
|
1045
|
+
${raw(setState)}
|
|
1046
|
+
return action;
|
|
1047
|
+
};`.apply(statement, cursor),
|
|
1048
|
+
statement.kind === JS.Kind.ExportAssignment ?
|
|
1049
|
+
await template`export default {${raw(members)}};`.apply(statement, cursor) :
|
|
1050
|
+
await template`${raw((statement as J.VariableDeclarations).modifiers.some(m => m.keyword === "export") ? "export " : "")}const ${raw(store.store)} = {${raw(members)}};`.apply(statement, cursor),
|
|
1051
|
+
...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)] : []
|
|
1053
|
+
];
|
|
1054
|
+
const statements: J.RightPadded<Statement>[] = [...cu.statements.slice(0, found.index)];
|
|
1055
|
+
for (let i = 0; i < generated.length; i++) {
|
|
1056
|
+
const prefixed = withPrefix(generated[i] as Statement, i === 0 ? statement.prefix : space("\n\n"));
|
|
1057
|
+
const element = i === 0 ? prefixed : await autoFormat(prefixed, ctx, undefined, new Cursor(cu, undefined)) as Statement;
|
|
1058
|
+
// A function declaration ends without the semicolon of the statement it follows
|
|
1059
|
+
statements.push(element.kind === J.Kind.MethodDeclaration ? {...padded, element, markers: emptyMarkers} : {...padded, element});
|
|
1060
|
+
}
|
|
1061
|
+
statements.push(...cu.statements.slice(found.index + 1));
|
|
1062
|
+
const result = await withoutUnused({...cu, statements} as JS.CompilationUnit, found.consts ?? new Set());
|
|
1063
|
+
return new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1064
|
+
override async visitJsCompilationUnit(unit: JS.CompilationUnit, q: ExecutionContext): Promise<J | undefined> {
|
|
1065
|
+
const quoteStyle = quoteOf(cu);
|
|
1066
|
+
maybeRemoveImport(this, RTK, "configureStore");
|
|
1067
|
+
for (const module of [REDUX, RTK]) for (const member of ["createStore", "legacy_createStore"]) maybeRemoveImport(this, module, member);
|
|
1068
|
+
if (legacy) {
|
|
1069
|
+
for (const member of ["applyMiddleware", "compose"]) maybeRemoveImport(this, REDUX, member);
|
|
1070
|
+
for (const member of ["default", "thunk"]) maybeRemoveImport(this, "redux-thunk", member);
|
|
1071
|
+
for (const module of ["redux-devtools-extension", "@redux-devtools/extension"]) {
|
|
1072
|
+
for (const member of ["composeWithDevTools", "devToolsEnhancer", "devToolsEnhancerLogOnlyInProduction"]) maybeRemoveImport(this, module, member);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
if (combined) maybeAddImport(this, {module: RTK, member: "combineReducers", onlyIfReferenced: false, quoteStyle});
|
|
1076
|
+
maybeAddImport(this, {module: ZUSTAND, member: "create", onlyIfReferenced: false, quoteStyle});
|
|
1077
|
+
if (selectorHook) for (const member of ["useRef", "useSyncExternalStore"]) maybeAddImport(this, {module: "react", member, onlyIfReferenced: false, quoteStyle});
|
|
1078
|
+
if (renderer) {
|
|
1079
|
+
for (const member of ["createElement", "forwardRef", "memo", "useRef"]) maybeAddImport(this, {module: "react", member, onlyIfReferenced: false, quoteStyle});
|
|
1080
|
+
maybeAddImport(this, {module: renderer, member: "unstable_batchedUpdates", onlyIfReferenced: false, quoteStyle});
|
|
1081
|
+
}
|
|
1082
|
+
return super.visitJsCompilationUnit(unit, q);
|
|
1083
|
+
}
|
|
1084
|
+
}().visit(result, ctx);
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* `<Provider store={store}>` of several children as the fragment `<>` of the same children, which renders them as the
|
|
1089
|
+
* provider did once nothing reads its context.
|
|
1090
|
+
*/
|
|
1091
|
+
function fragment(tag: JSX.Tag): JSX.Tag {
|
|
1092
|
+
// The parser makes `<>` and `</>` of empty names, with no space around them
|
|
1093
|
+
const empty = (): J.Empty => ({kind: J.Kind.Empty, id: randomId(), prefix: emptySpace, markers: emptyMarkers});
|
|
1094
|
+
return create(tag, draft => {
|
|
1095
|
+
draft.openName = {...draft.openName, before: emptySpace, element: empty()} as any;
|
|
1096
|
+
draft.closingName = {...draft.closingName!, before: emptySpace, element: empty()} as any;
|
|
1097
|
+
draft.attributes = [];
|
|
1098
|
+
draft.afterName = emptySpace as any;
|
|
1099
|
+
draft.afterClosingName = emptySpace as any;
|
|
1100
|
+
}) as JSX.Tag;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** Rewrites a source's uses of react-redux for a store that moves whole: the hooks read and dispatch to its zustand store. */
|
|
1104
|
+
async function convertReducerConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned, ctx: ExecutionContext): Promise<J | undefined> {
|
|
1105
|
+
const {hook, selectorHook} = p.reducerStore!;
|
|
1106
|
+
const source = scanned.sources.get(cu.sourcePath);
|
|
1107
|
+
// A read of the state keeps the store's own hook; another selector, on zustand 5, goes through the store's selector hook
|
|
1108
|
+
const reads = (selector: J | undefined) => !!selectorRead(selector) ||
|
|
1109
|
+
isIdentifier(selector) && !!source && readSelector(source, selector.simpleName, scanned.sources);
|
|
1110
|
+
const bindings = importBindings(cu);
|
|
1111
|
+
const followed = new Map(bindings.filter(b => b.module === REACT_REDUX || b.module.startsWith(".")).map(b => [b.local, b]));
|
|
1112
|
+
const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
|
|
1113
|
+
const removed = new Set<string>();
|
|
1114
|
+
// The store's hooks the source now calls
|
|
1115
|
+
const uses = new Set<string>();
|
|
1116
|
+
const result = await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1117
|
+
override async visitVariableDeclarations(declarations: J.VariableDeclarations, q: ExecutionContext): Promise<J | undefined> {
|
|
1118
|
+
const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
|
|
1119
|
+
if (variable && isDispatcherDeclaration(variable, followed)) {
|
|
1120
|
+
// `useDispatch` returns the store's `dispatch`, which the zustand store now holds
|
|
1121
|
+
removed.add("useDispatch");
|
|
1122
|
+
uses.add(hook);
|
|
1123
|
+
const initializer = variable.initializer!.element;
|
|
1124
|
+
const replaced = await template`${raw(hook)}.dispatch`.apply(initializer, new Cursor(initializer, this.cursor)) as J;
|
|
1125
|
+
return create(declarations, draft => {
|
|
1126
|
+
draft.variables[0].element.initializer!.element = withPrefix(replaced, initializer.prefix) as any;
|
|
1127
|
+
}) as J.VariableDeclarations;
|
|
1128
|
+
}
|
|
1129
|
+
return super.visitVariableDeclarations(declarations, q);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
override async visitMethodInvocation(call: J.MethodInvocation, q: ExecutionContext): Promise<J | undefined> {
|
|
1133
|
+
const visited = await super.visitMethodInvocation(call, q) as J.MethodInvocation;
|
|
1134
|
+
if (visited.select || !reactRedux(visited.name.simpleName, "useSelector")) return visited;
|
|
1135
|
+
removed.add("useSelector");
|
|
1136
|
+
const through = selectorHook && !reads(argumentsOf(visited)[0]) ? selectorHook : hook;
|
|
1137
|
+
uses.add(through);
|
|
1138
|
+
return create(visited, draft => {
|
|
1139
|
+
draft.name = {...draft.name, simpleName: through, fieldType: undefined, type: undefined} as any;
|
|
1140
|
+
draft.methodType = undefined;
|
|
1141
|
+
}) as J.MethodInvocation;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
override async visitJsxTag(tag: JSX.Tag, q: ExecutionContext): Promise<J | undefined> {
|
|
1145
|
+
const name = tag.openName.element;
|
|
1146
|
+
if (isIdentifier(name) && reactRedux(name.simpleName, "Provider")) {
|
|
1147
|
+
const child = providerChild(tag);
|
|
1148
|
+
if (child) {
|
|
1149
|
+
removed.add("Provider");
|
|
1150
|
+
return withPrefix(await this.visit(child, q, this.cursor) as JSX.Tag, tag.prefix);
|
|
1151
|
+
}
|
|
1152
|
+
if (providerChildren(tag)) {
|
|
1153
|
+
removed.add("Provider");
|
|
1154
|
+
return fragment(await super.visitJsxTag(tag, q) as JSX.Tag);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
return super.visitJsxTag(tag, q);
|
|
1158
|
+
}
|
|
1159
|
+
}().visit(cu, ctx) as JS.CompilationUnit;
|
|
1160
|
+
// `connect` stays as it is called, imported from the store's source, which declares it for the zustand store
|
|
1161
|
+
const connected = p.reducerStore!.renderer && bindings.some(b => b.module === REACT_REDUX && b.name === "connect") ?
|
|
1162
|
+
await (await new ChangeImport({oldModule: REACT_REDUX, oldMember: "connect", newModule: relativeSpecifier(cu.sourcePath, p.store!.path)}).editor()).visit(result, ctx) as JS.CompilationUnit :
|
|
1163
|
+
result;
|
|
1164
|
+
return await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1165
|
+
override async visitJsCompilationUnit(unit: JS.CompilationUnit, q: ExecutionContext): Promise<J | undefined> {
|
|
1166
|
+
for (const member of ["useSelector", "useDispatch", "Provider"]) {
|
|
1167
|
+
if (removed.has(member)) maybeRemoveImport(this, REACT_REDUX, member);
|
|
1168
|
+
}
|
|
1169
|
+
// The store's variable stays, so its import goes only where nothing uses it any more
|
|
1170
|
+
if (removed.has("Provider")) {
|
|
1171
|
+
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);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
for (const member of [hook, selectorHook]) {
|
|
1176
|
+
if (member && uses.has(member)) maybeAddImport(this, {module: relativeSpecifier(cu.sourcePath, p.store!.path), member, onlyIfReferenced: false, quoteStyle: quoteOf(cu)});
|
|
1177
|
+
}
|
|
1178
|
+
return super.visitJsCompilationUnit(unit, q);
|
|
1179
|
+
}
|
|
1180
|
+
}().visit(connected, ctx);
|
|
1181
|
+
}
|