@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,4 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
2
8
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
9
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
10
|
return new (P || (P = Promise))(function (resolve, reject) {
|
|
@@ -9,7 +15,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
15
|
});
|
|
10
16
|
};
|
|
11
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.ReduxToZustand = exports.AddImmer = exports.AddZustand4 = exports.AddZustand = void 0;
|
|
18
|
+
exports.CONNECT = exports.SELECTOR = exports.ReduxToZustand = exports.AddImmer = exports.AddZustand4 = exports.AddZustand = void 0;
|
|
13
19
|
const rewrite_1 = require("@openrewrite/rewrite");
|
|
14
20
|
const javascript_1 = require("@openrewrite/rewrite/javascript");
|
|
15
21
|
const java_1 = require("@openrewrite/rewrite/java");
|
|
@@ -25,8 +31,7 @@ const zustand_plan_1 = require("./zustand-plan");
|
|
|
25
31
|
const ZUSTAND = "zustand";
|
|
26
32
|
const IMMER = "immer";
|
|
27
33
|
const ZUSTAND_5 = {
|
|
28
|
-
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies",
|
|
29
|
-
onlyIfResolving: ["react@>=18.0.0"]
|
|
34
|
+
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies", onlyIfResolving: ["react@>=18.0.0"]
|
|
30
35
|
};
|
|
31
36
|
const ZUSTAND_4 = Object.assign(Object.assign({}, ZUSTAND_5), { version: "^4.5.7", onlyIfResolving: ["react@>=16.8.0 <18"] });
|
|
32
37
|
const IMMER_10 = Object.assign(Object.assign({}, ZUSTAND_5), { packageName: IMMER, version: "^10.1.3", onlyIfResolving: ["react@>=16.8.0"] });
|
|
@@ -39,6 +44,9 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
39
44
|
this.landed = new Set();
|
|
40
45
|
this.held = [];
|
|
41
46
|
this.locks = [];
|
|
47
|
+
this.owned = new Set();
|
|
48
|
+
this.workspaces = new Map();
|
|
49
|
+
this.pending = [];
|
|
42
50
|
this.unfit = new Set();
|
|
43
51
|
}
|
|
44
52
|
initialValue() {
|
|
@@ -47,6 +55,9 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
47
55
|
this.unfit.clear();
|
|
48
56
|
this.held.length = 0;
|
|
49
57
|
this.locks.length = 0;
|
|
58
|
+
this.owned.clear();
|
|
59
|
+
this.workspaces.clear();
|
|
60
|
+
this.pending.length = 0;
|
|
50
61
|
(_a = this.forecast.refused) === null || _a === void 0 ? void 0 : _a.clear();
|
|
51
62
|
return super.initialValue();
|
|
52
63
|
}
|
|
@@ -55,6 +66,8 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
55
66
|
this.held.push(manifest);
|
|
56
67
|
return false;
|
|
57
68
|
}
|
|
69
|
+
if (/(^|\/)pnpm-workspace\.yaml$/.test(manifest.sourcePath))
|
|
70
|
+
this.pending.push(manifest);
|
|
58
71
|
if (LOCKFILE.test(manifest.sourcePath))
|
|
59
72
|
this.locks.push(manifest);
|
|
60
73
|
return true;
|
|
@@ -64,6 +77,8 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
64
77
|
return false;
|
|
65
78
|
if (LOCKFILE.test(manifest.sourcePath) && this.unfit.has(manifest.sourcePath.slice(0, manifest.sourcePath.lastIndexOf("/") + 1)))
|
|
66
79
|
return false;
|
|
80
|
+
if (LOCKFILE.test(manifest.sourcePath) && !this.owned.has(manifest.sourcePath))
|
|
81
|
+
return false;
|
|
67
82
|
const refused = this.forecast.refused;
|
|
68
83
|
if (!(refused === null || refused === void 0 ? void 0 : refused.size))
|
|
69
84
|
return true;
|
|
@@ -71,6 +86,9 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
71
86
|
return !refused.has(packageRoot(manifest.sourcePath));
|
|
72
87
|
return ![...refused.values()].some(refusal => refusal.lock === manifest.sourcePath);
|
|
73
88
|
}
|
|
89
|
+
skipped() {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
74
92
|
fits(root) {
|
|
75
93
|
var _a, _b, _c, _d;
|
|
76
94
|
const declared = (_b = (_a = this.forecast).react) === null || _b === void 0 ? void 0 : _b.call(_a, root);
|
|
@@ -82,20 +100,40 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
82
100
|
}
|
|
83
101
|
lockOf(root) {
|
|
84
102
|
const directory = (path) => path.slice(0, path.lastIndexOf("/") + 1);
|
|
85
|
-
return this.locks.filter(lock =>
|
|
86
|
-
|
|
103
|
+
return this.locks.filter(lock => {
|
|
104
|
+
var _a;
|
|
105
|
+
const base = directory(lock.sourcePath);
|
|
106
|
+
return root === base || root.startsWith(base) && member((_a = this.workspaces.get(base)) !== null && _a !== void 0 ? _a : [], root.slice(base.length, -1));
|
|
107
|
+
}).sort((a, b) => b.sourcePath.length - a.sourcePath.length)[0];
|
|
108
|
+
}
|
|
109
|
+
readWorkspaces() {
|
|
110
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
111
|
+
var _a;
|
|
112
|
+
for (const manifest of this.held) {
|
|
113
|
+
const globs = workspaceGlobs(yield parsed(manifest));
|
|
114
|
+
if (globs.length)
|
|
115
|
+
this.workspaces.set(packageRoot(manifest.sourcePath), globs);
|
|
116
|
+
}
|
|
117
|
+
for (const file of this.pending) {
|
|
118
|
+
const root = file.sourcePath.slice(0, -"pnpm-workspace.yaml".length);
|
|
119
|
+
this.workspaces.set(root, [...(_a = this.workspaces.get(root)) !== null && _a !== void 0 ? _a : [], ...pnpmPackages(yield rewrite_1.TreePrinters.print(file))]);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
87
122
|
}
|
|
88
123
|
generate(acc, ctx) {
|
|
89
124
|
const _super = Object.create(null, {
|
|
90
125
|
generate: { get: () => super.generate }
|
|
91
126
|
});
|
|
92
127
|
return __awaiter(this, void 0, void 0, function* () {
|
|
93
|
-
var _a, _b, _c, _d;
|
|
94
|
-
const converting = (_c = yield ((_b = (_a = this.forecast).converting) === null || _b === void 0 ? void 0 : _b.call(_a))) !== null && _c !== void 0 ? _c :
|
|
128
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
129
|
+
const converting = new Set((_c = yield ((_b = (_a = this.forecast).converting) === null || _b === void 0 ? void 0 : _b.call(_a))) !== null && _c !== void 0 ? _c : []);
|
|
130
|
+
for (const root of this.skipped())
|
|
131
|
+
converting.delete(root);
|
|
95
132
|
for (const root of converting)
|
|
96
133
|
if (!this.fits(root))
|
|
97
134
|
this.unfit.add(root);
|
|
98
135
|
const forwarded = this.held.filter(manifest => converting.has(packageRoot(manifest.sourcePath)) && !this.unfit.has(packageRoot(manifest.sourcePath)));
|
|
136
|
+
yield this.readWorkspaces();
|
|
99
137
|
const scanner = yield this.java.scanner(acc);
|
|
100
138
|
for (const manifest of forwarded)
|
|
101
139
|
yield scanner.visit(manifest, ctx);
|
|
@@ -103,14 +141,22 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
103
141
|
const editor = yield this.java.editorWithData(acc);
|
|
104
142
|
for (const manifest of forwarded) {
|
|
105
143
|
const edited = yield editor.visit(manifest, ctx);
|
|
106
|
-
if (!edited || edited === manifest
|
|
144
|
+
if (!edited || edited === manifest)
|
|
107
145
|
continue;
|
|
108
146
|
const root = packageRoot(manifest.sourcePath);
|
|
147
|
+
if (!(yield declares(edited, this.addition.packageName))) {
|
|
148
|
+
const warning = newWarning(manifest, edited);
|
|
149
|
+
if (warning)
|
|
150
|
+
(_d = this.forecast.refused) === null || _d === void 0 ? void 0 : _d.set(root, { message: warning.message, lock: (_f = (_e = this.lockOf(root)) === null || _e === void 0 ? void 0 : _e.sourcePath) !== null && _f !== void 0 ? _f : manifest.sourcePath });
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
109
153
|
const lock = this.lockOf(root);
|
|
154
|
+
if (lock)
|
|
155
|
+
this.owned.add(lock.sourcePath);
|
|
110
156
|
const regenerated = lock ? yield editor.visit(lock, ctx) : undefined;
|
|
111
157
|
const warning = regenerated === null || regenerated === void 0 ? void 0 : regenerated.markers.markers.find(marker => marker.kind === rewrite_1.MarkersKind.MarkupWarn || marker.kind === rewrite_1.MarkersKind.MarkupError);
|
|
112
158
|
if (warning)
|
|
113
|
-
(
|
|
159
|
+
(_g = this.forecast.refused) === null || _g === void 0 ? void 0 : _g.set(root, { message: warning.message, lock: lock.sourcePath });
|
|
114
160
|
else
|
|
115
161
|
this.landed.add(root);
|
|
116
162
|
}
|
|
@@ -119,12 +165,17 @@ class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
|
119
165
|
});
|
|
120
166
|
}
|
|
121
167
|
}
|
|
168
|
+
function newWarning(before, after) {
|
|
169
|
+
const had = new Set(before.markers.markers.map(marker => marker.id));
|
|
170
|
+
return after.markers.markers.find(marker => !had.has(marker.id) &&
|
|
171
|
+
(marker.kind === rewrite_1.MarkersKind.MarkupWarn || marker.kind === rewrite_1.MarkersKind.MarkupError));
|
|
172
|
+
}
|
|
122
173
|
class AddZustand extends ZustandDependency {
|
|
123
174
|
constructor(forecast = {}) {
|
|
124
175
|
super(ZUSTAND_5, forecast);
|
|
125
176
|
this.name = "org.openrewrite.react.migrate.add-zustand";
|
|
126
177
|
this.displayName = "Add `zustand` where a Redux store is migrated";
|
|
127
|
-
this.description = "Adds `zustand` 5 to packages that
|
|
178
|
+
this.description = "Adds `zustand` 5 to packages that resolve React 18 or later, where a Redux store moves to zustand.";
|
|
128
179
|
}
|
|
129
180
|
}
|
|
130
181
|
exports.AddZustand = AddZustand;
|
|
@@ -133,7 +184,7 @@ class AddZustand4 extends ZustandDependency {
|
|
|
133
184
|
super(ZUSTAND_4, forecast);
|
|
134
185
|
this.name = "org.openrewrite.react.migrate.add-zustand-4";
|
|
135
186
|
this.displayName = "Add `zustand` 4 where a Redux store is migrated on React 16.8 to 17";
|
|
136
|
-
this.description = "Adds `zustand` 4 to packages that
|
|
187
|
+
this.description = "Adds `zustand` 4 to packages that resolve React 16.8 to 17, where a Redux store moves to zustand.";
|
|
137
188
|
}
|
|
138
189
|
}
|
|
139
190
|
exports.AddZustand4 = AddZustand4;
|
|
@@ -142,7 +193,11 @@ class AddImmer extends ZustandDependency {
|
|
|
142
193
|
super(IMMER_10, forecast);
|
|
143
194
|
this.name = "org.openrewrite.react.migrate.add-immer";
|
|
144
195
|
this.displayName = "Add `immer` where a Redux store is migrated";
|
|
145
|
-
this.description = "Adds `immer` 10 to packages that
|
|
196
|
+
this.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`.";
|
|
197
|
+
}
|
|
198
|
+
skipped() {
|
|
199
|
+
var _a;
|
|
200
|
+
return (_a = this.forecast.withoutImmer) !== null && _a !== void 0 ? _a : [];
|
|
146
201
|
}
|
|
147
202
|
}
|
|
148
203
|
exports.AddImmer = AddImmer;
|
|
@@ -155,16 +210,18 @@ const ADDS_DEPENDENCIES = (() => {
|
|
|
155
210
|
}
|
|
156
211
|
})();
|
|
157
212
|
class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
158
|
-
constructor() {
|
|
159
|
-
|
|
213
|
+
constructor(options) {
|
|
214
|
+
var _a;
|
|
215
|
+
super(options);
|
|
160
216
|
this.name = "org.openrewrite.react.migrate.redux-to-zustand";
|
|
161
217
|
this.displayName = "Migrate Redux Toolkit slices to zustand";
|
|
162
|
-
this.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
|
|
163
|
-
this.forecast = { refused: new Map() };
|
|
218
|
+
this.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.";
|
|
219
|
+
this.forecast = { refused: new Map(), withoutImmer: new Set() };
|
|
164
220
|
this.storeSources = [];
|
|
165
221
|
this.steps = ADDS_DEPENDENCIES ? { zustand: new AddZustand(this.forecast), zustand4: new AddZustand4(this.forecast), immer: new AddImmer(this.forecast) } : undefined;
|
|
166
222
|
this.stores = new rewrite_1.DataTable(redux_stores_1.REDUX_STORES_TABLE, "Redux stores", "The Redux stores of the repository and whether each one's setup can move to zustand, with one row for each reason it can't.", redux_stores_1.ReduxStoreRow);
|
|
167
223
|
this.plans = new WeakMap();
|
|
224
|
+
(_a = this.wholeStores) !== null && _a !== void 0 ? _a : (this.wholeStores = true);
|
|
168
225
|
}
|
|
169
226
|
initialValue() {
|
|
170
227
|
this.storeSources.length = 0;
|
|
@@ -176,8 +233,13 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
176
233
|
let forecast;
|
|
177
234
|
this.asked = undefined;
|
|
178
235
|
this.forecast.react = root => { var _a; return (_a = scanned.packages.get(root)) === null || _a === void 0 ? void 0 : _a.react; };
|
|
179
|
-
this.forecast.converting = () => forecast !== null && forecast !== void 0 ? forecast : (forecast = this.planned(scanned, true)
|
|
180
|
-
|
|
236
|
+
this.forecast.converting = () => forecast !== null && forecast !== void 0 ? forecast : (forecast = this.planned(scanned, true).then(plans => {
|
|
237
|
+
this.forecast.withoutImmer.clear();
|
|
238
|
+
for (const p of plans)
|
|
239
|
+
if (p.reducerStore)
|
|
240
|
+
this.forecast.withoutImmer.add(packageOf(scanned.packages, p.store.path));
|
|
241
|
+
return this.asked = new Set(plans.filter(p => p.store).map(p => packageOf(scanned.packages, p.store.path)));
|
|
242
|
+
}));
|
|
181
243
|
const sources = yield (0, rewrite_2.check)((0, rewrite_2.not)((0, javascript_1.isVendoredOrBundled)()), new class extends javascript_1.JavaScriptVisitor {
|
|
182
244
|
visitJsCompilationUnit(cu) {
|
|
183
245
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -199,7 +261,7 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
199
261
|
if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
|
|
200
262
|
const declared = (0, javascript_1.findNodeResolutionResult)(doc) ? undefined : yield declaredDependencies(doc);
|
|
201
263
|
const get = (name) => declared ? declared[name] : version(doc, name);
|
|
202
|
-
scanned.packages.set(packageRoot(doc.sourcePath), { react: get("react"), zustand: get(ZUSTAND), immer: get(IMMER) });
|
|
264
|
+
scanned.packages.set(packageRoot(doc.sourcePath), { react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER) });
|
|
203
265
|
}
|
|
204
266
|
return doc;
|
|
205
267
|
});
|
|
@@ -235,14 +297,22 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
235
297
|
if (facts)
|
|
236
298
|
facts.stores = yield (0, zustand_plan_1.storeFacts)(cu, scanned.modules);
|
|
237
299
|
}
|
|
238
|
-
return (0, zustand_plan_1.planPackages)(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path), storePath => this.dependencies(scanned, storePath, forecast)
|
|
300
|
+
return (0, zustand_plan_1.planPackages)(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path), (storePath, immer) => this.dependencies(scanned, storePath, forecast, immer), this.wholeStores !== false, storePath => {
|
|
301
|
+
var _a;
|
|
302
|
+
const facts = scanned.packages.get((_a = packageOf(scanned.packages, storePath)) !== null && _a !== void 0 ? _a : "");
|
|
303
|
+
return (facts === null || facts === void 0 ? void 0 : facts.reactNative) ? "react-native" : (facts === null || facts === void 0 ? void 0 : facts.reactDom) ? "react-dom" : undefined;
|
|
304
|
+
}, storePath => {
|
|
305
|
+
var _a, _b, _c;
|
|
306
|
+
const facts = scanned.packages.get((_a = packageOf(scanned.packages, storePath)) !== null && _a !== void 0 ? _a : "");
|
|
307
|
+
return (facts === null || facts === void 0 ? void 0 : facts.zustand) !== undefined ? ((_b = major(facts.zustand)) !== null && _b !== void 0 ? _b : 0) >= 5 : ((_c = major(facts === null || facts === void 0 ? void 0 : facts.react)) !== null && _c !== void 0 ? _c : 0) >= 18;
|
|
308
|
+
});
|
|
239
309
|
}))();
|
|
240
310
|
if (!forecast)
|
|
241
311
|
this.plans.set(scanned, result);
|
|
242
312
|
return result;
|
|
243
313
|
});
|
|
244
314
|
}
|
|
245
|
-
dependencies(scanned, storePath, forecast) {
|
|
315
|
+
dependencies(scanned, storePath, forecast, needsImmer = true) {
|
|
246
316
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
247
317
|
const root = packageOf(scanned.packages, storePath);
|
|
248
318
|
const facts = root !== undefined ? scanned.packages.get(root) : undefined;
|
|
@@ -259,7 +329,7 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
259
329
|
: landed(react >= 18 ? (_f = this.steps) === null || _f === void 0 ? void 0 : _f.zustand : (_g = this.steps) === null || _g === void 0 ? void 0 : _g.zustand4);
|
|
260
330
|
if (!zustand)
|
|
261
331
|
return { reason: "DEPENDENCY", detail: facts.zustand ? `zustand ${facts.zustand} doesn't support React ${react}` : "zustand can't be added" };
|
|
262
|
-
const immer = facts.immer !== undefined ? ((_h = major(facts.immer)) !== null && _h !== void 0 ? _h : 0) >= 9 : landed((_j = this.steps) === null || _j === void 0 ? void 0 : _j.immer);
|
|
332
|
+
const immer = !needsImmer || (facts.immer !== undefined ? ((_h = major(facts.immer)) !== null && _h !== void 0 ? _h : 0) >= 9 : landed((_j = this.steps) === null || _j === void 0 ? void 0 : _j.immer));
|
|
263
333
|
if (!immer)
|
|
264
334
|
return { reason: "DEPENDENCY", detail: facts.immer ? `immer ${facts.immer} is older than 9` : "immer can't be added" };
|
|
265
335
|
return undefined;
|
|
@@ -282,7 +352,7 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
282
352
|
reported.add(key);
|
|
283
353
|
const p = (_b = plans.find(candidate => candidate.store === store)) !== null && _b !== void 0 ? _b : plans.find(candidate => candidate.blocked.has(store));
|
|
284
354
|
const findings = (p === null || p === void 0 ? void 0 : p.store) === store ? [] : (_c = p === null || p === void 0 ? void 0 : p.blocked.get(store)) !== null && _c !== void 0 ? _c : store.findings;
|
|
285
|
-
const rows = findings.length === 0 ? [{ reason: "SLICE_STORE", detail: "" }] : findings;
|
|
355
|
+
const rows = findings.length === 0 ? [{ reason: (p === null || p === void 0 ? void 0 : p.reducerStore) ? "REDUCER_STORE" : "SLICE_STORE", detail: "" }] : findings;
|
|
286
356
|
for (const { reason, detail } of rows) {
|
|
287
357
|
stores.insertRow(ctx, {
|
|
288
358
|
sourcePath: store.path, store: store.store, api: store.api,
|
|
@@ -294,6 +364,8 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
294
364
|
const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
|
|
295
365
|
if (!(p === null || p === void 0 ? void 0 : p.store))
|
|
296
366
|
return cu;
|
|
367
|
+
if (p.reducerStore)
|
|
368
|
+
return cu.sourcePath === p.store.path ? convertReducerStore(cu, p, ctx) : convertReducerConsumer(cu, p, scanned, ctx);
|
|
297
369
|
if (cu.sourcePath === p.store.path)
|
|
298
370
|
return undefined;
|
|
299
371
|
const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
|
|
@@ -312,6 +384,14 @@ class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
|
312
384
|
}
|
|
313
385
|
}
|
|
314
386
|
exports.ReduxToZustand = ReduxToZustand;
|
|
387
|
+
__decorate([
|
|
388
|
+
(0, rewrite_1.Option)({
|
|
389
|
+
displayName: "Move stores whole",
|
|
390
|
+
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.",
|
|
391
|
+
required: false,
|
|
392
|
+
type: "Boolean"
|
|
393
|
+
})
|
|
394
|
+
], ReduxToZustand.prototype, "wholeStores", void 0);
|
|
315
395
|
const CONVERSION_ACTIONS = {
|
|
316
396
|
MULTIPLE_STORES: "Convert by hand, or one store at a time: the uses of react-redux can't be told apart by store.",
|
|
317
397
|
STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module; a zustand store is a module-level singleton.",
|
|
@@ -327,10 +407,10 @@ const CONVERSION_ACTIONS = {
|
|
|
327
407
|
ACTIONS_EXPORT: "Export the action creators as `export const {a, b} = slice.actions`, under their own names.",
|
|
328
408
|
UNKNOWN_ACTION: "Remove the import of an action creator that has no reducer, which is `undefined`.",
|
|
329
409
|
SLICE_USE: "Use the slice only through its action creators and the store; other uses of the slice object are converted by hand.",
|
|
330
|
-
STORE_USE: "Use the store only in `<Provider store>`, `store.getState().key` and `store.dispatch(action())`.",
|
|
331
|
-
REACT_REDUX_USE: "Replace `
|
|
410
|
+
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`.",
|
|
411
|
+
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.",
|
|
332
412
|
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.",
|
|
333
|
-
SELECTOR: "
|
|
413
|
+
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.",
|
|
334
414
|
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.",
|
|
335
415
|
TYPESCRIPT: "TypeScript sources are not converted yet.",
|
|
336
416
|
NO_PACKAGE: "Add a `package.json` for the store's package.",
|
|
@@ -340,6 +420,42 @@ const CONVERSION_ACTIONS = {
|
|
|
340
420
|
function packageRoot(manifestPath) {
|
|
341
421
|
return manifestPath.slice(0, -"package.json".length);
|
|
342
422
|
}
|
|
423
|
+
function parsed(doc) {
|
|
424
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
425
|
+
try {
|
|
426
|
+
return JSON.parse(yield rewrite_1.TreePrinters.print(doc));
|
|
427
|
+
}
|
|
428
|
+
catch (_a) {
|
|
429
|
+
return {};
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
function workspaceGlobs(manifest) {
|
|
434
|
+
var _a;
|
|
435
|
+
const workspaces = Array.isArray(manifest === null || manifest === void 0 ? void 0 : manifest.workspaces) ? manifest.workspaces : (_a = manifest === null || manifest === void 0 ? void 0 : manifest.workspaces) === null || _a === void 0 ? void 0 : _a.packages;
|
|
436
|
+
return Array.isArray(workspaces) ? workspaces.filter((glob) => typeof glob === "string") : [];
|
|
437
|
+
}
|
|
438
|
+
function pnpmPackages(yaml) {
|
|
439
|
+
var _a, _b;
|
|
440
|
+
const globs = [];
|
|
441
|
+
let inPackages = false;
|
|
442
|
+
for (const line of yaml.split(/\r?\n/)) {
|
|
443
|
+
if (/^\S/.test(line))
|
|
444
|
+
inPackages = /^packages\s*:/.test(line);
|
|
445
|
+
const entry = inPackages && /^\s+-\s*(?:'([^']*)'|"([^"]*)"|([^#\s]+))/.exec(line);
|
|
446
|
+
if (entry)
|
|
447
|
+
globs.push((_b = (_a = entry[1]) !== null && _a !== void 0 ? _a : entry[2]) !== null && _b !== void 0 ? _b : entry[3]);
|
|
448
|
+
}
|
|
449
|
+
return globs;
|
|
450
|
+
}
|
|
451
|
+
function member(globs, path) {
|
|
452
|
+
const matches = (glob) => {
|
|
453
|
+
const pattern = glob.replace(/^\.\//, "").replace(/\/+$/, "").replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
454
|
+
.replace(/\*\*\/?|\*|\?/g, token => token.startsWith("**") ? "(?:.*/)?" + (token.endsWith("/") ? "" : ".*") : token === "*" ? "[^/]*" : "[^/]");
|
|
455
|
+
return new RegExp(`^${pattern}$`).test(path);
|
|
456
|
+
};
|
|
457
|
+
return globs.some(glob => !glob.startsWith("!") && matches(glob)) && !globs.some(glob => glob.startsWith("!") && matches(glob.slice(1)));
|
|
458
|
+
}
|
|
343
459
|
function packageOf(packages, sourcePath) {
|
|
344
460
|
return [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length)[0];
|
|
345
461
|
}
|
|
@@ -603,6 +719,11 @@ function convertConsumer(cu, p, scanned, ctx) {
|
|
|
603
719
|
removed.add("store");
|
|
604
720
|
return withPrefix(yield this.visit(child, q, this.cursor), tag.prefix);
|
|
605
721
|
}
|
|
722
|
+
if ((0, zustand_plan_1.providerChildren)(tag)) {
|
|
723
|
+
removed.add("Provider");
|
|
724
|
+
removed.add("store");
|
|
725
|
+
return fragment(yield _super.visitJsxTag.call(this, tag, q));
|
|
726
|
+
}
|
|
606
727
|
}
|
|
607
728
|
return _super.visitJsxTag.call(this, tag, q);
|
|
608
729
|
});
|
|
@@ -651,4 +772,375 @@ function replaceTree(root, target, replacement) {
|
|
|
651
772
|
replace(draft);
|
|
652
773
|
});
|
|
653
774
|
}
|
|
775
|
+
function storeStatement(cu, store) {
|
|
776
|
+
var _a, _b;
|
|
777
|
+
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
778
|
+
const functions = (0, redux_stores_1.storeFunctions)(cu);
|
|
779
|
+
const names = legacy ? functions.legacy : functions.configure;
|
|
780
|
+
const isStoreCall = (node) => (node === null || node === void 0 ? void 0 : node.kind) === java_1.J.Kind.MethodInvocation &&
|
|
781
|
+
!node.select && names.has(node.name.simpleName);
|
|
782
|
+
for (let index = 0; index < cu.statements.length; index++) {
|
|
783
|
+
const statement = cu.statements[index].element;
|
|
784
|
+
const call = statement.kind === javascript_1.JS.Kind.ExportAssignment ? statement.expression.element :
|
|
785
|
+
statement.kind === java_1.J.Kind.VariableDeclarations && statement.variables.length === 1 &&
|
|
786
|
+
(0, java_1.isIdentifier)(statement.variables[0].element.name) &&
|
|
787
|
+
statement.variables[0].element.name.simpleName === store.store
|
|
788
|
+
? (_a = statement.variables[0].element.initializer) === null || _a === void 0 ? void 0 : _a.element : undefined;
|
|
789
|
+
if (!isStoreCall(call))
|
|
790
|
+
continue;
|
|
791
|
+
if (legacy) {
|
|
792
|
+
const args = (0, zustand_plan_1.argumentsOf)(call);
|
|
793
|
+
const preloaded = args.length === 3 || args.length === 2 && (0, redux_stores_1.preloadedValue)(args[1], cu) ? args[1] : undefined;
|
|
794
|
+
const enhancer = args.length === 3 || args.length === 2 && !preloaded ? (0, redux_stores_1.legacyEnhancer)(args[args.length - 1], cu) : undefined;
|
|
795
|
+
return { index, call, reducer: Object.assign(Object.assign({}, args[0]), { prefix: java_1.emptySpace }), preloaded: preloaded && Object.assign(Object.assign({}, preloaded), { prefix: java_1.emptySpace }), consts: enhancer && !("unsupported" in enhancer) ? enhancer.consts : new Set() };
|
|
796
|
+
}
|
|
797
|
+
const reducer = (_b = (0, redux_stores_1.objectProperties)((0, zustand_plan_1.argumentsOf)(call)[0])) === null || _b === void 0 ? void 0 : _b.get("reducer");
|
|
798
|
+
return reducer ? { index, call, reducer } : undefined;
|
|
799
|
+
}
|
|
800
|
+
return undefined;
|
|
801
|
+
}
|
|
802
|
+
function withoutUnused(cu, names) {
|
|
803
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
804
|
+
const declared = (statement) => statement.kind === java_1.J.Kind.VariableDeclarations && statement.variables.length === 1 &&
|
|
805
|
+
(0, java_1.isIdentifier)(statement.variables[0].element.name) ?
|
|
806
|
+
statement.variables[0].element.name.simpleName : undefined;
|
|
807
|
+
for (let removed = true; removed;) {
|
|
808
|
+
const counts = new Map();
|
|
809
|
+
yield new class extends javascript_1.JavaScriptVisitor {
|
|
810
|
+
visitIdentifier(identifier, p) {
|
|
811
|
+
const _super = Object.create(null, {
|
|
812
|
+
visitIdentifier: { get: () => super.visitIdentifier }
|
|
813
|
+
});
|
|
814
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
815
|
+
var _a;
|
|
816
|
+
counts.set(identifier.simpleName, ((_a = counts.get(identifier.simpleName)) !== null && _a !== void 0 ? _a : 0) + 1);
|
|
817
|
+
return _super.visitIdentifier.call(this, identifier, p);
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
}().visit(cu, undefined);
|
|
821
|
+
const statements = cu.statements.filter(padded => {
|
|
822
|
+
const name = declared(padded.element);
|
|
823
|
+
return !name || !names.has(name) || counts.get(name) !== 1;
|
|
824
|
+
});
|
|
825
|
+
removed = statements.length < cu.statements.length;
|
|
826
|
+
cu = Object.assign(Object.assign({}, cu), { statements });
|
|
827
|
+
}
|
|
828
|
+
return cu;
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
exports.SELECTOR = `export function SELECTOR_HOOK(selector) {
|
|
832
|
+
const last = useRef(undefined);
|
|
833
|
+
const select = () => {
|
|
834
|
+
const state = HOOK.getState();
|
|
835
|
+
const kept = last.current;
|
|
836
|
+
if (kept && kept.state === state && kept.selector === selector) return kept.selection;
|
|
837
|
+
const selection = selector(state);
|
|
838
|
+
last.current = {state, selector, selection};
|
|
839
|
+
return selection;
|
|
840
|
+
};
|
|
841
|
+
return useSyncExternalStore(HOOK.subscribe, select, select);
|
|
842
|
+
}`;
|
|
843
|
+
exports.CONNECT = `export function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) {
|
|
844
|
+
const forwardsRef = Boolean(options && options.forwardRef);
|
|
845
|
+
const selectState = mapStateToProps ? state => state : () => undefined;
|
|
846
|
+
const dependsOnOwnProps = map => map.dependsOnOwnProps !== undefined && map.dependsOnOwnProps !== null ? Boolean(map.dependsOnOwnProps) : map.length !== 1;
|
|
847
|
+
// A map that returns a function on its first call is a factory of the map to use
|
|
848
|
+
const mapper = map => {
|
|
849
|
+
let actual = map;
|
|
850
|
+
let first = true;
|
|
851
|
+
const run = (value, ownProps) => dependsOnOwnProps(actual) ? actual(value, ownProps) : actual(value);
|
|
852
|
+
return {
|
|
853
|
+
map(value, ownProps) {
|
|
854
|
+
let props = run(value, ownProps);
|
|
855
|
+
if (first) {
|
|
856
|
+
first = false;
|
|
857
|
+
if (typeof props === "function") {
|
|
858
|
+
actual = props;
|
|
859
|
+
props = run(value, ownProps);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
return props;
|
|
863
|
+
},
|
|
864
|
+
dependsOnOwnProps: () => dependsOnOwnProps(actual)
|
|
865
|
+
};
|
|
866
|
+
};
|
|
867
|
+
const bound = actionCreators => {
|
|
868
|
+
const props = {};
|
|
869
|
+
for (const key of Object.keys(actionCreators)) {
|
|
870
|
+
const actionCreator = actionCreators[key];
|
|
871
|
+
if (typeof actionCreator === "function") props[key] = (...args) => HOOK.dispatch(actionCreator(...args));
|
|
872
|
+
}
|
|
873
|
+
return props;
|
|
874
|
+
};
|
|
875
|
+
const shallowEqual = (a, b) => {
|
|
876
|
+
const keys = Object.keys(a);
|
|
877
|
+
return keys.length === Object.keys(b).length && keys.every(key => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
|
|
878
|
+
};
|
|
879
|
+
const notHoisted = ["$$typeof", "render", "compare", "type", "childContextTypes", "contextType", "contextTypes", "defaultProps", "displayName",
|
|
880
|
+
"getDefaultProps", "getDerivedStateFromError", "getDerivedStateFromProps", "mixins", "propTypes", "name", "length", "prototype", "caller",
|
|
881
|
+
"callee", "arguments", "arity"];
|
|
882
|
+
const hoistStatics = (target, source) => {
|
|
883
|
+
for (let from = source; from && from !== Function.prototype && from !== Object.prototype; from = Object.getPrototypeOf(from)) {
|
|
884
|
+
for (const key of [...Object.getOwnPropertyNames(from), ...Object.getOwnPropertySymbols(from)]) {
|
|
885
|
+
if (!notHoisted.includes(key) && !Object.prototype.hasOwnProperty.call(target, key)) Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(from, key));
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
return target;
|
|
889
|
+
};
|
|
890
|
+
return WrappedComponent => {
|
|
891
|
+
const displayName = \`Connect(\${WrappedComponent.displayName || WrappedComponent.name || "Component"})\`;
|
|
892
|
+
function ConnectFunction(props) {
|
|
893
|
+
const cache = useRef({}).current;
|
|
894
|
+
const state = HOOK(selectState);
|
|
895
|
+
if (!cache.mappers) cache.mappers = {state: mapStateToProps ? mapper(mapStateToProps) : undefined, dispatch: typeof mapDispatchToProps === "function" ? mapper(mapDispatchToProps) : undefined};
|
|
896
|
+
const {state: mapState, dispatch: mapDispatch} = cache.mappers;
|
|
897
|
+
if (cache.props !== props) {
|
|
898
|
+
cache.props = props;
|
|
899
|
+
cache.ownProps = props;
|
|
900
|
+
if (forwardsRef) {
|
|
901
|
+
cache.ownProps = {};
|
|
902
|
+
for (const key of Object.keys(props)) if (key !== "reactReduxForwardedRef") cache.ownProps[key] = props[key];
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
const ownProps = cache.ownProps;
|
|
906
|
+
if (!cache.stateProps || (mapState && (cache.state !== state || (mapState.dependsOnOwnProps() && cache.stateOwnProps !== ownProps)))) {
|
|
907
|
+
cache.stateProps = mapState ? mapState.map(state, ownProps) : {};
|
|
908
|
+
cache.state = state;
|
|
909
|
+
cache.stateOwnProps = ownProps;
|
|
910
|
+
}
|
|
911
|
+
if (!cache.dispatchProps || (mapDispatch && mapDispatch.dependsOnOwnProps() && cache.dispatchOwnProps !== ownProps)) {
|
|
912
|
+
cache.dispatchProps = mapDispatch ? mapDispatch.map(HOOK.dispatch, ownProps) : mapDispatchToProps ? bound(mapDispatchToProps) : {dispatch: HOOK.dispatch};
|
|
913
|
+
cache.dispatchOwnProps = ownProps;
|
|
914
|
+
}
|
|
915
|
+
const merged = {...ownProps, ...cache.stateProps, ...cache.dispatchProps};
|
|
916
|
+
if (!cache.merged || !shallowEqual(cache.merged, merged)) cache.merged = merged;
|
|
917
|
+
if (!cache.element || cache.rendered !== cache.merged || cache.ref !== props.reactReduxForwardedRef) {
|
|
918
|
+
cache.rendered = cache.merged;
|
|
919
|
+
cache.ref = props.reactReduxForwardedRef;
|
|
920
|
+
cache.element = createElement(WrappedComponent, forwardsRef ? {...cache.merged, ref: cache.ref} : cache.merged);
|
|
921
|
+
}
|
|
922
|
+
return cache.element;
|
|
923
|
+
}
|
|
924
|
+
ConnectFunction.displayName = displayName;
|
|
925
|
+
const Connect = memo(ConnectFunction);
|
|
926
|
+
Connect.displayName = displayName;
|
|
927
|
+
Connect.WrappedComponent = WrappedComponent;
|
|
928
|
+
if (!forwardsRef) return hoistStatics(Connect, WrappedComponent);
|
|
929
|
+
const Forwarded = forwardRef((props, ref) => createElement(Connect, {...props, reactReduxForwardedRef: ref}));
|
|
930
|
+
Forwarded.displayName = displayName;
|
|
931
|
+
Forwarded.WrappedComponent = WrappedComponent;
|
|
932
|
+
return hoistStatics(Forwarded, WrappedComponent);
|
|
933
|
+
};
|
|
934
|
+
}`;
|
|
935
|
+
function convertReducerStore(cu, p, ctx) {
|
|
936
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
937
|
+
var _a;
|
|
938
|
+
const store = p.store;
|
|
939
|
+
const { hook, reducer, renderer, selectorHook, listeners } = p.reducerStore;
|
|
940
|
+
const found = storeStatement(cu, store);
|
|
941
|
+
if (!found)
|
|
942
|
+
return cu;
|
|
943
|
+
const padded = cu.statements[found.index];
|
|
944
|
+
const statement = padded.element;
|
|
945
|
+
const cursor = new rewrite_1.Cursor(statement, new rewrite_1.Cursor(cu, undefined));
|
|
946
|
+
const combined = store.reducerStore === "combined";
|
|
947
|
+
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
948
|
+
const thunk = store.reducerStore === "legacyThunk";
|
|
949
|
+
const update = `${hook}.setState(${reducer}(${hook}.getState(), action), true);`;
|
|
950
|
+
const notified = listeners ? `${update}\n for (const listener of [...${listeners}.values()]) listener();` : update;
|
|
951
|
+
const setState = renderer ? listeners ? `unstable_batchedUpdates(() => {\n ${notified}\n });` : `unstable_batchedUpdates(() => ${update.slice(0, -1)});` : notified;
|
|
952
|
+
const members = `getState: ${hook}.getState, dispatch: ${hook}.dispatch` + (listeners ? `, subscribe: listener => {
|
|
953
|
+
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) + "'");
|
|
954
|
+
const id = Symbol();
|
|
955
|
+
${listeners}.set(id, listener);
|
|
956
|
+
return () => {
|
|
957
|
+
${listeners}.delete(id);
|
|
958
|
+
};
|
|
959
|
+
}` : "");
|
|
960
|
+
const generated = [
|
|
961
|
+
combined ? yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(reducer)} = combineReducers(${found.reducer});`.apply(statement, cursor) :
|
|
962
|
+
yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(reducer)} = ${found.reducer};`.apply(statement, cursor),
|
|
963
|
+
found.preloaded ?
|
|
964
|
+
yield (0, javascript_1.template) `export const ${(0, javascript_1.raw)(hook)} = create(() => ${(0, javascript_1.raw)(reducer)}(${found.preloaded}, {type: "@@redux/INIT"}));`.apply(statement, cursor) :
|
|
965
|
+
yield (0, javascript_1.template) `export const ${(0, javascript_1.raw)(hook)} = create(() => ${(0, javascript_1.raw)(reducer)}(undefined, {type: "@@redux/INIT"}));`.apply(statement, cursor),
|
|
966
|
+
...listeners ? [yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(listeners)} = new Map();`.apply(statement, cursor)] : [],
|
|
967
|
+
thunk ?
|
|
968
|
+
yield (0, javascript_1.template) `${(0, javascript_1.raw)(hook)}.dispatch = action => {
|
|
969
|
+
if (typeof action === "function") return action(${(0, javascript_1.raw)(hook)}.dispatch, ${(0, javascript_1.raw)(hook)}.getState, undefined);
|
|
970
|
+
if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
|
|
971
|
+
if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");
|
|
972
|
+
${(0, javascript_1.raw)(setState)}
|
|
973
|
+
return action;
|
|
974
|
+
};`.apply(statement, cursor) :
|
|
975
|
+
legacy ?
|
|
976
|
+
yield (0, javascript_1.template) `${(0, javascript_1.raw)(hook)}.dispatch = action => {
|
|
977
|
+
if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
|
|
978
|
+
if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");
|
|
979
|
+
${(0, javascript_1.raw)(setState)}
|
|
980
|
+
return action;
|
|
981
|
+
};`.apply(statement, cursor) :
|
|
982
|
+
yield (0, javascript_1.template) `${(0, javascript_1.raw)(hook)}.dispatch = action => {
|
|
983
|
+
if (typeof action === "function") return action(${(0, javascript_1.raw)(hook)}.dispatch, ${(0, javascript_1.raw)(hook)}.getState, undefined);
|
|
984
|
+
${(0, javascript_1.raw)(setState)}
|
|
985
|
+
return action;
|
|
986
|
+
};`.apply(statement, cursor),
|
|
987
|
+
statement.kind === javascript_1.JS.Kind.ExportAssignment ?
|
|
988
|
+
yield (0, javascript_1.template) `export default {${(0, javascript_1.raw)(members)}};`.apply(statement, cursor) :
|
|
989
|
+
yield (0, javascript_1.template) `${(0, javascript_1.raw)(statement.modifiers.some(m => m.keyword === "export") ? "export " : "")}const ${(0, javascript_1.raw)(store.store)} = {${(0, javascript_1.raw)(members)}};`.apply(statement, cursor),
|
|
990
|
+
...selectorHook ? [yield (0, javascript_1.template) `${(0, javascript_1.raw)(exports.SELECTOR.split("SELECTOR_HOOK").join(selectorHook).split("HOOK").join(hook))}`.apply(statement, cursor)] : [],
|
|
991
|
+
...renderer ? [yield (0, javascript_1.template) `${(0, javascript_1.raw)(exports.CONNECT.split("HOOK").join(hook))}`.apply(statement, cursor)] : []
|
|
992
|
+
];
|
|
993
|
+
const statements = [...cu.statements.slice(0, found.index)];
|
|
994
|
+
for (let i = 0; i < generated.length; i++) {
|
|
995
|
+
const prefixed = withPrefix(generated[i], i === 0 ? statement.prefix : space("\n\n"));
|
|
996
|
+
const element = i === 0 ? prefixed : yield (0, javascript_1.autoFormat)(prefixed, ctx, undefined, new rewrite_1.Cursor(cu, undefined));
|
|
997
|
+
statements.push(element.kind === java_1.J.Kind.MethodDeclaration ? Object.assign(Object.assign({}, padded), { element, markers: rewrite_1.emptyMarkers }) : Object.assign(Object.assign({}, padded), { element }));
|
|
998
|
+
}
|
|
999
|
+
statements.push(...cu.statements.slice(found.index + 1));
|
|
1000
|
+
const result = yield withoutUnused(Object.assign(Object.assign({}, cu), { statements }), (_a = found.consts) !== null && _a !== void 0 ? _a : new Set());
|
|
1001
|
+
return new class extends javascript_1.JavaScriptVisitor {
|
|
1002
|
+
visitJsCompilationUnit(unit, q) {
|
|
1003
|
+
const _super = Object.create(null, {
|
|
1004
|
+
visitJsCompilationUnit: { get: () => super.visitJsCompilationUnit }
|
|
1005
|
+
});
|
|
1006
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1007
|
+
const quoteStyle = quoteOf(cu);
|
|
1008
|
+
(0, javascript_1.maybeRemoveImport)(this, redux_stores_1.RTK, "configureStore");
|
|
1009
|
+
for (const module of [redux_stores_1.REDUX, redux_stores_1.RTK])
|
|
1010
|
+
for (const member of ["createStore", "legacy_createStore"])
|
|
1011
|
+
(0, javascript_1.maybeRemoveImport)(this, module, member);
|
|
1012
|
+
if (legacy) {
|
|
1013
|
+
for (const member of ["applyMiddleware", "compose"])
|
|
1014
|
+
(0, javascript_1.maybeRemoveImport)(this, redux_stores_1.REDUX, member);
|
|
1015
|
+
for (const member of ["default", "thunk"])
|
|
1016
|
+
(0, javascript_1.maybeRemoveImport)(this, "redux-thunk", member);
|
|
1017
|
+
for (const module of ["redux-devtools-extension", "@redux-devtools/extension"]) {
|
|
1018
|
+
for (const member of ["composeWithDevTools", "devToolsEnhancer", "devToolsEnhancerLogOnlyInProduction"])
|
|
1019
|
+
(0, javascript_1.maybeRemoveImport)(this, module, member);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
if (combined)
|
|
1023
|
+
(0, javascript_1.maybeAddImport)(this, { module: redux_stores_1.RTK, member: "combineReducers", onlyIfReferenced: false, quoteStyle });
|
|
1024
|
+
(0, javascript_1.maybeAddImport)(this, { module: ZUSTAND, member: "create", onlyIfReferenced: false, quoteStyle });
|
|
1025
|
+
if (selectorHook)
|
|
1026
|
+
for (const member of ["useRef", "useSyncExternalStore"])
|
|
1027
|
+
(0, javascript_1.maybeAddImport)(this, { module: "react", member, onlyIfReferenced: false, quoteStyle });
|
|
1028
|
+
if (renderer) {
|
|
1029
|
+
for (const member of ["createElement", "forwardRef", "memo", "useRef"])
|
|
1030
|
+
(0, javascript_1.maybeAddImport)(this, { module: "react", member, onlyIfReferenced: false, quoteStyle });
|
|
1031
|
+
(0, javascript_1.maybeAddImport)(this, { module: renderer, member: "unstable_batchedUpdates", onlyIfReferenced: false, quoteStyle });
|
|
1032
|
+
}
|
|
1033
|
+
return _super.visitJsCompilationUnit.call(this, unit, q);
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
}().visit(result, ctx);
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
function fragment(tag) {
|
|
1040
|
+
const empty = () => ({ kind: java_1.J.Kind.Empty, id: (0, rewrite_1.randomId)(), prefix: java_1.emptySpace, markers: rewrite_1.emptyMarkers });
|
|
1041
|
+
return (0, mutative_1.create)(tag, draft => {
|
|
1042
|
+
draft.openName = Object.assign(Object.assign({}, draft.openName), { before: java_1.emptySpace, element: empty() });
|
|
1043
|
+
draft.closingName = Object.assign(Object.assign({}, draft.closingName), { before: java_1.emptySpace, element: empty() });
|
|
1044
|
+
draft.attributes = [];
|
|
1045
|
+
draft.afterName = java_1.emptySpace;
|
|
1046
|
+
draft.afterClosingName = java_1.emptySpace;
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
function convertReducerConsumer(cu, p, scanned, ctx) {
|
|
1050
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1051
|
+
const { hook, selectorHook } = p.reducerStore;
|
|
1052
|
+
const source = scanned.sources.get(cu.sourcePath);
|
|
1053
|
+
const reads = (selector) => !!(0, zustand_plan_1.selectorRead)(selector) ||
|
|
1054
|
+
(0, java_1.isIdentifier)(selector) && !!source && (0, zustand_plan_1.readSelector)(source, selector.simpleName, scanned.sources);
|
|
1055
|
+
const bindings = (0, module_imports_1.importBindings)(cu);
|
|
1056
|
+
const followed = new Map(bindings.filter(b => b.module === zustand_plan_1.REACT_REDUX || b.module.startsWith(".")).map(b => [b.local, b]));
|
|
1057
|
+
const reactRedux = (name, member) => { var _a, _b; return ((_a = followed.get(name)) === null || _a === void 0 ? void 0 : _a.module) === zustand_plan_1.REACT_REDUX && ((_b = followed.get(name)) === null || _b === void 0 ? void 0 : _b.name) === member; };
|
|
1058
|
+
const removed = new Set();
|
|
1059
|
+
const uses = new Set();
|
|
1060
|
+
const result = yield new class extends javascript_1.JavaScriptVisitor {
|
|
1061
|
+
visitVariableDeclarations(declarations, q) {
|
|
1062
|
+
const _super = Object.create(null, {
|
|
1063
|
+
visitVariableDeclarations: { get: () => super.visitVariableDeclarations }
|
|
1064
|
+
});
|
|
1065
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1066
|
+
const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
|
|
1067
|
+
if (variable && (0, zustand_plan_1.isDispatcherDeclaration)(variable, followed)) {
|
|
1068
|
+
removed.add("useDispatch");
|
|
1069
|
+
uses.add(hook);
|
|
1070
|
+
const initializer = variable.initializer.element;
|
|
1071
|
+
const replaced = yield (0, javascript_1.template) `${(0, javascript_1.raw)(hook)}.dispatch`.apply(initializer, new rewrite_1.Cursor(initializer, this.cursor));
|
|
1072
|
+
return (0, mutative_1.create)(declarations, draft => {
|
|
1073
|
+
draft.variables[0].element.initializer.element = withPrefix(replaced, initializer.prefix);
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
return _super.visitVariableDeclarations.call(this, declarations, q);
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
visitMethodInvocation(call, q) {
|
|
1080
|
+
const _super = Object.create(null, {
|
|
1081
|
+
visitMethodInvocation: { get: () => super.visitMethodInvocation }
|
|
1082
|
+
});
|
|
1083
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1084
|
+
const visited = yield _super.visitMethodInvocation.call(this, call, q);
|
|
1085
|
+
if (visited.select || !reactRedux(visited.name.simpleName, "useSelector"))
|
|
1086
|
+
return visited;
|
|
1087
|
+
removed.add("useSelector");
|
|
1088
|
+
const through = selectorHook && !reads((0, zustand_plan_1.argumentsOf)(visited)[0]) ? selectorHook : hook;
|
|
1089
|
+
uses.add(through);
|
|
1090
|
+
return (0, mutative_1.create)(visited, draft => {
|
|
1091
|
+
draft.name = Object.assign(Object.assign({}, draft.name), { simpleName: through, fieldType: undefined, type: undefined });
|
|
1092
|
+
draft.methodType = undefined;
|
|
1093
|
+
});
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
visitJsxTag(tag, q) {
|
|
1097
|
+
const _super = Object.create(null, {
|
|
1098
|
+
visitJsxTag: { get: () => super.visitJsxTag }
|
|
1099
|
+
});
|
|
1100
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1101
|
+
const name = tag.openName.element;
|
|
1102
|
+
if ((0, java_1.isIdentifier)(name) && reactRedux(name.simpleName, "Provider")) {
|
|
1103
|
+
const child = (0, zustand_plan_1.providerChild)(tag);
|
|
1104
|
+
if (child) {
|
|
1105
|
+
removed.add("Provider");
|
|
1106
|
+
return withPrefix(yield this.visit(child, q, this.cursor), tag.prefix);
|
|
1107
|
+
}
|
|
1108
|
+
if ((0, zustand_plan_1.providerChildren)(tag)) {
|
|
1109
|
+
removed.add("Provider");
|
|
1110
|
+
return fragment(yield _super.visitJsxTag.call(this, tag, q));
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return _super.visitJsxTag.call(this, tag, q);
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
}().visit(cu, ctx);
|
|
1117
|
+
const connected = p.reducerStore.renderer && bindings.some(b => b.module === zustand_plan_1.REACT_REDUX && b.name === "connect") ?
|
|
1118
|
+
yield (yield new javascript_1.ChangeImport({ oldModule: zustand_plan_1.REACT_REDUX, oldMember: "connect", newModule: (0, zustand_plan_1.relativeSpecifier)(cu.sourcePath, p.store.path) }).editor()).visit(result, ctx) :
|
|
1119
|
+
result;
|
|
1120
|
+
return yield new class extends javascript_1.JavaScriptVisitor {
|
|
1121
|
+
visitJsCompilationUnit(unit, q) {
|
|
1122
|
+
const _super = Object.create(null, {
|
|
1123
|
+
visitJsCompilationUnit: { get: () => super.visitJsCompilationUnit }
|
|
1124
|
+
});
|
|
1125
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1126
|
+
for (const member of ["useSelector", "useDispatch", "Provider"]) {
|
|
1127
|
+
if (removed.has(member))
|
|
1128
|
+
(0, javascript_1.maybeRemoveImport)(this, zustand_plan_1.REACT_REDUX, member);
|
|
1129
|
+
}
|
|
1130
|
+
if (removed.has("Provider")) {
|
|
1131
|
+
for (const binding of bindings) {
|
|
1132
|
+
if (binding.module !== zustand_plan_1.REACT_REDUX && (0, module_imports_1.resolveRelative)(cu.sourcePath, binding.module, scanned.sources) === p.store.path)
|
|
1133
|
+
(0, javascript_1.maybeRemoveImport)(this, binding.module, binding.name);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
for (const member of [hook, selectorHook]) {
|
|
1137
|
+
if (member && uses.has(member))
|
|
1138
|
+
(0, javascript_1.maybeAddImport)(this, { module: (0, zustand_plan_1.relativeSpecifier)(cu.sourcePath, p.store.path), member, onlyIfReferenced: false, quoteStyle: quoteOf(cu) });
|
|
1139
|
+
}
|
|
1140
|
+
return _super.visitJsCompilationUnit.call(this, unit, q);
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
}().visit(connected, ctx);
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
654
1146
|
//# sourceMappingURL=redux-to-zustand.js.map
|