@openrewrite/recipes-react 0.17.0 → 0.19.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/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -5
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +3 -5
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +5 -2
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +8 -1
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
- package/dist/react19/find-legacy-context-api.js +21 -38
- package/dist/react19/find-legacy-context-api.js.map +1 -1
- package/dist/react19/no-implicit-ref-callback-return.d.ts.map +1 -1
- package/dist/react19/no-implicit-ref-callback-return.js +25 -5
- package/dist/react19/no-implicit-ref-callback-return.js.map +1 -1
- package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
- package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
- package/dist/react19/remove-unstable-batched-updates.js +295 -0
- package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
- package/dist/react19/replace-default-props.d.ts +1 -0
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +198 -151
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +10 -25
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/class-to-functional.d.ts.map +1 -1
- package/dist/refactoring/class-to-functional.js +2 -0
- package/dist/refactoring/class-to-functional.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +14 -49
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/search/find-function-component-default-props.d.ts.map +1 -1
- package/dist/search/find-function-component-default-props.js +6 -15
- package/dist/search/find-function-component-default-props.js.map +1 -1
- package/dist/search/find-redux-stores.d.ts +12 -0
- package/dist/search/find-redux-stores.d.ts.map +1 -0
- package/dist/search/find-redux-stores.js +87 -0
- package/dist/search/find-redux-stores.js.map +1 -0
- package/dist/simplify-object-pattern-property.d.ts.map +1 -1
- package/dist/simplify-object-pattern-property.js +14 -21
- package/dist/simplify-object-pattern-property.js.map +1 -1
- package/dist/simplify-react-imports.d.ts.map +1 -1
- package/dist/simplify-react-imports.js +10 -59
- package/dist/simplify-react-imports.js.map +1 -1
- package/dist/testing/enzyme-host-components.d.ts +2 -1
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +33 -2
- package/dist/testing/enzyme-host-components.js.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +83 -24
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +4 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +36 -7
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +2 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -1
- package/dist/util/java-recipe-proxy.js +14 -2
- package/dist/util/java-recipe-proxy.js.map +1 -1
- package/dist/util/reindent.d.ts +5 -0
- package/dist/util/reindent.d.ts.map +1 -0
- package/dist/util/reindent.js +44 -0
- package/dist/util/reindent.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +74 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -0
- package/dist/zustand/redux-stores.js +439 -0
- package/dist/zustand/redux-stores.js.map +1 -0
- package/dist/zustand/redux-to-zustand.d.ts +76 -0
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
- package/dist/zustand/redux-to-zustand.js +654 -0
- package/dist/zustand/redux-to-zustand.js.map +1 -0
- package/dist/zustand/zustand-plan.d.ts +97 -0
- package/dist/zustand/zustand-plan.d.ts.map +1 -0
- package/dist/zustand/zustand-plan.js +833 -0
- package/dist/zustand/zustand-plan.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +7 -3
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +3 -5
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +3 -3
- package/src/react18/replace-unmount-component-at-node.ts +13 -2
- package/src/react19/find-legacy-context-api.ts +21 -42
- package/src/react19/no-implicit-ref-callback-return.ts +34 -8
- package/src/react19/remove-unstable-batched-updates.ts +301 -0
- package/src/react19/replace-default-props.ts +212 -159
- package/src/react19/replace-react-shallow-renderer.ts +13 -36
- package/src/refactoring/class-to-functional.ts +3 -1
- package/src/refactoring/create-class-to-es6.ts +12 -63
- package/src/search/find-function-component-default-props.ts +8 -10
- package/src/search/find-redux-stores.ts +76 -0
- package/src/simplify-object-pattern-property.ts +22 -49
- package/src/simplify-react-imports.ts +12 -66
- package/src/testing/enzyme-host-components.ts +38 -3
- package/src/testing/enzyme-to-react-testing-library.ts +118 -31
- package/src/testing/enzyme-wrapper-scope.ts +39 -10
- package/src/util/java-recipe-proxy.ts +15 -2
- package/src/util/reindent.ts +35 -0
- package/src/zustand/redux-stores.ts +441 -0
- package/src/zustand/redux-to-zustand.ts +660 -0
- package/src/zustand/zustand-plan.ts +854 -0
- package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
- package/dist/react18/remove-unstable-batched-updates.js +0 -170
- package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
- package/src/react18/remove-unstable-batched-updates.ts +0 -192
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.ReduxToZustand = exports.AddImmer = exports.AddZustand4 = exports.AddZustand = void 0;
|
|
13
|
+
const rewrite_1 = require("@openrewrite/rewrite");
|
|
14
|
+
const javascript_1 = require("@openrewrite/rewrite/javascript");
|
|
15
|
+
const java_1 = require("@openrewrite/rewrite/java");
|
|
16
|
+
const json_1 = require("@openrewrite/rewrite/json");
|
|
17
|
+
const mutative_1 = require("mutative");
|
|
18
|
+
const semver_1 = require("semver");
|
|
19
|
+
const rewrite_2 = require("@openrewrite/rewrite");
|
|
20
|
+
const java_recipe_proxy_1 = require("../util/java-recipe-proxy");
|
|
21
|
+
const module_imports_1 = require("../util/module-imports");
|
|
22
|
+
const enzyme_to_react_testing_library_1 = require("../testing/enzyme-to-react-testing-library");
|
|
23
|
+
const redux_stores_1 = require("./redux-stores");
|
|
24
|
+
const zustand_plan_1 = require("./zustand-plan");
|
|
25
|
+
const ZUSTAND = "zustand";
|
|
26
|
+
const IMMER = "immer";
|
|
27
|
+
const ZUSTAND_5 = {
|
|
28
|
+
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies", onlyIfDeclaring: [redux_stores_1.RTK],
|
|
29
|
+
onlyIfResolving: ["react@>=18.0.0"]
|
|
30
|
+
};
|
|
31
|
+
const ZUSTAND_4 = Object.assign(Object.assign({}, ZUSTAND_5), { version: "^4.5.7", onlyIfResolving: ["react@>=16.8.0 <18"] });
|
|
32
|
+
const IMMER_10 = Object.assign(Object.assign({}, ZUSTAND_5), { packageName: IMMER, version: "^10.1.3", onlyIfResolving: ["react@>=16.8.0"] });
|
|
33
|
+
const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lock)$/;
|
|
34
|
+
class ZustandDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
|
|
35
|
+
constructor(addition, forecast) {
|
|
36
|
+
super("org.openrewrite.javascript.AddDependency", addition);
|
|
37
|
+
this.addition = addition;
|
|
38
|
+
this.forecast = forecast;
|
|
39
|
+
this.landed = new Set();
|
|
40
|
+
this.held = [];
|
|
41
|
+
this.locks = [];
|
|
42
|
+
this.unfit = new Set();
|
|
43
|
+
}
|
|
44
|
+
initialValue() {
|
|
45
|
+
var _a;
|
|
46
|
+
this.landed.clear();
|
|
47
|
+
this.unfit.clear();
|
|
48
|
+
this.held.length = 0;
|
|
49
|
+
this.locks.length = 0;
|
|
50
|
+
(_a = this.forecast.refused) === null || _a === void 0 ? void 0 : _a.clear();
|
|
51
|
+
return super.initialValue();
|
|
52
|
+
}
|
|
53
|
+
scanned(manifest) {
|
|
54
|
+
if (manifest.kind === json_1.Json.Kind.Document && /(^|\/)package\.json$/.test(manifest.sourcePath)) {
|
|
55
|
+
this.held.push(manifest);
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
if (LOCKFILE.test(manifest.sourcePath))
|
|
59
|
+
this.locks.push(manifest);
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
edits(manifest) {
|
|
63
|
+
if (/(^|\/)package\.json$/.test(manifest.sourcePath) && this.unfit.has(packageRoot(manifest.sourcePath)))
|
|
64
|
+
return false;
|
|
65
|
+
if (LOCKFILE.test(manifest.sourcePath) && this.unfit.has(manifest.sourcePath.slice(0, manifest.sourcePath.lastIndexOf("/") + 1)))
|
|
66
|
+
return false;
|
|
67
|
+
const refused = this.forecast.refused;
|
|
68
|
+
if (!(refused === null || refused === void 0 ? void 0 : refused.size))
|
|
69
|
+
return true;
|
|
70
|
+
if (/(^|\/)package\.json$/.test(manifest.sourcePath))
|
|
71
|
+
return !refused.has(packageRoot(manifest.sourcePath));
|
|
72
|
+
return ![...refused.values()].some(refusal => refusal.lock === manifest.sourcePath);
|
|
73
|
+
}
|
|
74
|
+
fits(root) {
|
|
75
|
+
var _a, _b, _c, _d;
|
|
76
|
+
const declared = (_b = (_a = this.forecast).react) === null || _b === void 0 ? void 0 : _b.call(_a, root);
|
|
77
|
+
const gate = (_d = (_c = this.addition.onlyIfResolving) === null || _c === void 0 ? void 0 : _c.find(gate => gate.startsWith("react@"))) === null || _d === void 0 ? void 0 : _d.slice("react@".length);
|
|
78
|
+
if (!declared || !gate || !(0, semver_1.validRange)(declared))
|
|
79
|
+
return true;
|
|
80
|
+
const lowest = (0, semver_1.minVersion)(declared);
|
|
81
|
+
return !lowest || (0, semver_1.satisfies)(lowest, gate);
|
|
82
|
+
}
|
|
83
|
+
lockOf(root) {
|
|
84
|
+
const directory = (path) => path.slice(0, path.lastIndexOf("/") + 1);
|
|
85
|
+
return this.locks.filter(lock => root.startsWith(directory(lock.sourcePath)))
|
|
86
|
+
.sort((a, b) => b.sourcePath.length - a.sourcePath.length)[0];
|
|
87
|
+
}
|
|
88
|
+
generate(acc, ctx) {
|
|
89
|
+
const _super = Object.create(null, {
|
|
90
|
+
generate: { get: () => super.generate }
|
|
91
|
+
});
|
|
92
|
+
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 : new Set();
|
|
95
|
+
for (const root of converting)
|
|
96
|
+
if (!this.fits(root))
|
|
97
|
+
this.unfit.add(root);
|
|
98
|
+
const forwarded = this.held.filter(manifest => converting.has(packageRoot(manifest.sourcePath)) && !this.unfit.has(packageRoot(manifest.sourcePath)));
|
|
99
|
+
const scanner = yield this.java.scanner(acc);
|
|
100
|
+
for (const manifest of forwarded)
|
|
101
|
+
yield scanner.visit(manifest, ctx);
|
|
102
|
+
const generated = yield _super.generate.call(this, acc, ctx);
|
|
103
|
+
const editor = yield this.java.editorWithData(acc);
|
|
104
|
+
for (const manifest of forwarded) {
|
|
105
|
+
const edited = yield editor.visit(manifest, ctx);
|
|
106
|
+
if (!edited || edited === manifest || !(yield declares(edited, this.addition.packageName)))
|
|
107
|
+
continue;
|
|
108
|
+
const root = packageRoot(manifest.sourcePath);
|
|
109
|
+
const lock = this.lockOf(root);
|
|
110
|
+
const regenerated = lock ? yield editor.visit(lock, ctx) : undefined;
|
|
111
|
+
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
|
+
if (warning)
|
|
113
|
+
(_d = this.forecast.refused) === null || _d === void 0 ? void 0 : _d.set(root, { message: warning.message, lock: lock.sourcePath });
|
|
114
|
+
else
|
|
115
|
+
this.landed.add(root);
|
|
116
|
+
}
|
|
117
|
+
this.held.length = 0;
|
|
118
|
+
return generated;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
class AddZustand extends ZustandDependency {
|
|
123
|
+
constructor(forecast = {}) {
|
|
124
|
+
super(ZUSTAND_5, forecast);
|
|
125
|
+
this.name = "org.openrewrite.react.migrate.add-zustand";
|
|
126
|
+
this.displayName = "Add `zustand` where a Redux store is migrated";
|
|
127
|
+
this.description = "Adds `zustand` 5 to packages that declare `@reduxjs/toolkit` and resolve React 18 or later, where a Redux store moves to zustand.";
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
exports.AddZustand = AddZustand;
|
|
131
|
+
class AddZustand4 extends ZustandDependency {
|
|
132
|
+
constructor(forecast = {}) {
|
|
133
|
+
super(ZUSTAND_4, forecast);
|
|
134
|
+
this.name = "org.openrewrite.react.migrate.add-zustand-4";
|
|
135
|
+
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 declare `@reduxjs/toolkit` and resolve React 16.8 to 17, where a Redux store moves to zustand.";
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
exports.AddZustand4 = AddZustand4;
|
|
140
|
+
class AddImmer extends ZustandDependency {
|
|
141
|
+
constructor(forecast = {}) {
|
|
142
|
+
super(IMMER_10, forecast);
|
|
143
|
+
this.name = "org.openrewrite.react.migrate.add-immer";
|
|
144
|
+
this.displayName = "Add `immer` where a Redux store is migrated";
|
|
145
|
+
this.description = "Adds `immer` 10 to packages that declare `@reduxjs/toolkit` and resolve React 16.8 or later, where a Redux store moves to zustand and its slices' reducers run through `produce`.";
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
exports.AddImmer = AddImmer;
|
|
149
|
+
const ADDS_DEPENDENCIES = (() => {
|
|
150
|
+
try {
|
|
151
|
+
return (0, enzyme_to_react_testing_library_1.supportsResolvingGate)((0, enzyme_to_react_testing_library_1.rewriteVersion)(require.resolve("@openrewrite/rewrite"), require.cache));
|
|
152
|
+
}
|
|
153
|
+
catch (_a) {
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
})();
|
|
157
|
+
class ReduxToZustand extends rewrite_1.ScanningRecipe {
|
|
158
|
+
constructor() {
|
|
159
|
+
super(...arguments);
|
|
160
|
+
this.name = "org.openrewrite.react.migrate.redux-to-zustand";
|
|
161
|
+
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` 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. Adds `zustand` and `immer` where they are missing. Stores with any other use, such as `connect`, thunks that reach the rest of the store, selectors that build values or several stores, stay in Redux and are recorded for review.";
|
|
163
|
+
this.forecast = { refused: new Map() };
|
|
164
|
+
this.storeSources = [];
|
|
165
|
+
this.steps = ADDS_DEPENDENCIES ? { zustand: new AddZustand(this.forecast), zustand4: new AddZustand4(this.forecast), immer: new AddImmer(this.forecast) } : undefined;
|
|
166
|
+
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
|
+
this.plans = new WeakMap();
|
|
168
|
+
}
|
|
169
|
+
initialValue() {
|
|
170
|
+
this.storeSources.length = 0;
|
|
171
|
+
return { sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map() };
|
|
172
|
+
}
|
|
173
|
+
scanner(scanned) {
|
|
174
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
175
|
+
const storeSources = this.storeSources;
|
|
176
|
+
let forecast;
|
|
177
|
+
this.asked = undefined;
|
|
178
|
+
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
|
+
.then(plans => this.asked = new Set(plans.filter(p => p.store).map(p => packageOf(scanned.packages, p.store.path)))));
|
|
181
|
+
const sources = yield (0, rewrite_2.check)((0, rewrite_2.not)((0, javascript_1.isVendoredOrBundled)()), new class extends javascript_1.JavaScriptVisitor {
|
|
182
|
+
visitJsCompilationUnit(cu) {
|
|
183
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
184
|
+
const { reducers, slices } = (0, redux_stores_1.localSlices)(cu);
|
|
185
|
+
scanned.modules.set(cu.sourcePath, { reducers, slices });
|
|
186
|
+
scanned.sources.set(cu.sourcePath, yield (0, zustand_plan_1.sourceFacts)(cu));
|
|
187
|
+
const slice = (0, zustand_plan_1.sliceSource)(cu);
|
|
188
|
+
if (slice)
|
|
189
|
+
scanned.sliceSources.set(cu.sourcePath, slice);
|
|
190
|
+
if ((0, module_imports_1.importBindings)(cu).some(b => (b.module === redux_stores_1.RTK || b.module === "redux") && /^(configureStore|createStore|legacy_createStore)$/.test(b.name)))
|
|
191
|
+
storeSources.push(cu);
|
|
192
|
+
return cu;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}());
|
|
196
|
+
const manifests = new class extends json_1.JsonVisitor {
|
|
197
|
+
visitDocument(doc) {
|
|
198
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
199
|
+
if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
|
|
200
|
+
const declared = (0, javascript_1.findNodeResolutionResult)(doc) ? undefined : yield declaredDependencies(doc);
|
|
201
|
+
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) });
|
|
203
|
+
}
|
|
204
|
+
return doc;
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
}();
|
|
208
|
+
const scan = new class extends rewrite_1.TreeVisitor {
|
|
209
|
+
isAcceptable(sourceFile) {
|
|
210
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
211
|
+
return sourceFile.kind === json_1.Json.Kind.Document || sourceFile.kind === javascript_1.JS.Kind.CompilationUnit;
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
visit(tree, ctx, parent) {
|
|
215
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
216
|
+
if (tree.kind === json_1.Json.Kind.Document)
|
|
217
|
+
return yield manifests.visit(tree, ctx, parent);
|
|
218
|
+
return tree.kind === javascript_1.JS.Kind.CompilationUnit ? yield sources.visit(tree, ctx, parent) : tree;
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}();
|
|
222
|
+
return (0, rewrite_2.check)((0, rewrite_1.or)((0, java_recipe_proxy_1.treesOfType)("org.openrewrite.json.tree.Json"), (0, java_recipe_proxy_1.treesOfType)("org.openrewrite.javascript.tree.JS")), scan);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
planned(scanned_1) {
|
|
226
|
+
return __awaiter(this, arguments, void 0, function* (scanned, forecast = false) {
|
|
227
|
+
if (!forecast) {
|
|
228
|
+
const cached = this.plans.get(scanned);
|
|
229
|
+
if (cached)
|
|
230
|
+
return cached;
|
|
231
|
+
}
|
|
232
|
+
const result = (() => __awaiter(this, void 0, void 0, function* () {
|
|
233
|
+
for (const cu of this.storeSources) {
|
|
234
|
+
const facts = scanned.sources.get(cu.sourcePath);
|
|
235
|
+
if (facts)
|
|
236
|
+
facts.stores = yield (0, zustand_plan_1.storeFacts)(cu, scanned.modules);
|
|
237
|
+
}
|
|
238
|
+
return (0, zustand_plan_1.planPackages)(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path), storePath => this.dependencies(scanned, storePath, forecast));
|
|
239
|
+
}))();
|
|
240
|
+
if (!forecast)
|
|
241
|
+
this.plans.set(scanned, result);
|
|
242
|
+
return result;
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
dependencies(scanned, storePath, forecast) {
|
|
246
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
247
|
+
const root = packageOf(scanned.packages, storePath);
|
|
248
|
+
const facts = root !== undefined ? scanned.packages.get(root) : undefined;
|
|
249
|
+
if (root === undefined || !facts)
|
|
250
|
+
return { reason: "NO_PACKAGE", detail: storePath };
|
|
251
|
+
const react = major(facts.react);
|
|
252
|
+
if (react === undefined || react < 16 || react === 16 && ((_b = (_a = (0, semver_1.minVersion)(facts.react)) === null || _a === void 0 ? void 0 : _a.minor) !== null && _b !== void 0 ? _b : 0) < 8)
|
|
253
|
+
return { reason: "REACT_VERSION", detail: (_c = facts.react) !== null && _c !== void 0 ? _c : "react not declared" };
|
|
254
|
+
const refusal = !forecast ? (_d = this.forecast.refused) === null || _d === void 0 ? void 0 : _d.get(root) : undefined;
|
|
255
|
+
if (refusal)
|
|
256
|
+
return { reason: "DEPENDENCY", detail: `zustand isn't added: ${refusal.message}` };
|
|
257
|
+
const landed = (step) => { var _a; return forecast || !((_a = this.asked) === null || _a === void 0 ? void 0 : _a.has(root)) && this.asked !== undefined ? !!this.steps : !!(step === null || step === void 0 ? void 0 : step.landed.has(root)); };
|
|
258
|
+
const zustand = facts.zustand !== undefined ? ((_e = major(facts.zustand)) !== null && _e !== void 0 ? _e : 0) >= (react >= 18 ? 4 : 4) && (react >= 18 || major(facts.zustand) === 4)
|
|
259
|
+
: 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
|
+
if (!zustand)
|
|
261
|
+
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);
|
|
263
|
+
if (!immer)
|
|
264
|
+
return { reason: "DEPENDENCY", detail: facts.immer ? `immer ${facts.immer} is older than 9` : "immer can't be added" };
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
editorWithData(scanned) {
|
|
268
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
269
|
+
const recipe = this;
|
|
270
|
+
const stores = this.stores;
|
|
271
|
+
const reported = new Set();
|
|
272
|
+
return (0, rewrite_2.check)((0, rewrite_2.not)((0, javascript_1.isVendoredOrBundled)()), new class extends javascript_1.JavaScriptVisitor {
|
|
273
|
+
visitJsCompilationUnit(cu, ctx) {
|
|
274
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
275
|
+
var _a, _b, _c, _d, _e;
|
|
276
|
+
const plans = yield recipe.planned(scanned);
|
|
277
|
+
const facts = scanned.sources.get(cu.sourcePath);
|
|
278
|
+
for (const store of (_a = facts === null || facts === void 0 ? void 0 : facts.stores) !== null && _a !== void 0 ? _a : []) {
|
|
279
|
+
const key = `${store.path}\0${store.store}\0${store.api}`;
|
|
280
|
+
if (reported.has(key))
|
|
281
|
+
continue;
|
|
282
|
+
reported.add(key);
|
|
283
|
+
const p = (_b = plans.find(candidate => candidate.store === store)) !== null && _b !== void 0 ? _b : plans.find(candidate => candidate.blocked.has(store));
|
|
284
|
+
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;
|
|
286
|
+
for (const { reason, detail } of rows) {
|
|
287
|
+
stores.insertRow(ctx, {
|
|
288
|
+
sourcePath: store.path, store: store.store, api: store.api,
|
|
289
|
+
status: (p === null || p === void 0 ? void 0 : p.store) === store ? "CONVERTED" : "REVIEW", reason, detail,
|
|
290
|
+
testSource: redux_stores_1.TEST_SOURCE.test(store.path), suggestedAction: (_e = (_d = redux_stores_1.SUGGESTED_ACTIONS[reason]) !== null && _d !== void 0 ? _d : CONVERSION_ACTIONS[reason]) !== null && _e !== void 0 ? _e : ""
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
|
|
295
|
+
if (!(p === null || p === void 0 ? void 0 : p.store))
|
|
296
|
+
return cu;
|
|
297
|
+
if (cu.sourcePath === p.store.path)
|
|
298
|
+
return undefined;
|
|
299
|
+
const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
|
|
300
|
+
const converted = slice ? yield convertSlice(this, cu, slice, scanned, ctx) : cu;
|
|
301
|
+
return convertConsumer(converted, p, scanned, ctx);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
}());
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
recipeList() {
|
|
308
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
309
|
+
const steps = this.steps;
|
|
310
|
+
return steps ? [steps.zustand, steps.zustand4, steps.immer] : [];
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
exports.ReduxToZustand = ReduxToZustand;
|
|
315
|
+
const CONVERSION_ACTIONS = {
|
|
316
|
+
MULTIPLE_STORES: "Convert by hand, or one store at a time: the uses of react-redux can't be told apart by store.",
|
|
317
|
+
STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module; a zustand store is a module-level singleton.",
|
|
318
|
+
STORE_SOURCE: "Move what else the store's source declares, such as types or helpers, to another module.",
|
|
319
|
+
SLICE_SOURCE: "Declare each slice in a source of its own, held in a `const` of its own.",
|
|
320
|
+
SLICE_KEY: "Use a reducer key that is a JavaScript identifier, which names the zustand hook.",
|
|
321
|
+
NAME_TAKEN: "Rename what already uses the name the conversion would give the zustand store or its helpers.",
|
|
322
|
+
SLICE_OPTION: "Remove the `createSlice` option, or convert the slice by hand.",
|
|
323
|
+
SLICE_NAME: "Write the slice's `name` as a string literal.",
|
|
324
|
+
SHARED_ACTION_TYPE: "Give the slices, or the thunk, different names: in Redux an action reaches the reducers and cases of every slice that handles its type, and in zustand only its own slice's.",
|
|
325
|
+
INITIAL_STATE: "Write the initial state as a value, or a `const` holding one, rather than a function.",
|
|
326
|
+
REDUCER: "Write each reducer as a function; `prepare` callbacks and reducers that use `this` are converted by hand.",
|
|
327
|
+
ACTIONS_EXPORT: "Export the action creators as `export const {a, b} = slice.actions`, under their own names.",
|
|
328
|
+
UNKNOWN_ACTION: "Remove the import of an action creator that has no reducer, which is `undefined`.",
|
|
329
|
+
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 `connect`, `useStore` and other react-redux APIs with `useSelector` and `useDispatch`, or convert by hand.",
|
|
332
|
+
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: "Read one slice's state in each selector, such as `state => state.counter.value`; selectors that build a value are converted by hand.",
|
|
334
|
+
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
|
+
TYPESCRIPT: "TypeScript sources are not converted yet.",
|
|
336
|
+
NO_PACKAGE: "Add a `package.json` for the store's package.",
|
|
337
|
+
REACT_VERSION: "zustand needs React 16.8 or later.",
|
|
338
|
+
DEPENDENCY: "Add `zustand` and `immer` to the package, in versions that support its React."
|
|
339
|
+
};
|
|
340
|
+
function packageRoot(manifestPath) {
|
|
341
|
+
return manifestPath.slice(0, -"package.json".length);
|
|
342
|
+
}
|
|
343
|
+
function packageOf(packages, sourcePath) {
|
|
344
|
+
return [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length)[0];
|
|
345
|
+
}
|
|
346
|
+
function declares(manifest, name) {
|
|
347
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
348
|
+
if (declaration(manifest, name))
|
|
349
|
+
return true;
|
|
350
|
+
return name in (yield declaredDependencies(manifest));
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
function declaration(manifest, name) {
|
|
354
|
+
var _a, _b, _c, _d;
|
|
355
|
+
const resolution = (0, javascript_1.findNodeResolutionResult)(manifest);
|
|
356
|
+
return [...(_a = resolution === null || resolution === void 0 ? void 0 : resolution.dependencies) !== null && _a !== void 0 ? _a : [], ...(_b = resolution === null || resolution === void 0 ? void 0 : resolution.devDependencies) !== null && _b !== void 0 ? _b : [], ...(_c = resolution === null || resolution === void 0 ? void 0 : resolution.optionalDependencies) !== null && _c !== void 0 ? _c : [],
|
|
357
|
+
...(_d = resolution === null || resolution === void 0 ? void 0 : resolution.peerDependencies) !== null && _d !== void 0 ? _d : []].find(dep => dep.name === name);
|
|
358
|
+
}
|
|
359
|
+
function version(manifest, name) {
|
|
360
|
+
const dependency = declaration(manifest, name);
|
|
361
|
+
const resolved = dependency === null || dependency === void 0 ? void 0 : dependency.resolved;
|
|
362
|
+
if ((resolved === null || resolved === void 0 ? void 0 : resolved.name) === name && (0, semver_1.valid)(resolved.version) && (!(0, semver_1.validRange)(dependency.versionConstraint) || (0, semver_1.satisfies)(resolved.version, dependency.versionConstraint))) {
|
|
363
|
+
return resolved.version;
|
|
364
|
+
}
|
|
365
|
+
return dependency === null || dependency === void 0 ? void 0 : dependency.versionConstraint;
|
|
366
|
+
}
|
|
367
|
+
function declaredDependencies(doc) {
|
|
368
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
369
|
+
try {
|
|
370
|
+
const manifest = JSON.parse(yield rewrite_1.TreePrinters.print(doc));
|
|
371
|
+
return Object.assign(Object.assign(Object.assign(Object.assign({}, manifest.peerDependencies), manifest.optionalDependencies), manifest.devDependencies), manifest.dependencies);
|
|
372
|
+
}
|
|
373
|
+
catch (_a) {
|
|
374
|
+
return {};
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
function major(range) {
|
|
379
|
+
var _a;
|
|
380
|
+
if (!range || !(0, semver_1.validRange)(range))
|
|
381
|
+
return undefined;
|
|
382
|
+
return (_a = (0, semver_1.minVersion)(range)) === null || _a === void 0 ? void 0 : _a.major;
|
|
383
|
+
}
|
|
384
|
+
function space(whitespace) {
|
|
385
|
+
return { kind: java_1.J.Kind.Space, comments: [], whitespace };
|
|
386
|
+
}
|
|
387
|
+
function convertSlice(visitor, cu, slice, scanned, ctx) {
|
|
388
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
389
|
+
var _a;
|
|
390
|
+
const local = (0, redux_stores_1.localSlices)(cu);
|
|
391
|
+
const cursor = new rewrite_1.Cursor(cu, undefined);
|
|
392
|
+
const statements = [];
|
|
393
|
+
const facts = local.localSlices.get(slice.variable);
|
|
394
|
+
for (const padded of cu.statements) {
|
|
395
|
+
const statement = padded.element;
|
|
396
|
+
const thunk = statement.kind === java_1.J.Kind.VariableDeclarations ? statement.variables[0].element : undefined;
|
|
397
|
+
const kept = thunk && (0, java_1.isIdentifier)(thunk.name) ? slice.thunkVariables.get(thunk.name.simpleName) : undefined;
|
|
398
|
+
if (thunk && kept) {
|
|
399
|
+
const name = thunk.name.simpleName;
|
|
400
|
+
const exported = statement.modifiers.some(m => m.keyword === "export");
|
|
401
|
+
const statementCursor = new rewrite_1.Cursor(statement, cursor);
|
|
402
|
+
const rtk = yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(kept)} = ${thunk.initializer.element};`.apply(statement, statementCursor);
|
|
403
|
+
const run = yield (0, javascript_1.template) `${(0, javascript_1.raw)(exported ? "export " : "")}const ${(0, javascript_1.raw)(name)} = arg => ${(0, javascript_1.raw)(kept)}(arg)(${(0, javascript_1.raw)(slice.dispatch)}, ${(0, javascript_1.raw)(slice.hook)}.getState, undefined);`
|
|
404
|
+
.apply(statement, statementCursor);
|
|
405
|
+
statements.push(Object.assign(Object.assign({}, padded), { element: withPrefix(rtk, statement.prefix) }));
|
|
406
|
+
statements.push(Object.assign(Object.assign({}, padded), { element: withPrefix(run, space("\n")) }));
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (statement.kind === java_1.J.Kind.VariableDeclarations && statement.variables.some(v => (0, java_1.isIdentifier)(v.element.name) && v.element.name.simpleName === slice.variable)) {
|
|
410
|
+
const call = statement.variables[0].element.initializer.element;
|
|
411
|
+
const options = new Map(((0, zustand_plan_1.argumentsOf)(call)[0].body.statements.map(s => s.element))
|
|
412
|
+
.map(p => { var _a, _b; return [(_a = p.name.element.simpleName) !== null && _a !== void 0 ? _a : String(p.name.element.value), (_b = p.initializer) !== null && _b !== void 0 ? _b : p.name.element]; }));
|
|
413
|
+
const name = String(options.get("name").value);
|
|
414
|
+
const statementCursor = new rewrite_1.Cursor(statement, cursor);
|
|
415
|
+
const hook = yield (0, javascript_1.template) `export const ${(0, javascript_1.raw)(slice.hook)} = create(() => freeze(${options.get("initialState")}, true));`.apply(statement, statementCursor);
|
|
416
|
+
const reducers = options.get("reducers");
|
|
417
|
+
const reducerObject = reducers ? yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(slice.reducers)} = ${reducers};`.apply(statement, statementCursor) :
|
|
418
|
+
yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(slice.reducers)} = {};`.apply(statement, statementCursor);
|
|
419
|
+
const action = yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(slice.action)} = type => payload => ${(0, javascript_1.raw)(slice.hook)}.setState(state => produce(state, draft => ${(0, javascript_1.raw)(slice.reducers)}[type](draft, {type: ${(0, javascript_1.raw)(JSON.stringify(name + "/"))} + type, payload})), true);`
|
|
420
|
+
.apply(statement, statementCursor);
|
|
421
|
+
const generatedStatements = [reducerObject, action];
|
|
422
|
+
const cases = ((_a = facts === null || facts === void 0 ? void 0 : facts.cases) === null || _a === void 0 ? void 0 : _a.length) ? (0, redux_stores_1.caseReducers)(cu, slice.variable) : [];
|
|
423
|
+
if (cases.length > 0) {
|
|
424
|
+
const parts = [`const ${slice.caseObject} = {\n`, ...cases.slice(1).map(() => ",\n"), "\n};"];
|
|
425
|
+
const keyed = parts.map((part, i) => i < cases.length ? `${part}${JSON.stringify(`${facts.thunks.get(cases[i].thunk).typePrefix}/${cases[i].stage}`)}: ` : part);
|
|
426
|
+
const strings = Object.assign([...keyed], { raw: [...keyed] });
|
|
427
|
+
generatedStatements.push(yield (0, javascript_1.template)(strings, ...cases.map(c => c.reducer)).apply(statement, statementCursor));
|
|
428
|
+
generatedStatements.push(yield (0, javascript_1.template) `const ${(0, javascript_1.raw)(slice.dispatch)} = action => {
|
|
429
|
+
if (${(0, javascript_1.raw)(slice.caseObject)}[action.type]) ${(0, javascript_1.raw)(slice.hook)}.setState(state => produce(state, draft => ${(0, javascript_1.raw)(slice.caseObject)}[action.type](draft, action)), true);
|
|
430
|
+
};`.apply(statement, statementCursor));
|
|
431
|
+
}
|
|
432
|
+
statements.push(Object.assign(Object.assign({}, padded), { element: withPrefix(hook, statement.prefix) }));
|
|
433
|
+
for (const generated of generatedStatements) {
|
|
434
|
+
const formatted = yield (0, javascript_1.autoFormat)(withPrefix(generated, space("\n\n")), ctx, undefined, cursor);
|
|
435
|
+
statements.push(Object.assign(Object.assign({}, padded), { element: formatted }));
|
|
436
|
+
}
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
const actions = (0, zustand_plan_1.actionsExport)(statement, slice.variable);
|
|
440
|
+
if (actions) {
|
|
441
|
+
let first = true;
|
|
442
|
+
for (const { name } of actions) {
|
|
443
|
+
const generated = slice.unknown.has(name) ?
|
|
444
|
+
yield (0, javascript_1.template) `export const ${(0, javascript_1.raw)(name)} = undefined;`.apply(statement, new rewrite_1.Cursor(statement, cursor)) :
|
|
445
|
+
yield (0, javascript_1.template) `export const ${(0, javascript_1.raw)(name)} = ${(0, javascript_1.raw)(slice.action)}(${(0, javascript_1.raw)(JSON.stringify(name))});`.apply(statement, new rewrite_1.Cursor(statement, cursor));
|
|
446
|
+
statements.push(Object.assign(Object.assign({}, padded), { element: withPrefix(generated, first ? statement.prefix : space("\n")) }));
|
|
447
|
+
first = false;
|
|
448
|
+
}
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if ((0, zustand_plan_1.isReducerExport)(statement, slice.variable, local.localReducers))
|
|
452
|
+
continue;
|
|
453
|
+
statements.push(padded);
|
|
454
|
+
}
|
|
455
|
+
let result = Object.assign(Object.assign({}, cu), { statements });
|
|
456
|
+
result = (yield new class extends javascript_1.JavaScriptVisitor {
|
|
457
|
+
visitJsCompilationUnit(unit, p) {
|
|
458
|
+
const _super = Object.create(null, {
|
|
459
|
+
visitJsCompilationUnit: { get: () => super.visitJsCompilationUnit }
|
|
460
|
+
});
|
|
461
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
462
|
+
const quoteStyle = quoteOf(cu);
|
|
463
|
+
(0, javascript_1.maybeRemoveImport)(this, redux_stores_1.RTK, "createSlice");
|
|
464
|
+
(0, javascript_1.maybeAddImport)(this, { module: ZUSTAND, member: "create", onlyIfReferenced: false, quoteStyle });
|
|
465
|
+
(0, javascript_1.maybeAddImport)(this, { module: IMMER, member: "freeze", onlyIfReferenced: false, quoteStyle });
|
|
466
|
+
(0, javascript_1.maybeAddImport)(this, { module: IMMER, member: "produce", onlyIfReferenced: false, quoteStyle });
|
|
467
|
+
return _super.visitJsCompilationUnit.call(this, unit, p);
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
}().visit(result, ctx));
|
|
471
|
+
void visitor;
|
|
472
|
+
void scanned;
|
|
473
|
+
return result;
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
function quoteOf(cu) {
|
|
477
|
+
var _a;
|
|
478
|
+
for (const { element } of cu.statements) {
|
|
479
|
+
const specifier = element.kind === javascript_1.JS.Kind.Import ? (_a = element.moduleSpecifier) === null || _a === void 0 ? void 0 : _a.element : undefined;
|
|
480
|
+
const source = (specifier === null || specifier === void 0 ? void 0 : specifier.kind) === java_1.J.Kind.Literal ? specifier.valueSource : undefined;
|
|
481
|
+
if (source === null || source === void 0 ? void 0 : source.startsWith("'"))
|
|
482
|
+
return "'";
|
|
483
|
+
if (source === null || source === void 0 ? void 0 : source.startsWith('"'))
|
|
484
|
+
return '"';
|
|
485
|
+
}
|
|
486
|
+
return undefined;
|
|
487
|
+
}
|
|
488
|
+
function withPrefix(node, prefix) {
|
|
489
|
+
return Object.assign(Object.assign({}, node), { prefix });
|
|
490
|
+
}
|
|
491
|
+
function convertConsumer(cu, p, scanned, ctx) {
|
|
492
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
493
|
+
const bindings = (0, module_imports_1.importBindings)(cu);
|
|
494
|
+
const followed = new Map(bindings.filter(b => b.module === zustand_plan_1.REACT_REDUX || b.module.startsWith(".")).map(b => [b.local, b]));
|
|
495
|
+
const isStore = (name) => {
|
|
496
|
+
const binding = followed.get(name);
|
|
497
|
+
return !!binding && binding.module !== zustand_plan_1.REACT_REDUX && (0, module_imports_1.resolveRelative)(cu.sourcePath, binding.module, scanned.sources) === p.store.path &&
|
|
498
|
+
binding.name === p.store.exportedAs;
|
|
499
|
+
};
|
|
500
|
+
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; };
|
|
501
|
+
const dispatchers = new Set();
|
|
502
|
+
const hooks = new Set();
|
|
503
|
+
const removed = new Set();
|
|
504
|
+
const result = yield new class extends javascript_1.JavaScriptVisitor {
|
|
505
|
+
visitVariableDeclarations(declarations, q) {
|
|
506
|
+
const _super = Object.create(null, {
|
|
507
|
+
visitVariableDeclarations: { get: () => super.visitVariableDeclarations }
|
|
508
|
+
});
|
|
509
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
510
|
+
const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
|
|
511
|
+
if (variable && (0, zustand_plan_1.isDispatcherDeclaration)(variable, followed)) {
|
|
512
|
+
dispatchers.add(variable.name.simpleName);
|
|
513
|
+
removed.add("useDispatch");
|
|
514
|
+
return undefined;
|
|
515
|
+
}
|
|
516
|
+
return _super.visitVariableDeclarations.call(this, declarations, q);
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
visitMethodInvocation(call, q) {
|
|
520
|
+
const _super = Object.create(null, {
|
|
521
|
+
visitMethodInvocation: { get: () => super.visitMethodInvocation }
|
|
522
|
+
});
|
|
523
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
524
|
+
const visited = yield _super.visitMethodInvocation.call(this, call, q);
|
|
525
|
+
const action = (0, zustand_plan_1.dispatchedAction)(visited);
|
|
526
|
+
if (action && (!visited.select && dispatchers.has(visited.name.simpleName) ||
|
|
527
|
+
visited.select && (0, java_1.isIdentifier)(visited.select.element) && isStore(visited.select.element.simpleName) && visited.name.simpleName === "dispatch")) {
|
|
528
|
+
if (visited.select)
|
|
529
|
+
removed.add("store");
|
|
530
|
+
return withPrefix(action, visited.prefix);
|
|
531
|
+
}
|
|
532
|
+
if (!visited.select && reactRedux(visited.name.simpleName, "useSelector")) {
|
|
533
|
+
const read = (0, zustand_plan_1.selectorRead)((0, zustand_plan_1.argumentsOf)(visited)[0]);
|
|
534
|
+
const slice = read && p.slices.get(read.key);
|
|
535
|
+
if (!read || !slice)
|
|
536
|
+
return visited;
|
|
537
|
+
hooks.add(slice);
|
|
538
|
+
removed.add("useSelector");
|
|
539
|
+
if (read.lambda.body === read.read) {
|
|
540
|
+
return withPrefix(yield (0, javascript_1.template) `${(0, javascript_1.raw)(slice.hook)}()`.apply(visited, this.cursor), visited.prefix);
|
|
541
|
+
}
|
|
542
|
+
const lambda = read.lambda;
|
|
543
|
+
const body = replaceTree(lambda.body, read.read, read.read.target);
|
|
544
|
+
const arg = (0, zustand_plan_1.argumentsOf)(visited)[0];
|
|
545
|
+
const rewritten = arg.kind === javascript_1.JS.Kind.ArrowFunction ? Object.assign(Object.assign({}, arg), { lambda: Object.assign(Object.assign({}, lambda), { body }) }) : Object.assign(Object.assign({}, lambda), { body });
|
|
546
|
+
return (0, mutative_1.create)(visited, draft => {
|
|
547
|
+
draft.name = Object.assign(Object.assign({}, draft.name), { simpleName: slice.hook, fieldType: undefined, type: undefined });
|
|
548
|
+
draft.methodType = undefined;
|
|
549
|
+
draft.arguments.elements[0].element = rewritten;
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
return visited;
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
visitFieldAccess(access, q) {
|
|
556
|
+
const _super = Object.create(null, {
|
|
557
|
+
visitFieldAccess: { get: () => super.visitFieldAccess }
|
|
558
|
+
});
|
|
559
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
560
|
+
const target = access.target;
|
|
561
|
+
if (target.kind === java_1.J.Kind.MethodInvocation) {
|
|
562
|
+
const call = target;
|
|
563
|
+
const read = call.select && (0, java_1.isIdentifier)(call.select.element) && isStore(call.select.element.simpleName) ? (0, zustand_plan_1.getStateRead)(call, access) : undefined;
|
|
564
|
+
const slice = read && p.slices.get(read.key);
|
|
565
|
+
if (slice) {
|
|
566
|
+
hooks.add(slice);
|
|
567
|
+
removed.add("store");
|
|
568
|
+
return withPrefix(yield (0, javascript_1.template) `${(0, javascript_1.raw)(slice.hook)}.getState()`.apply(access, this.cursor), access.prefix);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return _super.visitFieldAccess.call(this, access, q);
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
visitNewArray(array, q) {
|
|
575
|
+
const _super = Object.create(null, {
|
|
576
|
+
visitNewArray: { get: () => super.visitNewArray }
|
|
577
|
+
});
|
|
578
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
579
|
+
const visited = yield _super.visitNewArray.call(this, array, q);
|
|
580
|
+
if (!visited.initializer || !(0, zustand_plan_1.isReactDependencies)(array, (0, zustand_plan_1.parentTree)(this.cursor), bindings))
|
|
581
|
+
return visited;
|
|
582
|
+
const elements = visited.initializer.elements;
|
|
583
|
+
const kept = elements.filter(({ element }) => !((0, java_1.isIdentifier)(element) && dispatchers.has(element.simpleName)));
|
|
584
|
+
if (kept.length === elements.length)
|
|
585
|
+
return visited;
|
|
586
|
+
return (0, mutative_1.create)(visited, draft => {
|
|
587
|
+
draft.initializer.elements = (kept.length === 0
|
|
588
|
+
? [Object.assign(Object.assign({}, elements[elements.length - 1]), { element: { kind: java_1.J.Kind.Empty, id: (0, rewrite_1.randomId)(), prefix: space(""), markers: rewrite_1.emptyMarkers } })]
|
|
589
|
+
: kept.map((padded, i) => (Object.assign(Object.assign({}, padded), { element: i === 0 ? Object.assign(Object.assign({}, padded.element), { prefix: elements[0].element.prefix }) : padded.element, after: i === kept.length - 1 ? elements[elements.length - 1].after : padded.after }))));
|
|
590
|
+
});
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
visitJsxTag(tag, q) {
|
|
594
|
+
const _super = Object.create(null, {
|
|
595
|
+
visitJsxTag: { get: () => super.visitJsxTag }
|
|
596
|
+
});
|
|
597
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
598
|
+
const name = tag.openName.element;
|
|
599
|
+
if ((0, java_1.isIdentifier)(name) && reactRedux(name.simpleName, "Provider")) {
|
|
600
|
+
const child = (0, zustand_plan_1.providerChild)(tag);
|
|
601
|
+
if (child) {
|
|
602
|
+
removed.add("Provider");
|
|
603
|
+
removed.add("store");
|
|
604
|
+
return withPrefix(yield this.visit(child, q, this.cursor), tag.prefix);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return _super.visitJsxTag.call(this, tag, q);
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
}().visit(cu, ctx);
|
|
611
|
+
return yield new class extends javascript_1.JavaScriptVisitor {
|
|
612
|
+
visitJsCompilationUnit(unit, q) {
|
|
613
|
+
const _super = Object.create(null, {
|
|
614
|
+
visitJsCompilationUnit: { get: () => super.visitJsCompilationUnit }
|
|
615
|
+
});
|
|
616
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
617
|
+
for (const member of ["useSelector", "useDispatch", "Provider"]) {
|
|
618
|
+
if (removed.has(member))
|
|
619
|
+
(0, javascript_1.maybeRemoveImport)(this, zustand_plan_1.REACT_REDUX, member);
|
|
620
|
+
}
|
|
621
|
+
for (const binding of bindings) {
|
|
622
|
+
if (binding.module !== zustand_plan_1.REACT_REDUX && isStore(binding.local))
|
|
623
|
+
(0, javascript_1.maybeRemoveImport)(this, binding.module, binding.name);
|
|
624
|
+
}
|
|
625
|
+
for (const slice of hooks) {
|
|
626
|
+
(0, javascript_1.maybeAddImport)(this, { module: (0, zustand_plan_1.relativeSpecifier)(cu.sourcePath, slice.path), member: slice.hook, onlyIfReferenced: false, quoteStyle: quoteOf(cu) });
|
|
627
|
+
}
|
|
628
|
+
return _super.visitJsCompilationUnit.call(this, unit, q);
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
}().visit(result, ctx);
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
function replaceTree(root, target, replacement) {
|
|
635
|
+
if (root === target)
|
|
636
|
+
return Object.assign(Object.assign({}, replacement), { prefix: target.prefix });
|
|
637
|
+
return (0, mutative_1.create)(root, draft => {
|
|
638
|
+
const replace = (node) => {
|
|
639
|
+
if (!node || typeof node !== "object")
|
|
640
|
+
return false;
|
|
641
|
+
for (const [key, value] of Object.entries(node)) {
|
|
642
|
+
if (value && typeof value === "object" && value.id === target.id) {
|
|
643
|
+
node[key] = Object.assign(Object.assign({}, replacement), { prefix: target.prefix });
|
|
644
|
+
return true;
|
|
645
|
+
}
|
|
646
|
+
if (value && typeof value === "object" && replace(value))
|
|
647
|
+
return true;
|
|
648
|
+
}
|
|
649
|
+
return false;
|
|
650
|
+
};
|
|
651
|
+
replace(draft);
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
//# sourceMappingURL=redux-to-zustand.js.map
|