@openrewrite/recipes-react 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
- package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
- package/dist/i18n/translate-hard-coded-strings.js +439 -0
- package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/search/find-enzyme-usage.d.ts +4 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +64 -4
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/search/find-hard-coded-strings.d.ts +110 -0
- package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
- package/dist/search/find-hard-coded-strings.js +987 -0
- package/dist/search/find-hard-coded-strings.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +2 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
- package/dist/search/find-missing-use-client-directive.js +1 -0
- package/dist/search/find-missing-use-client-directive.js.map +1 -1
- package/dist/testing/enzyme-portals.d.ts +3 -5
- package/dist/testing/enzyme-portals.d.ts.map +1 -1
- package/dist/testing/enzyme-portals.js +8 -39
- package/dist/testing/enzyme-portals.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +10 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +119 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- 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 +9 -2
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +355 -16
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +5 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +48 -6
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +7 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +24 -9
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/json-and-javascript.d.ts +4 -0
- package/dist/util/json-and-javascript.d.ts.map +1 -0
- package/dist/util/json-and-javascript.js +37 -0
- package/dist/util/json-and-javascript.js.map +1 -0
- package/dist/util/module-imports.d.ts +36 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +216 -0
- package/dist/util/module-imports.js.map +1 -1
- package/dist/util/test-source.d.ts +2 -0
- package/dist/util/test-source.d.ts.map +1 -0
- package/dist/util/test-source.js +5 -0
- package/dist/util/test-source.js.map +1 -0
- package/dist/zustand/entry-store.d.ts +9 -0
- package/dist/zustand/entry-store.d.ts.map +1 -0
- package/dist/zustand/entry-store.js +136 -0
- package/dist/zustand/entry-store.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +15 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +155 -10
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +29 -5
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +629 -42
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +31 -6
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +320 -31
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/i18n/translate-hard-coded-strings.ts +442 -0
- package/src/index.ts +7 -0
- package/src/search/find-enzyme-usage.ts +59 -6
- package/src/search/find-hard-coded-strings.ts +1006 -0
- package/src/search/find-missing-use-client-directive.ts +1 -1
- package/src/testing/enzyme-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +113 -0
- package/src/testing/enzyme-shared-wrapper.ts +224 -0
- package/src/testing/enzyme-to-react-testing-library.ts +354 -19
- package/src/testing/enzyme-usage.ts +62 -5
- package/src/testing/enzyme-wrapper-scope.ts +24 -6
- package/src/util/json-and-javascript.ts +26 -0
- package/src/util/module-imports.ts +223 -0
- package/src/util/test-source.ts +2 -0
- package/src/zustand/entry-store.ts +131 -0
- package/src/zustand/redux-stores.ts +171 -11
- package/src/zustand/redux-to-zustand.ts +689 -48
- package/src/zustand/zustand-plan.ts +350 -29
|
@@ -2,8 +2,8 @@ import {Cursor, ExecutionContext} from "@openrewrite/rewrite";
|
|
|
2
2
|
import {JavaScriptVisitor, JS, JSX, namesReferencedWithin} from "@openrewrite/rewrite/javascript";
|
|
3
3
|
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
4
|
import {posix} from "path";
|
|
5
|
-
import {ImportBinding, importBindings, isRelativeSpecifier, resolveRelative} from "../util/module-imports";
|
|
6
|
-
import {Finding, localSlices, objectProperties, RTK, SliceFacts, SliceModule, storeFindings, storeFunctions, TEST_SOURCE} from "./redux-stores";
|
|
5
|
+
import {ImportBinding, importBindings, isAliasSpecifier, isRelativeSpecifier, Resolve, resolveRelative} from "../util/module-imports";
|
|
6
|
+
import {Finding, localSlices, ReducerStoreKind, objectProperties, RTK, SliceFacts, SliceModule, storeFindings, storeFunctions, TEST_SOURCE} from "./redux-stores";
|
|
7
7
|
|
|
8
8
|
export const REACT_REDUX = "react-redux";
|
|
9
9
|
|
|
@@ -23,6 +23,8 @@ export type UseKind =
|
|
|
23
23
|
"dispatcher" |
|
|
24
24
|
/** The `Provider` tag itself. */
|
|
25
25
|
"providerTag" |
|
|
26
|
+
/** `connect(...)` with no `mergeProps` and no option but `forwardRef`, which moves with its whole store. */
|
|
27
|
+
"connect" |
|
|
26
28
|
/** Anything else, which keeps the store from converting. */
|
|
27
29
|
"other";
|
|
28
30
|
|
|
@@ -31,12 +33,41 @@ export interface Use {
|
|
|
31
33
|
kind: UseKind;
|
|
32
34
|
/** The slice key a selector or `getState()` read starts with. */
|
|
33
35
|
key?: string;
|
|
34
|
-
/** For `dispatched`, the import the dispatch goes through: a dispatcher from `useDispatch`, or the store. */
|
|
36
|
+
/** For `dispatched`, the import the dispatch goes through: a dispatcher from `useDispatch`, or the store. For `providerTag`, the import it provides. */
|
|
35
37
|
via?: string;
|
|
36
38
|
/** What `other` was, for the review row. */
|
|
37
39
|
detail?: string;
|
|
38
40
|
/** The reason an `other` use is recorded under, when it is more precise than the kind of import it uses. */
|
|
39
41
|
reason?: string;
|
|
42
|
+
/** For a call of a member of an import, `store.getState()`, the member called. */
|
|
43
|
+
member?: string;
|
|
44
|
+
/** For `useSelector(name)`, the name the selector is passed by. */
|
|
45
|
+
selector?: string;
|
|
46
|
+
/** For `useSelector(selector)` with one argument and no type arguments, which a whole store runs as it is. */
|
|
47
|
+
anySelector?: boolean;
|
|
48
|
+
/** What to do about an `other` use, for the review row, where it says more than its reason's action. */
|
|
49
|
+
action?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What to do with an import of react-redux used other than called, by its name. */
|
|
53
|
+
const REACT_REDUX_VALUE_ACTIONS: Readonly<Record<string, string>> = {
|
|
54
|
+
shallowEqual: "zustand's hooks take no equality function. Where `shallowEqual` is `useSelector`'s second argument, select one value in each `useSelector` and drop it, or write the selector with zustand's `useShallow` by hand.",
|
|
55
|
+
TypedUseSelectorHook: "A react-redux type goes with the TypeScript sources, which aren't converted yet.",
|
|
56
|
+
ConnectedProps: "A react-redux type goes with the TypeScript sources, which aren't converted yet.",
|
|
57
|
+
ResolveThunks: "A react-redux type goes with the TypeScript sources, which aren't converted yet."
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** What to do with a call of an export of react-redux that the conversion doesn't follow, by its name. */
|
|
61
|
+
const REACT_REDUX_CALL_ACTIONS: Readonly<Record<string, string>> = {
|
|
62
|
+
batch: "zustand has no `batch`: on React 18, which batches updates itself, call the callback directly; before React 18, wrap it in `unstable_batchedUpdates` of react-dom.",
|
|
63
|
+
useStore: "Read the state with `useSelector` and dispatch with `useDispatch` instead of `useStore()`, or convert by hand."
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** What to do with a `connect` of a store that can't move whole, which only a store moving whole declares. */
|
|
67
|
+
export function connectAction(wholeStores: boolean): string {
|
|
68
|
+
return wholeStores ?
|
|
69
|
+
"`connect` converts only where the store moves whole, which takes a `configureStore` of `reducer` alone, or a `createStore` of a reducer with at most a preloaded state, `applyMiddleware(thunk)` and Redux DevTools. Remove what the store's other rows name so it moves whole, or replace `connect` with `useSelector` and `useDispatch`." :
|
|
70
|
+
"`connect` converts only where the store moves whole, which `wholeStores` turns off: run with it on, or replace `connect` with `useSelector` and `useDispatch`.";
|
|
40
71
|
}
|
|
41
72
|
|
|
42
73
|
/** What one source tells the plan. */
|
|
@@ -52,6 +83,11 @@ export interface SourceFacts {
|
|
|
52
83
|
unfollowed: {module: string, detail: string}[];
|
|
53
84
|
/** The Redux stores the source creates. */
|
|
54
85
|
stores: StoreFacts[];
|
|
86
|
+
/**
|
|
87
|
+
* The top-level `const name = state => state.key...` the source declares once, plain reads of the state, and those
|
|
88
|
+
* of them it exports as declared.
|
|
89
|
+
*/
|
|
90
|
+
readSelectors: {local: ReadonlySet<string>, exported: ReadonlySet<string>};
|
|
55
91
|
}
|
|
56
92
|
|
|
57
93
|
export interface StoreFacts {
|
|
@@ -62,6 +98,15 @@ export interface StoreFacts {
|
|
|
62
98
|
slices: Map<string, SliceFacts>;
|
|
63
99
|
/** The name the store module exports the store as, `default`, or undefined when it isn't exported at the top level. */
|
|
64
100
|
exportedAs?: string;
|
|
101
|
+
/**
|
|
102
|
+
* For a store that can move to zustand whole driven by its reducer, a `configureStore` of its `reducer` alone or a
|
|
103
|
+
* legacy `createStore` without an enhancer, how its reducer is given.
|
|
104
|
+
*/
|
|
105
|
+
reducerStore?: ReducerStoreKind;
|
|
106
|
+
/** Whether the store's own source uses the store other than to declare and export it, or to call its `getState`, `dispatch` or `subscribe`. */
|
|
107
|
+
usedInSource?: boolean;
|
|
108
|
+
/** The members of the store its own source calls, such as `subscribe`. */
|
|
109
|
+
calledInSource?: ReadonlySet<string>;
|
|
65
110
|
}
|
|
66
111
|
|
|
67
112
|
/** The parent tree of the node at `cursor`, past paddings and containers. */
|
|
@@ -212,15 +257,33 @@ export function walk(node: unknown, visit: (tree: J) => boolean): void {
|
|
|
212
257
|
|
|
213
258
|
const SKIPPED = new Set(["markers", "prefix", "type", "methodType", "fieldType", "variableType", "constructorType", "javaType", "before", "after"]);
|
|
214
259
|
|
|
260
|
+
/** The plain-read selectors `cu` declares, as {@link SourceFacts.readSelectors} says. */
|
|
261
|
+
function readSelectors(cu: JS.CompilationUnit, declared: ReadonlyMap<string, number>): SourceFacts["readSelectors"] {
|
|
262
|
+
const local = new Set<string>();
|
|
263
|
+
const exported = new Set<string>();
|
|
264
|
+
for (const {element} of cu.statements) {
|
|
265
|
+
if (element.kind !== J.Kind.VariableDeclarations) continue;
|
|
266
|
+
const declarations = element as J.VariableDeclarations;
|
|
267
|
+
if (!declarations.modifiers.some(m => m.keyword === "const")) continue;
|
|
268
|
+
for (const {element: variable} of declarations.variables) {
|
|
269
|
+
if (!isIdentifier(variable.name) || declared.get(variable.name.simpleName) !== 1 || !selectorRead(variable.initializer?.element)) continue;
|
|
270
|
+
local.add(variable.name.simpleName);
|
|
271
|
+
if (declarations.modifiers.some(m => m.keyword === "export")) exported.add(variable.name.simpleName);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return {local, exported};
|
|
275
|
+
}
|
|
276
|
+
|
|
215
277
|
/** The facts of one source, read once while scanning. */
|
|
216
278
|
export async function sourceFacts(cu: JS.CompilationUnit): Promise<SourceFacts> {
|
|
217
279
|
const bindings = importBindings(cu);
|
|
218
280
|
const declared = declaredNames(cu);
|
|
219
281
|
const facts: SourceFacts = {
|
|
220
282
|
path: cu.sourcePath, typescript: /\.(?:ts|tsx|mts|cts)$/.test(cu.sourcePath), test: TEST_SOURCE.test(cu.sourcePath),
|
|
221
|
-
bindings, declared: new Set(declared.keys()), uses: [], unfollowed: [], stores: []
|
|
283
|
+
bindings, declared: new Set(declared.keys()), uses: [], unfollowed: [], stores: [], readSelectors: readSelectors(cu, declared)
|
|
222
284
|
};
|
|
223
|
-
|
|
285
|
+
// A specifier no package can have, such as `@/store`, may name a source through an alias, which the plan resolves
|
|
286
|
+
const followed = new Map(bindings.filter(binding => binding.module === REACT_REDUX || isRelativeSpecifier(binding.module) || isAliasSpecifier(binding.module))
|
|
224
287
|
.map(binding => [binding.local, binding]));
|
|
225
288
|
for (const {element} of cu.statements) {
|
|
226
289
|
if (element.kind === JS.Kind.Import) {
|
|
@@ -275,16 +338,18 @@ export async function sourceFacts(cu: JS.CompilationUnit): Promise<SourceFacts>
|
|
|
275
338
|
}
|
|
276
339
|
|
|
277
340
|
/** The Redux stores `cu` creates, read once every slice of the repository is known. */
|
|
278
|
-
export async function storeFacts(cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule
|
|
341
|
+
export async function storeFacts(cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule>, resolve?: Resolve): Promise<StoreFacts[]> {
|
|
279
342
|
const stores: StoreFacts[] = [];
|
|
280
343
|
const functions = storeFunctions(cu);
|
|
281
344
|
if (functions.legacy.size === 0 && functions.configure.size === 0) return stores;
|
|
282
345
|
await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
283
346
|
override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
284
|
-
const store = storeFindings(call, cu, modules, functions);
|
|
347
|
+
const store = storeFindings(call, cu, modules, functions, resolve);
|
|
285
348
|
if (store) {
|
|
286
|
-
|
|
287
|
-
|
|
349
|
+
const name = storeNameAt(this.cursor);
|
|
350
|
+
const own = await usesInSource(cu, name, call);
|
|
351
|
+
stores.push({path: cu.sourcePath, api: store.api, store: name, findings: store.findings,
|
|
352
|
+
slices: store.slices, exportedAs: exportedStore(cu, this.cursor), reducerStore: store.reducerStore, usedInSource: own.other, calledInSource: own.called});
|
|
288
353
|
}
|
|
289
354
|
return super.visitMethodInvocation(call, ctx);
|
|
290
355
|
}
|
|
@@ -330,7 +395,7 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
|
|
|
330
395
|
if (trees.some(tree => tree.kind === JS.Kind.Import)) return undefined;
|
|
331
396
|
const parent = parentTree(cursor);
|
|
332
397
|
const local = identifier.simpleName;
|
|
333
|
-
const other = (detail: string): Use => ({local, kind: "other", detail});
|
|
398
|
+
const other = (detail: string, action?: string): Use => ({local, kind: "other", detail, ...action ? {action} : {}});
|
|
334
399
|
// Names of members, properties and attributes are no use of the import
|
|
335
400
|
if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).name.element === identifier) return undefined;
|
|
336
401
|
if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier && (parent as J.MethodInvocation).select) return undefined;
|
|
@@ -346,19 +411,27 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
|
|
|
346
411
|
return providerUse(tag, followed, local);
|
|
347
412
|
}
|
|
348
413
|
if (binding.module === REACT_REDUX) {
|
|
349
|
-
if (parent?.kind !== J.Kind.MethodInvocation || (parent as J.MethodInvocation).name !== identifier) return other(`\`${binding.name}\` from react-redux
|
|
414
|
+
if (parent?.kind !== J.Kind.MethodInvocation || (parent as J.MethodInvocation).name !== identifier) return other(`\`${binding.name}\` from react-redux`, REACT_REDUX_VALUE_ACTIONS[binding.name] ?? (binding.name.startsWith("use") ?
|
|
415
|
+
`\`${binding.name}\` is used other than called, most often in a typed alias such as \`const useApp${binding.name.slice(3)} = ${binding.name}\` or \`${binding.name}.withTypes<RootState>()\`, which the recipe doesn't follow: call \`${binding.name}\` itself where the alias is called and remove the alias, or convert by hand.` :
|
|
416
|
+
`\`${binding.name}\` is used other than called, such as passed or re-exported: call it where it's used, so the recipe follows each call, or convert by hand.`));
|
|
350
417
|
const call = parent as J.MethodInvocation;
|
|
418
|
+
if (binding.name === "connect") return connectUse(call, other) ?? {local, kind: "connect"};
|
|
351
419
|
if (binding.name === "useSelector") {
|
|
352
420
|
const args = argumentsOf(call);
|
|
353
421
|
const read = args.length === 1 && !call.typeParameters ? selectorRead(args[0]) : undefined;
|
|
354
|
-
|
|
422
|
+
if (read) return {local, kind: "selector", key: read.key};
|
|
423
|
+
// A selector passed by name moves only with its whole store, which calls it as it is
|
|
424
|
+
const selector = args.length === 1 && !call.typeParameters && isIdentifier(args[0]) ? args[0].simpleName : undefined;
|
|
425
|
+
return {...other("a selector that isn't a read of one slice's state"), reason: "SELECTOR", selector, anySelector: args.length === 1 && !call.typeParameters};
|
|
355
426
|
}
|
|
356
427
|
if (binding.name === "useDispatch") {
|
|
357
428
|
const variable = parentTree(cursorOf(cursor, call));
|
|
358
429
|
return variable?.kind === J.Kind.NamedVariable && dispatchers.has(((variable as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName)
|
|
359
|
-
? {local, kind: "dispatcher"} : other("`useDispatch` not held in a variable of its own"
|
|
430
|
+
? {local, kind: "dispatcher"} : other("`useDispatch` not held in a variable of its own",
|
|
431
|
+
"Hold the dispatcher in a `const` of its own, such as `const dispatch = useDispatch()`, and dispatch through it.");
|
|
360
432
|
}
|
|
361
|
-
return other(`\`${binding.name}\` from react-redux
|
|
433
|
+
return other(`\`${binding.name}\` from react-redux`, REACT_REDUX_CALL_ACTIONS[binding.name] ??
|
|
434
|
+
`The recipe converts only \`connect\`, \`useSelector\`, \`useDispatch\` and \`<Provider>\` of react-redux: replace \`${binding.name}(...)\` by hand.`);
|
|
362
435
|
}
|
|
363
436
|
// A relative import: an action creator, the store, a slice or anything else of the repository
|
|
364
437
|
if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier) {
|
|
@@ -377,10 +450,11 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
|
|
|
377
450
|
const outer = parentTree(cursorOf(cursor, call));
|
|
378
451
|
const read = getStateRead(call, outer);
|
|
379
452
|
if (read) return {local, kind: "getState", key: read.key};
|
|
380
|
-
|
|
381
|
-
|
|
453
|
+
const member = call.name.simpleName;
|
|
454
|
+
if (member === "dispatch" && dispatchedAction(call)) {
|
|
455
|
+
return isStatement(call, outer) ? {local, kind: "storeDispatch", member} : {...other("the dispatch's result is used"), reason: "DISPATCH", member};
|
|
382
456
|
}
|
|
383
|
-
return other(`\`${local}.${
|
|
457
|
+
return {...other(`\`${local}.${member}\``), member};
|
|
384
458
|
}
|
|
385
459
|
if (parent?.kind === JS.Kind.JsxEmbeddedExpression) {
|
|
386
460
|
const attribute = trees[2];
|
|
@@ -395,6 +469,25 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
|
|
|
395
469
|
return other("referenced");
|
|
396
470
|
}
|
|
397
471
|
|
|
472
|
+
/** Why a call of `connect` can't move to the zustand store's own `connect`, if it can't. */
|
|
473
|
+
function connectUse(call: J.MethodInvocation, other: (detail: string, action?: string) => Use): Use | undefined {
|
|
474
|
+
const args = argumentsOf(call);
|
|
475
|
+
// NOTE: a `null` read back from a stored LST doesn't keep `value: null`, so its source decides
|
|
476
|
+
const absent = (node: J | undefined) => !node ||
|
|
477
|
+
node.kind === J.Kind.Literal && (node as J.Literal).valueSource === "null" ||
|
|
478
|
+
isIdentifier(node) && node.simpleName === "undefined";
|
|
479
|
+
if (args.length > 4 || !absent(args[2])) return other("`connect` with `mergeProps`", "Merge the props in the wrapped component rather than with `mergeProps`, or convert by hand.");
|
|
480
|
+
if (args.length === 4 && !absent(args[3])) {
|
|
481
|
+
const options = objectProperties(args[3]);
|
|
482
|
+
const forwardRef = options?.get("forwardRef");
|
|
483
|
+
if (!options || options.size !== 1 || forwardRef?.kind !== J.Kind.Literal || typeof (forwardRef as J.Literal).value !== "boolean") {
|
|
484
|
+
return other("`connect` with options other than `forwardRef`",
|
|
485
|
+
"Pass `connect` no options, or only `{forwardRef: true}` or `{forwardRef: false}`; others, such as `context`, `areStatesEqual` or `pure`, are converted by hand.");
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return undefined;
|
|
489
|
+
}
|
|
490
|
+
|
|
398
491
|
/** A use of a dispatcher from `useDispatch`: only `dispatch(x(...))` of an imported `x`, whose result is unused, converts. */
|
|
399
492
|
function dispatcherUse(identifier: J.Identifier, cursor: Cursor, followed: ReadonlyMap<string, ImportBinding>,
|
|
400
493
|
bindings: readonly ImportBinding[]): Use | undefined {
|
|
@@ -414,16 +507,29 @@ function dispatcherUse(identifier: J.Identifier, cursor: Cursor, followed: Reado
|
|
|
414
507
|
return {local, kind: "other", detail: "the dispatcher is used other than to dispatch", reason: "DISPATCH"};
|
|
415
508
|
}
|
|
416
509
|
|
|
510
|
+
const PROVIDER_OTHER_STORE = "`Provider` gets something other than the store this package creates: pass it that store, under the name its source exports, or convert by hand.";
|
|
511
|
+
|
|
512
|
+
const PROVIDER_NOT_IMPORTED = "`Provider` gets a store that isn't imported, such as one made in this source, passed in, or held in a ref or `this`. " +
|
|
513
|
+
"A zustand store is one per module: pass `Provider` the store imported from the module that creates it at its top level, or convert by hand.";
|
|
514
|
+
|
|
417
515
|
/** `<Provider store={store}>` with one element child and no other prop. */
|
|
418
516
|
function providerUse(tag: JSX.Tag, followed: ReadonlyMap<string, ImportBinding>, local: string): Use {
|
|
419
|
-
const other = (detail: string): Use => ({local, kind: "other", detail});
|
|
517
|
+
const other = (detail: string, action?: string): Use => ({local, kind: "other", detail, ...action ? {action} : {}});
|
|
420
518
|
const attributes = tag.attributes.map(a => a.element);
|
|
421
|
-
if (attributes.length !== 1 || attributes[0].kind !== JS.Kind.JsxAttribute)
|
|
519
|
+
if (attributes.length !== 1 || attributes[0].kind !== JS.Kind.JsxAttribute) {
|
|
520
|
+
return other("`Provider` with props other than `store`", "`Provider`'s props other than `store`, such as `context` or `serverState`, have no zustand equivalent: convert by hand.");
|
|
521
|
+
}
|
|
422
522
|
const value = (attributes[0] as JSX.Attribute).value?.element;
|
|
423
523
|
const expression = value?.kind === JS.Kind.JsxEmbeddedExpression ? (value as JSX.EmbeddedExpression).expression.element : undefined;
|
|
424
|
-
if (!isIdentifier(expression) || !followed.has(expression.simpleName)) return other("`Provider` of a store that isn't imported");
|
|
425
|
-
if (!providerChild(tag)) return other("`Provider` without
|
|
426
|
-
return {local, kind: "providerTag"};
|
|
524
|
+
if (!isIdentifier(expression) || !followed.has(expression.simpleName)) return other("`Provider` of a store that isn't imported", PROVIDER_NOT_IMPORTED);
|
|
525
|
+
if (!providerChild(tag) && !providerChildren(tag)) return other("`Provider` without children");
|
|
526
|
+
return {local, kind: "providerTag", via: expression.simpleName};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** Whether a tag has children other than whitespace, which a fragment keeps when the tag goes. */
|
|
530
|
+
export function providerChildren(tag: JSX.Tag): boolean {
|
|
531
|
+
return !tag.selfClosing && (tag.children ?? []).some(child => !(child.kind === J.Kind.Literal && String((child as J.Literal).value ?? "").trim() === "") &&
|
|
532
|
+
child.kind !== J.Kind.Empty);
|
|
427
533
|
}
|
|
428
534
|
|
|
429
535
|
/** The one element child of a tag, with only whitespace around it. */
|
|
@@ -439,6 +545,51 @@ function cursorOf(cursor: Cursor, node: J): Cursor {
|
|
|
439
545
|
return cursor;
|
|
440
546
|
}
|
|
441
547
|
|
|
548
|
+
/** Members of a store that a whole store keeps, so that a call of one on the store's variable stays as it is. */
|
|
549
|
+
export const STORE_MEMBERS: ReadonlySet<string> = new Set(["getState", "dispatch", "subscribe"]);
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* How the statements of `cu` other than the store's declaration, `call`, and `export default name` refer to the store's
|
|
553
|
+
* variable: the members of `STORE_MEMBERS` they call on it, and whether they refer to it any other way.
|
|
554
|
+
*/
|
|
555
|
+
async function usesInSource(cu: JS.CompilationUnit, name: string, call: J.MethodInvocation): Promise<{other: boolean, called: Set<string>}> {
|
|
556
|
+
const result = {other: false, called: new Set<string>()};
|
|
557
|
+
const statements = cu.statements.map(s => s.element).flatMap(statement => {
|
|
558
|
+
if (statement.kind === JS.Kind.Import) return [];
|
|
559
|
+
// Exporting the store by name, which `exportedStore` reads, is no use of it
|
|
560
|
+
if (exportList(statement).some(entry => entry.local === name)) return [];
|
|
561
|
+
if (statement.kind === JS.Kind.ExportAssignment && isIdentifier((statement as JS.ExportAssignment).expression.element) &&
|
|
562
|
+
((statement as JS.ExportAssignment).expression.element as J.Identifier).simpleName === name) return [];
|
|
563
|
+
if (statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.some(v => v.element.initializer?.element === call)) {
|
|
564
|
+
return [call];
|
|
565
|
+
}
|
|
566
|
+
return [statement];
|
|
567
|
+
});
|
|
568
|
+
for (const statement of statements) {
|
|
569
|
+
if (![...namesReferencedWithin(statement)].includes(name)) continue;
|
|
570
|
+
await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
571
|
+
override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
|
|
572
|
+
if (identifier.simpleName !== name) return identifier;
|
|
573
|
+
const parent = parentTree(this.cursor);
|
|
574
|
+
// Names of members and properties are no use of the store
|
|
575
|
+
if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).name.element === identifier) return identifier;
|
|
576
|
+
if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier) {
|
|
577
|
+
if ((parent as J.MethodInvocation).select) return identifier;
|
|
578
|
+
} else if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).select?.element === identifier &&
|
|
579
|
+
STORE_MEMBERS.has((parent as J.MethodInvocation).name.simpleName)) {
|
|
580
|
+
result.called.add((parent as J.MethodInvocation).name.simpleName);
|
|
581
|
+
return identifier;
|
|
582
|
+
}
|
|
583
|
+
if (parent?.kind === JS.Kind.PropertyAssignment && (parent as JS.PropertyAssignment).name.element === identifier &&
|
|
584
|
+
(parent as JS.PropertyAssignment).initializer) return identifier;
|
|
585
|
+
result.other = true;
|
|
586
|
+
return identifier;
|
|
587
|
+
}
|
|
588
|
+
}().visit(statement, new ExecutionContext());
|
|
589
|
+
}
|
|
590
|
+
return result;
|
|
591
|
+
}
|
|
592
|
+
|
|
442
593
|
function storeNameAt(cursor: Cursor): string {
|
|
443
594
|
for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
|
|
444
595
|
const node = c.value as J;
|
|
@@ -469,7 +620,25 @@ function exportedStore(cu: JS.CompilationUnit, cursor: Cursor): string | undefin
|
|
|
469
620
|
if (declarations.modifiers.some(m => m.keyword === "export")) return name;
|
|
470
621
|
const exported = cu.statements.map(s => s.element).find(s => s.kind === JS.Kind.ExportAssignment &&
|
|
471
622
|
isIdentifier((s as JS.ExportAssignment).expression.element) && ((s as JS.ExportAssignment).expression.element as J.Identifier).simpleName === name);
|
|
472
|
-
|
|
623
|
+
if (exported) return "default";
|
|
624
|
+
// `export {store}`, or `export {store as appStore}`, once
|
|
625
|
+
const listed = cu.statements.flatMap(s => exportList(s.element)).filter(entry => entry.local === name);
|
|
626
|
+
return listed.length === 1 ? listed[0].exported : undefined;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** The local and exported names of `export {a, b as c}`, with no module specifier and no `type`. */
|
|
630
|
+
function exportList(statement: J): {local: string, exported: string}[] {
|
|
631
|
+
if (statement.kind !== JS.Kind.ExportDeclaration) return [];
|
|
632
|
+
const declaration = statement as JS.ExportDeclaration;
|
|
633
|
+
if (declaration.moduleSpecifier || declaration.typeOnly.element || declaration.exportClause?.kind !== JS.Kind.NamedExports) return [];
|
|
634
|
+
return (declaration.exportClause as JS.NamedExports).elements.elements.flatMap(({element}) => {
|
|
635
|
+
if (element.kind !== JS.Kind.ExportSpecifier || (element as JS.ExportSpecifier).typeOnly.element) return [];
|
|
636
|
+
const specifier = (element as JS.ExportSpecifier).specifier;
|
|
637
|
+
if (isIdentifier(specifier)) return [{local: specifier.simpleName, exported: specifier.simpleName}];
|
|
638
|
+
if (specifier.kind !== JS.Kind.Alias) return [];
|
|
639
|
+
const local = (specifier as JS.Alias).propertyName.element, alias = (specifier as JS.Alias).alias;
|
|
640
|
+
return isIdentifier(local) && isIdentifier(alias) ? [{local: local.simpleName, exported: alias.simpleName}] : [];
|
|
641
|
+
});
|
|
473
642
|
}
|
|
474
643
|
|
|
475
644
|
/** A slice of the store, with what the conversion writes for it. */
|
|
@@ -497,8 +666,25 @@ export interface Plan {
|
|
|
497
666
|
sources: Set<string>;
|
|
498
667
|
/** Why each store doesn't convert, by store; the converting store has no entry. */
|
|
499
668
|
blocked: Map<StoreFacts, Finding[]>;
|
|
669
|
+
/**
|
|
670
|
+
* For a store that moves to zustand whole, the names the conversion gives its zustand store and its reducer, and,
|
|
671
|
+
* where a source calls `connect`, the module whose `unstable_batchedUpdates` the store's `connect` renders with.
|
|
672
|
+
*/
|
|
673
|
+
reducerStore?: {hook: string, reducer: string, renderer?: string, selectorHook?: string, listeners?: string};
|
|
500
674
|
}
|
|
501
675
|
|
|
676
|
+
/**
|
|
677
|
+
* The hook a whole store's source declares for selectors that may build a value, where the store's own hook, as
|
|
678
|
+
* zustand 5's does, runs the selector on each read: it keeps the selection while the state and the selector stay.
|
|
679
|
+
*/
|
|
680
|
+
export const SELECTOR_HOOK = "useAppStoreSelector";
|
|
681
|
+
|
|
682
|
+
/** The `Map` a whole store's source keeps the listeners of its `subscribe` in. */
|
|
683
|
+
export const STORE_LISTENERS = "storeListeners";
|
|
684
|
+
|
|
685
|
+
/** The zustand store a store becomes when it moves whole, driven by its own reducer. */
|
|
686
|
+
export const REDUCER_STORE_HOOK = "useAppStore";
|
|
687
|
+
|
|
502
688
|
/** The hook a slice under `key` becomes, such as `useCounterStore` for `counter`. */
|
|
503
689
|
export const hookName = (key: string) => `use${key.charAt(0).toUpperCase()}${key.slice(1)}Store`;
|
|
504
690
|
|
|
@@ -507,7 +693,10 @@ export const hookName = (key: string) => `use${key.charAt(0).toUpperCase()}${key
|
|
|
507
693
|
* slices can be rewritten, and every use of the store, its slices, their action creators and react-redux converts.
|
|
508
694
|
*/
|
|
509
695
|
export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>,
|
|
510
|
-
dependencies: (storePath: string) => Finding | undefined, scope: (path: string) => boolean = () => true
|
|
696
|
+
dependencies: (storePath: string, immer?: boolean) => Finding | undefined, scope: (path: string) => boolean = () => true,
|
|
697
|
+
wholeStores = true, renderer: (storePath: string) => string | undefined = () => "react-dom",
|
|
698
|
+
selectsOnEachRead: (storePath: string) => boolean = () => false,
|
|
699
|
+
resolveFrom: Resolve = (from, specifier) => resolveRelative(from, specifier, facts)): Plan {
|
|
511
700
|
const stores = [...facts.values()].filter(source => scope(source.path)).flatMap(source => source.stores);
|
|
512
701
|
const result: Plan = {slices: new Map(), sources: new Set(), blocked: new Map()};
|
|
513
702
|
if (stores.length === 0) return result;
|
|
@@ -517,7 +706,7 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
|
|
|
517
706
|
}
|
|
518
707
|
const store = stores[0];
|
|
519
708
|
const findings: Finding[] = [...store.findings];
|
|
520
|
-
const block = (reason: string, detail: string) => findings.push({reason, detail});
|
|
709
|
+
const block = (reason: string, detail: string, action?: string) => findings.push({reason, detail, ...action ? {action} : {}});
|
|
521
710
|
// Slices that stay in Redux for a reason of their own, already recorded: their uses add nothing to it
|
|
522
711
|
const held = new Map<string, string>();
|
|
523
712
|
const handled = new Map<string, string>();
|
|
@@ -566,7 +755,7 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
|
|
|
566
755
|
const slicePaths = new Map([...result.slices.values()].map(slice => [slice.path, slice]));
|
|
567
756
|
const sources = new Set<string>([store.path, ...slicePaths.keys()]);
|
|
568
757
|
for (const source of facts.values()) {
|
|
569
|
-
const resolve = (module: string) =>
|
|
758
|
+
const resolve = (module: string) => resolveFrom(source.path, module);
|
|
570
759
|
const touches = (module: string) => {
|
|
571
760
|
const path = resolve(module);
|
|
572
761
|
return path === store.path || (path !== undefined && slicePaths.has(path));
|
|
@@ -606,8 +795,9 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
|
|
|
606
795
|
if (source.path === store.path && slice && use.kind === "other") continue;
|
|
607
796
|
changes = true;
|
|
608
797
|
const where = `${use.local} in ${source.path}`;
|
|
798
|
+
if (use.kind === "providerTag" && !provides(source, use, store, resolve)) block("REACT_REDUX_USE", `${where}: \`Provider\` of \`${use.via}\`, which isn't the store`, PROVIDER_OTHER_STORE);
|
|
609
799
|
if (use.kind === "other") {
|
|
610
|
-
block(use.reason ?? (isStore ? "STORE_USE" : slice ? "SLICE_USE" : !binding ? "DISPATCH" : isReactRedux ? "REACT_REDUX_USE" : "STORE_USE"), `${where}: ${use.detail}
|
|
800
|
+
block(use.reason ?? (isStore ? "STORE_USE" : slice ? "SLICE_USE" : !binding ? "DISPATCH" : isReactRedux ? "REACT_REDUX_USE" : "STORE_USE"), `${where}: ${use.detail}`, use.action);
|
|
611
801
|
} else if (use.kind === "selector" || use.kind === "getState") {
|
|
612
802
|
if (!result.slices.has(use.key!)) block("SELECTOR", `${where} reads \`${use.key}\`, which is no slice of the store`);
|
|
613
803
|
} else if (use.kind === "dispatched") {
|
|
@@ -615,6 +805,8 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
|
|
|
615
805
|
if (!slice || !binding || !slice.actions.has(binding.name) && !slice.unknown.has(binding.name) && !slice.thunkVariables.has(binding.name)) block("DISPATCH", `${where} dispatches what isn't an action creator of a slice`);
|
|
616
806
|
const via = source.bindings.find(b => b.local === use.via);
|
|
617
807
|
if (via && !(resolve(via.module) === store.path && via.name === store.exportedAs)) block("DISPATCH", `${where} is dispatched through \`${use.via}\``);
|
|
808
|
+
} else if (use.kind === "connect") {
|
|
809
|
+
block("REACT_REDUX_USE", `${where}: \`connect\` from react-redux`, connectAction(wholeStores));
|
|
618
810
|
} else if ((use.kind === "provider" || use.kind === "storeDispatch") && !isStore) {
|
|
619
811
|
block("STORE_USE", `${where} isn't the store`);
|
|
620
812
|
}
|
|
@@ -639,6 +831,8 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
|
|
|
639
831
|
}
|
|
640
832
|
}
|
|
641
833
|
if ([store.path, ...slicePaths.keys()].some(path => /\.(?:ts|tsx|mts|cts)$/.test(path))) block("TYPESCRIPT", store.path);
|
|
834
|
+
// A store whose slices can't move one by one may still move whole, its reducer running on one zustand store
|
|
835
|
+
if (findings.length > 0 && store.reducerStore && wholeStores) return reducerPlan(facts, sliceSources, store, dependencies, scope, renderer, selectsOnEachRead, resolveFrom);
|
|
642
836
|
if (findings.length > 0) {
|
|
643
837
|
result.blocked.set(store, dedupe(findings));
|
|
644
838
|
result.slices.clear();
|
|
@@ -649,15 +843,142 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
|
|
|
649
843
|
return result;
|
|
650
844
|
}
|
|
651
845
|
|
|
846
|
+
/**
|
|
847
|
+
* Plans a store of its `reducer` alone to move whole: one zustand store whose state is the reducer's, and whose
|
|
848
|
+
* `dispatch` runs the reducer as Redux does, and thunks as Redux Toolkit's default middleware does. The slices, their
|
|
849
|
+
* action creators and thunks stay as they are, so only the uses of react-redux and of the store itself must convert.
|
|
850
|
+
*/
|
|
851
|
+
function reducerPlan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>, store: StoreFacts,
|
|
852
|
+
dependencies: (storePath: string, immer?: boolean) => Finding | undefined, scope: (path: string) => boolean,
|
|
853
|
+
renderer: (storePath: string) => string | undefined, selectsOnEachRead: (storePath: string) => boolean, resolveFrom: Resolve): Plan {
|
|
854
|
+
const findings: Finding[] = [];
|
|
855
|
+
const block = (reason: string, detail: string, action?: string) => findings.push({reason, detail, ...action ? {action} : {}});
|
|
856
|
+
const hook = REDUCER_STORE_HOOK;
|
|
857
|
+
// A legacy `createStore` source has no slice source, so its own declarations and imports count too
|
|
858
|
+
const source = facts.get(store.path);
|
|
859
|
+
const names = new Set<string>([...sliceSources.get(store.path)?.names ?? [], ...source?.declared ?? [], ...source?.bindings.map(b => b.local) ?? []]);
|
|
860
|
+
const reducer = ["rootReducer", "appReducer", "storeReducer"].find(name => !names.has(name)) ?? "rootReducer";
|
|
861
|
+
if (!store.exportedAs) block("STORE_NOT_MODULE_LEVEL", store.store);
|
|
862
|
+
if (store.usedInSource) block("STORE_USE", `\`${store.store}\` is used in its own source`);
|
|
863
|
+
const dependency = dependencies(store.path, false);
|
|
864
|
+
if (dependency) findings.push(dependency);
|
|
865
|
+
for (const name of [hook, reducer, "create"]) if (names.has(name)) block("NAME_TAKEN", `${name} in ${store.path}`);
|
|
866
|
+
const storeSource = facts.get(store.path);
|
|
867
|
+
// RTK's `combineReducers` combines the reducers, as `configureStore` does, under its own name
|
|
868
|
+
const rtkCombine = storeSource?.bindings.some(b => b.local === "combineReducers" && b.module === RTK && b.name === "combineReducers");
|
|
869
|
+
if (store.reducerStore === "combined" && names.has("combineReducers") && !rtkCombine) block("NAME_TAKEN", `combineReducers in ${store.path}`);
|
|
870
|
+
const sources = new Set<string>([store.path]);
|
|
871
|
+
let connects = false;
|
|
872
|
+
let selects = false;
|
|
873
|
+
// Redux calls a store's listeners after every dispatch, which the store's `dispatch` does for its own `subscribe`
|
|
874
|
+
let subscribes = store.calledInSource?.has("subscribe") ?? false;
|
|
875
|
+
for (const source of facts.values()) {
|
|
876
|
+
const resolve = (module: string) => resolveFrom(source.path, module);
|
|
877
|
+
if (!scope(source.path)) {
|
|
878
|
+
for (const binding of source.bindings) {
|
|
879
|
+
if (binding.module !== REACT_REDUX && resolve(binding.module) === store.path) block("STORE_USE", `${binding.local} in ${source.path}, of another package`);
|
|
880
|
+
}
|
|
881
|
+
for (const {module, detail} of source.unfollowed) {
|
|
882
|
+
if (resolve(module) === store.path) block("UNFOLLOWED_IMPORT", `${detail} of ${module} in ${source.path}, of another package`);
|
|
883
|
+
}
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
for (const {module, detail} of source.unfollowed) {
|
|
887
|
+
if (module === REACT_REDUX || resolve(module) === store.path) block("UNFOLLOWED_IMPORT", `${detail} of ${module} in ${source.path}`);
|
|
888
|
+
}
|
|
889
|
+
let changes = false;
|
|
890
|
+
for (const use of source.uses) {
|
|
891
|
+
const binding = source.bindings.find(b => b.local === use.local);
|
|
892
|
+
// A dispatcher stays the store's `dispatch`, whatever it is used for, and the slices stay as they are
|
|
893
|
+
if (!binding) continue;
|
|
894
|
+
const where = `${use.local} in ${source.path}`;
|
|
895
|
+
if (binding.module === REACT_REDUX) {
|
|
896
|
+
changes = true;
|
|
897
|
+
if (use.kind === "connect") connects = true;
|
|
898
|
+
if (use.kind === "providerTag" && !provides(source, use, store, resolve)) block("REACT_REDUX_USE", `${where}: \`Provider\` of \`${use.via}\`, which isn't the store`, PROVIDER_OTHER_STORE);
|
|
899
|
+
if (use.kind === "other" && use.selector && readSelector(source, use.selector, facts, resolveFrom)) continue;
|
|
900
|
+
// Any other selector runs as it is on the whole store, through a hook that keeps its selection where the store's own doesn't
|
|
901
|
+
if (use.kind === "other" && use.anySelector) {
|
|
902
|
+
if (selectsOnEachRead(store.path)) selects = true;
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
if (use.kind === "other") block(use.reason ?? "REACT_REDUX_USE", `${where}: ${use.detail}`, use.action);
|
|
906
|
+
continue;
|
|
907
|
+
}
|
|
908
|
+
const path = resolve(binding.module);
|
|
909
|
+
// What else the store's source exports stays there
|
|
910
|
+
if (path !== store.path || binding.name !== store.exportedAs) continue;
|
|
911
|
+
if (use.kind === "provider") changes = true;
|
|
912
|
+
else if (use.kind === "other" && use.member === "subscribe") subscribes = true;
|
|
913
|
+
else if (use.kind === "other" && use.member !== "getState" && use.member !== "dispatch") block(use.reason === "DISPATCH" ? "STORE_USE" : use.reason ?? "STORE_USE", `${where}: ${use.detail}`);
|
|
914
|
+
}
|
|
915
|
+
if (changes && source.path !== store.path) {
|
|
916
|
+
if (source.typescript) block("TYPESCRIPT", source.path);
|
|
917
|
+
if (source.bindings.some(b => b.local === hook) || source.declared.has(hook)) block("NAME_TAKEN", `${hook} in ${source.path}`);
|
|
918
|
+
sources.add(source.path);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (/\.(?:ts|tsx|mts|cts)$/.test(store.path)) block("TYPESCRIPT", store.path);
|
|
922
|
+
// The store's source declares `connect`, with what it imports to render and to batch the store's updates
|
|
923
|
+
const module = connects ? renderer(store.path) : undefined;
|
|
924
|
+
if (connects && !module) block("REACT_REDUX_USE", `connect in a package that declares neither react-dom nor react-native`);
|
|
925
|
+
if (connects && storeSource) {
|
|
926
|
+
const helpers: [string, string][] = [["connect", ""], ...["createElement", "forwardRef", "memo", "useRef"].map(name => [name, "react"] as [string, string]),
|
|
927
|
+
["unstable_batchedUpdates", module ?? ""]];
|
|
928
|
+
for (const [name, from] of helpers) {
|
|
929
|
+
const bound = storeSource.bindings.find(b => b.local === name);
|
|
930
|
+
if (storeSource.declared.has(name) || bound && (bound.module !== from || bound.name !== name)) block("NAME_TAKEN", `${name} in ${store.path}`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
if (selects && storeSource) {
|
|
934
|
+
for (const name of [SELECTOR_HOOK, "useRef", "useSyncExternalStore"]) {
|
|
935
|
+
const bound = storeSource.bindings.find(b => b.local === name);
|
|
936
|
+
if (storeSource.declared.has(name) || bound && (bound.module !== (name === SELECTOR_HOOK ? "" : "react") || bound.name !== name)) block("NAME_TAKEN", `${name} in ${store.path}`);
|
|
937
|
+
}
|
|
938
|
+
for (const path of sources) {
|
|
939
|
+
const source = facts.get(path);
|
|
940
|
+
if (source && path !== store.path && (source.declared.has(SELECTOR_HOOK) || source.bindings.some(b => b.local === SELECTOR_HOOK))) block("NAME_TAKEN", `${SELECTOR_HOOK} in ${path}`);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (subscribes && names.has(STORE_LISTENERS)) block("NAME_TAKEN", `${STORE_LISTENERS} in ${store.path}`);
|
|
944
|
+
const result: Plan = {slices: new Map(), sources: new Set(), blocked: new Map()};
|
|
945
|
+
if (findings.length > 0) {
|
|
946
|
+
result.blocked.set(store, dedupe(findings));
|
|
947
|
+
return result;
|
|
948
|
+
}
|
|
949
|
+
return {...result, store, sources, reducerStore: {hook, reducer, ...module ? {renderer: module} : {}, ...selects ? {selectorHook: SELECTOR_HOOK} : {},
|
|
950
|
+
...subscribes ? {listeners: STORE_LISTENERS} : {}}};
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/** Whether the `Provider` of a `providerTag` use provides `store`, as its source imports it. */
|
|
954
|
+
function provides(source: SourceFacts, use: Use, store: StoreFacts, resolve: (module: string) => string | undefined): boolean {
|
|
955
|
+
const binding = source.bindings.find(b => b.local === use.via);
|
|
956
|
+
return !!binding && binding.module !== REACT_REDUX && resolve(binding.module) === store.path && binding.name === store.exportedAs;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* Whether `name`, which `source` passes to `useSelector`, is a plain read of the state: a `const` of its own, or one it
|
|
961
|
+
* imports by the name a followed module exports it as.
|
|
962
|
+
*/
|
|
963
|
+
export function readSelector(source: SourceFacts, name: string, facts: ReadonlyMap<string, SourceFacts>,
|
|
964
|
+
resolve: Resolve = (from, specifier) => resolveRelative(from, specifier, facts)): boolean {
|
|
965
|
+
const binding = source.bindings.find(b => b.local === name);
|
|
966
|
+
if (!binding) return source.readSelectors.local.has(name);
|
|
967
|
+
const path = resolve(source.path, binding.module);
|
|
968
|
+
return path !== undefined && (facts.get(path)?.readSelectors.exported.has(binding.name) ?? false);
|
|
969
|
+
}
|
|
970
|
+
|
|
652
971
|
/**
|
|
653
972
|
* A plan for each package that creates a store, by `packageOf`, the root of the package a source is in. A package's
|
|
654
973
|
* one store converts with its own sources; what another package imports of it keeps it in Redux.
|
|
655
974
|
*/
|
|
656
975
|
export function planPackages(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>,
|
|
657
|
-
packageOf: (path: string) => string | undefined, dependencies: (storePath: string) => Finding | undefined
|
|
976
|
+
packageOf: (path: string) => string | undefined, dependencies: (storePath: string, immer?: boolean) => Finding | undefined,
|
|
977
|
+
wholeStores = true, renderer?: (storePath: string) => string | undefined,
|
|
978
|
+
selectsOnEachRead?: (storePath: string) => boolean, resolve?: Resolve): Plan[] {
|
|
658
979
|
const root = (path: string) => packageOf(path) ?? "";
|
|
659
980
|
const roots = new Set([...facts.values()].filter(source => source.stores.length > 0).map(source => root(source.path)));
|
|
660
|
-
return [...roots].map(packageRoot => plan(facts, sliceSources, dependencies, path => root(path) === packageRoot));
|
|
981
|
+
return [...roots].map(packageRoot => plan(facts, sliceSources, dependencies, path => root(path) === packageRoot, wholeStores, renderer, selectsOnEachRead, resolve));
|
|
661
982
|
}
|
|
662
983
|
|
|
663
984
|
function dedupe(findings: Finding[]): Finding[] {
|