@openrewrite/recipes-react 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +10 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/search/find-enzyme-usage.d.ts +4 -0
  10. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  11. package/dist/search/find-enzyme-usage.js +30 -3
  12. package/dist/search/find-enzyme-usage.js.map +1 -1
  13. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  14. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  15. package/dist/search/find-hard-coded-strings.js +987 -0
  16. package/dist/search/find-hard-coded-strings.js.map +1 -0
  17. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  18. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  19. package/dist/search/find-missing-use-client-directive.js +1 -0
  20. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  21. package/dist/testing/enzyme-portals.d.ts +3 -5
  22. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  23. package/dist/testing/enzyme-portals.js +8 -39
  24. package/dist/testing/enzyme-portals.js.map +1 -1
  25. package/dist/testing/enzyme-render-blockers.d.ts +10 -0
  26. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  27. package/dist/testing/enzyme-render-blockers.js +119 -0
  28. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  29. package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
  30. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  31. package/dist/testing/enzyme-to-react-testing-library.js +80 -17
  32. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  33. package/dist/testing/enzyme-usage.d.ts +2 -0
  34. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  35. package/dist/testing/enzyme-usage.js +29 -3
  36. package/dist/testing/enzyme-usage.js.map +1 -1
  37. package/dist/testing/enzyme-wrapper-scope.d.ts +5 -1
  38. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  39. package/dist/testing/enzyme-wrapper-scope.js +12 -3
  40. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  41. package/dist/util/json-and-javascript.d.ts +4 -0
  42. package/dist/util/json-and-javascript.d.ts.map +1 -0
  43. package/dist/util/json-and-javascript.js +37 -0
  44. package/dist/util/json-and-javascript.js.map +1 -0
  45. package/dist/util/module-imports.d.ts +36 -0
  46. package/dist/util/module-imports.d.ts.map +1 -1
  47. package/dist/util/module-imports.js +216 -0
  48. package/dist/util/module-imports.js.map +1 -1
  49. package/dist/util/test-source.d.ts +2 -0
  50. package/dist/util/test-source.d.ts.map +1 -0
  51. package/dist/util/test-source.js +5 -0
  52. package/dist/util/test-source.js.map +1 -0
  53. package/dist/zustand/entry-store.d.ts +9 -0
  54. package/dist/zustand/entry-store.d.ts.map +1 -0
  55. package/dist/zustand/entry-store.js +136 -0
  56. package/dist/zustand/entry-store.js.map +1 -0
  57. package/dist/zustand/redux-stores.d.ts +5 -4
  58. package/dist/zustand/redux-stores.d.ts.map +1 -1
  59. package/dist/zustand/redux-stores.js +8 -5
  60. package/dist/zustand/redux-stores.js.map +1 -1
  61. package/dist/zustand/redux-to-zustand.d.ts +11 -2
  62. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  63. package/dist/zustand/redux-to-zustand.js +137 -42
  64. package/dist/zustand/redux-to-zustand.js.map +1 -1
  65. package/dist/zustand/zustand-plan.d.ts +7 -5
  66. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  67. package/dist/zustand/zustand-plan.js +87 -33
  68. package/dist/zustand/zustand-plan.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  71. package/src/index.ts +7 -0
  72. package/src/search/find-enzyme-usage.ts +30 -6
  73. package/src/search/find-hard-coded-strings.ts +1006 -0
  74. package/src/search/find-missing-use-client-directive.ts +1 -1
  75. package/src/testing/enzyme-portals.ts +4 -44
  76. package/src/testing/enzyme-render-blockers.ts +113 -0
  77. package/src/testing/enzyme-to-react-testing-library.ts +90 -18
  78. package/src/testing/enzyme-usage.ts +35 -2
  79. package/src/testing/enzyme-wrapper-scope.ts +13 -2
  80. package/src/util/json-and-javascript.ts +26 -0
  81. package/src/util/module-imports.ts +223 -0
  82. package/src/util/test-source.ts +2 -0
  83. package/src/zustand/entry-store.ts +131 -0
  84. package/src/zustand/redux-stores.ts +12 -7
  85. package/src/zustand/redux-to-zustand.ts +168 -48
  86. package/src/zustand/zustand-plan.ts +98 -32
@@ -1,4 +1,6 @@
1
+ import {TreePrinters} from "@openrewrite/rewrite";
1
2
  import {JS, moduleNameOf} from "@openrewrite/rewrite/javascript";
3
+ import {Json} from "@openrewrite/rewrite/json";
2
4
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
5
  import {posix} from "path";
4
6
 
@@ -34,6 +36,21 @@ export function importBindings(cu: JS.CompilationUnit): ImportBinding[] {
34
36
  return bindings;
35
37
  }
36
38
 
39
+ /** The modules a source's namespace imports, `import * as name`, bind, by local name. */
40
+ export function namespaceImportModules(cu: JS.CompilationUnit): Map<string, string> {
41
+ const modules = new Map<string, string>();
42
+ for (const {element} of cu.statements) {
43
+ if (element.kind !== JS.Kind.Import) continue;
44
+ const declaration = element as JS.Import;
45
+ const bindings = declaration.importClause?.namedBindings;
46
+ const specifier = declaration.moduleSpecifier?.element;
47
+ if (bindings?.kind === JS.Kind.Alias && isIdentifier((bindings as JS.Alias).alias) && specifier?.kind === J.Kind.Literal) {
48
+ modules.set(((bindings as JS.Alias).alias as J.Identifier).simpleName, moduleNameOf(specifier as J.Literal));
49
+ }
50
+ }
51
+ return modules;
52
+ }
53
+
37
54
  /** The local names of a source's namespace imports, `import * as name`, which bind a whole module. */
38
55
  export function namespaceImports(cu: JS.CompilationUnit): string[] {
39
56
  const names: string[] = [];
@@ -52,9 +69,215 @@ export function isRelativeSpecifier(specifier: string): boolean {
52
69
  return /^\.\.?(?:\/|$)/.test(specifier);
53
70
  }
54
71
 
72
+ /** Resolves a module specifier from the source at the first path to the source it names, if it names one. */
73
+ export type Resolve = (from: string, specifier: string) => string | undefined;
74
+
75
+ /** The `compilerOptions.paths` of a `jsconfig.json` or `tsconfig.json`, and the directory its targets resolve from. */
76
+ export interface PathsConfig {
77
+ readonly base: string;
78
+ readonly paths: readonly (readonly [string, readonly string[]])[];
79
+ }
80
+
81
+ /** Whether a module specifier is one that no npm package can have, such as `@/store` or `~/store`, which only a project's alias resolves. */
82
+ export function isAliasSpecifier(specifier: string): boolean {
83
+ return /^[@~]\//.test(specifier);
84
+ }
85
+
86
+ /**
87
+ * The source a specifier resolves to from the source at `from`: a relative one as Node resolves it, and an alias specifier
88
+ * through the `paths` of the nearest `configs`, by directory, as TypeScript resolves it.
89
+ */
90
+ export function resolveModule(from: string, specifier: string, sources: {has(path: string): boolean}, configs: ReadonlyMap<string, PathsConfig>): string | undefined {
91
+ if (!isAliasSpecifier(specifier)) return resolveRelative(from, specifier, sources);
92
+ const directory = [...configs.keys()].filter(dir => from.startsWith(dir)).sort((a, b) => b.length - a.length)[0];
93
+ const config = directory !== undefined ? configs.get(directory) : undefined;
94
+ if (!config) return undefined;
95
+ // TypeScript takes the pattern with the longest prefix before its `*`, so an exact pattern comes first
96
+ const matches = config.paths.flatMap(([pattern, targets]) => {
97
+ const star = pattern.indexOf("*");
98
+ if (star < 0) return pattern === specifier ? [{prefix: pattern.length, rest: "", targets}] : [];
99
+ const prefix = pattern.slice(0, star), suffix = pattern.slice(star + 1);
100
+ return specifier.length >= prefix.length + suffix.length && specifier.startsWith(prefix) && specifier.endsWith(suffix) ?
101
+ [{prefix: prefix.length, rest: specifier.slice(prefix.length, specifier.length - suffix.length), targets}] : [];
102
+ }).sort((a, b) => b.prefix - a.prefix);
103
+ for (const {rest, targets} of matches) {
104
+ for (const target of targets) {
105
+ const base = posix.normalize(posix.join(config.base || ".", target.replace("*", rest)));
106
+ const found = RESOLVED.map(suffix => base + suffix).find(path => sources.has(path));
107
+ if (found) return found;
108
+ }
109
+ }
110
+ return undefined;
111
+ }
112
+
55
113
  /** The source a relative module specifier resolves to from the source at `from`, as Node resolves it among `sources`. */
56
114
  export function resolveRelative(from: string, specifier: string, sources: {has(path: string): boolean}): string | undefined {
57
115
  if (!isRelativeSpecifier(specifier)) return undefined;
58
116
  const base = posix.normalize(posix.join(posix.dirname(from), specifier));
59
117
  return RESOLVED.map(suffix => base + suffix).find(path => sources.has(path));
60
118
  }
119
+
120
+ /** Where module specifiers of a source resolve: relative ones as Node resolves them, bare ones through a `baseUrl` alias. */
121
+ export interface Resolver {
122
+ (from: string, specifier: string): string | undefined;
123
+ }
124
+
125
+ /** The package a bare module specifier names, such as `@scope/name` for `@scope/name/sub`. */
126
+ export function packageName(specifier: string): string {
127
+ const parts = specifier.split("/");
128
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
129
+ }
130
+
131
+ /**
132
+ * Resolves relative specifiers among the scanned sources, and a bare one that no enclosing package
133
+ * declares from each of `roots`, the way a `baseUrl` of the package or the repository resolves it.
134
+ */
135
+ export function resolver(modules: {has(path: string): boolean}, roots: readonly string[], declares: (name: string) => boolean): Resolver {
136
+ return (from, specifier) => {
137
+ const relative = resolveRelative(from, specifier, modules);
138
+ if (relative || isRelativeSpecifier(specifier) || specifier.startsWith("node:") || declares(packageName(specifier))) return relative;
139
+ for (const root of roots) {
140
+ const aliased = resolveRelative(posix.join(root || ".", "_"), `./${specifier}`, modules);
141
+ if (aliased) return aliased;
142
+ }
143
+ return undefined;
144
+ };
145
+ }
146
+
147
+ /** Each name a named export clause exports, to the name it has in the module it comes from. */
148
+ export function exportedNames(clause: JS.NamedExports): Map<string, string> {
149
+ const names = new Map<string, string>();
150
+ for (const {element: exported} of clause.elements.elements) {
151
+ if (exported.kind !== JS.Kind.ExportSpecifier) continue;
152
+ const named = (exported as JS.ExportSpecifier).specifier;
153
+ if (isIdentifier(named)) names.set(named.simpleName, named.simpleName);
154
+ if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
155
+ const property = (named as JS.Alias).propertyName.element;
156
+ names.set(((named as JS.Alias).alias as J.Identifier).simpleName,
157
+ isIdentifier(property) ? property.simpleName : String((property as J.Literal).value));
158
+ }
159
+ }
160
+ return names;
161
+ }
162
+
163
+ /**
164
+ * {@link resolver}, and also a `@/` or `~/` path alias, onto the nearest of `roots` that holds a match, at the
165
+ * root or in its `src` directory. Where both hold one the alias is ambiguous and stays unresolved.
166
+ */
167
+ export function aliasResolver(modules: {has(path: string): boolean}, roots: readonly string[], declares: (name: string) => boolean): Resolver {
168
+ const resolve = resolver(modules, roots, declares);
169
+ return (from, specifier) => {
170
+ if (!/^[@~]\//.test(specifier)) return resolve(from, specifier);
171
+ for (const root of roots) {
172
+ const found = [root, `${root}src/`]
173
+ .map(base => resolveRelative(posix.join(base || ".", "_"), `.${specifier.slice(1)}`, modules))
174
+ .filter((path): path is string => path !== undefined);
175
+ if (found.length > 0) return found.length === 1 ? found[0] : undefined;
176
+ }
177
+ return undefined;
178
+ };
179
+ }
180
+
181
+ /** A source's own exports, each exported name to the local name it exports, and its `export ... from` re-exports. */
182
+ export interface ModuleExports {
183
+ locals: ReadonlyMap<string, string>;
184
+ reExports: readonly {module: string, names: ReadonlyMap<string, string> | "*"}[];
185
+ }
186
+
187
+ export function moduleExports(cu: JS.CompilationUnit): ModuleExports {
188
+ const locals = new Map<string, string>();
189
+ const reExports: {module: string, names: ReadonlyMap<string, string> | "*"}[] = [];
190
+ for (const {element} of cu.statements) {
191
+ if (element.kind === J.Kind.VariableDeclarations && (element as J.VariableDeclarations).modifiers.some(m => m.keyword === "export")) {
192
+ for (const {element: variable} of (element as J.VariableDeclarations).variables) {
193
+ if (isIdentifier(variable.name)) locals.set(variable.name.simpleName, variable.name.simpleName);
194
+ }
195
+ } else if (element.kind === J.Kind.MethodDeclaration || element.kind === J.Kind.ClassDeclaration) {
196
+ const declaration = element as J.MethodDeclaration | J.ClassDeclaration;
197
+ const keywords = declaration.modifiers.map(modifier => modifier.keyword);
198
+ if (keywords.includes("export")) locals.set(keywords.includes("default") ? "default" : declaration.name.simpleName, declaration.name.simpleName);
199
+ } else if (element.kind === JS.Kind.ExportAssignment) {
200
+ const value = (element as JS.ExportAssignment).expression.element;
201
+ if (isIdentifier(value) && !(element as JS.ExportAssignment).exportEquals) locals.set("default", value.simpleName);
202
+ } else if (element.kind === JS.Kind.ExportDeclaration) {
203
+ const {exportClause, moduleSpecifier, typeOnly} = element as JS.ExportDeclaration;
204
+ if (typeOnly.element) continue;
205
+ const specifier = moduleSpecifier?.element;
206
+ if (!specifier) {
207
+ if (exportClause?.kind === JS.Kind.NamedExports) exportedNames(exportClause as JS.NamedExports).forEach((local, exported) => locals.set(exported, local));
208
+ } else if (specifier.kind === J.Kind.Literal) {
209
+ const module = moduleNameOf(specifier as J.Literal);
210
+ if (exportClause?.kind === JS.Kind.NamedExports) reExports.push({module, names: exportedNames(exportClause as JS.NamedExports)});
211
+ // `export * as name from` binds a namespace, not the module's names
212
+ else if (exportClause?.kind !== JS.Kind.Alias) reExports.push({module, names: "*"});
213
+ }
214
+ }
215
+ }
216
+ return {locals, reExports};
217
+ }
218
+
219
+ /** The directory of a `jsconfig.json` or `tsconfig.json`, as a prefix of the paths of the sources below it. */
220
+ export function configDirectory(sourcePath: string): string | undefined {
221
+ const match = /^(.*\/)?(?:jsconfig|tsconfig)\.json$/.exec(sourcePath);
222
+ return match ? match[1] ?? "" : undefined;
223
+ }
224
+
225
+ /**
226
+ * The `paths` of a `jsconfig.json` or `tsconfig.json` at `sourcePath`, which may have comments and trailing commas, with
227
+ * targets resolving from its `baseUrl`, or from its directory without one. No `paths` where it `extends` another config and
228
+ * has no `paths` and `baseUrl` of its own, since the other one's, which this doesn't read, may set either.
229
+ */
230
+ export function pathsConfig(sourcePath: string, text: string): PathsConfig | undefined {
231
+ const directory = configDirectory(sourcePath);
232
+ if (directory === undefined) return undefined;
233
+ let config: any;
234
+ try {
235
+ config = JSON.parse(withoutComments(text).replace(/,(\s*[}\]])/g, "$1"));
236
+ } catch {
237
+ return undefined;
238
+ }
239
+ const options = config?.compilerOptions;
240
+ if (typeof options?.paths !== "object" || options.paths === null || config.extends !== undefined && typeof options.baseUrl !== "string") return {base: directory, paths: []};
241
+ const base = posix.normalize(posix.join(directory || ".", typeof options.baseUrl === "string" ? options.baseUrl : "."));
242
+ const paths = Object.entries(options.paths)
243
+ .filter((entry): entry is [string, string[]] => Array.isArray(entry[1]) && entry[1].every(target => typeof target === "string"));
244
+ return {base: base === "." ? "" : base, paths};
245
+ }
246
+
247
+ /** Each directory's `paths`, keyed as {@link configDirectory} gives them. */
248
+ export type PathsConfigs = Map<string, PathsConfig & {typescript: boolean}>;
249
+
250
+ /** Adds the `paths` of `doc` to `configs` where it is a `jsconfig.json` or `tsconfig.json`. */
251
+ export async function addPathsConfig(configs: PathsConfigs, doc: Json.Document): Promise<void> {
252
+ const directory = configDirectory(doc.sourcePath);
253
+ if (directory === undefined) return;
254
+ const config = pathsConfig(doc.sourcePath, await TreePrinters.print(doc));
255
+ const typescript = doc.sourcePath.endsWith("tsconfig.json");
256
+ // As bundlers read them, a directory's `tsconfig.json` is its config, and its `jsconfig.json` only without one
257
+ if (config && (typescript || !configs.get(directory)?.typescript)) configs.set(directory, {...config, typescript});
258
+ }
259
+
260
+ /** JSON text without the `//` and `/* *\/` comments outside its strings. */
261
+ function withoutComments(text: string): string {
262
+ let out = "";
263
+ for (let i = 0; i < text.length; i++) {
264
+ const c = text[i];
265
+ if (c === '"') {
266
+ const end = /"((?:[^"\\]|\\.)*)"/y;
267
+ end.lastIndex = i;
268
+ const string = end.exec(text);
269
+ if (!string) return out + text.slice(i);
270
+ out += string[0];
271
+ i += string[0].length - 1;
272
+ } else if (c === "/" && text[i + 1] === "/") {
273
+ while (i < text.length && text[i] !== "\n") i++;
274
+ out += "\n";
275
+ } else if (c === "/" && text[i + 1] === "*") {
276
+ const close = text.indexOf("*/", i + 2);
277
+ i = close < 0 ? text.length : close + 1;
278
+ } else {
279
+ out += c;
280
+ }
281
+ }
282
+ return out;
283
+ }
@@ -0,0 +1,2 @@
1
+ /** Test, mock and story sources, which hold fixtures rather than application code. */
2
+ export const TEST_SOURCE = /(^|\/)(__tests__|__mocks__|tests?|stories)\/|\.(test|spec|stories)\.[jt]sx?$/i;
@@ -0,0 +1,131 @@
1
+ import {ExecutionContext, TreePrinters} from "@openrewrite/rewrite";
2
+ import {J, isIdentifier} from "@openrewrite/rewrite/java";
3
+ import {JavaScriptParser, JS, namesReferencedWithin} from "@openrewrite/rewrite/javascript";
4
+ import {importBindings} from "../util/module-imports";
5
+ import {storeFunctions} from "./redux-stores";
6
+
7
+ /** The module, beside the source that creates a store it doesn't export, that the store moves to. */
8
+ export const ENTRY_STORE_MODULE = "appStore";
9
+
10
+ /** A source that creates a store it doesn't export, split into the module the store moves to and what the source keeps. */
11
+ export interface EntrySplit {
12
+ /** The source as it is once the store has moved, importing it back. */
13
+ readonly entry: JS.CompilationUnit;
14
+ /** The new module: the store, exported, with the declarations and imports that only it uses. */
15
+ readonly module: JS.CompilationUnit;
16
+ }
17
+
18
+ /**
19
+ * Splits `cu`, which creates the store `name` in a top-level `const` or `let` it doesn't export, so that the store
20
+ * moves to `modulePath` with the top-level declarations and imports that only it uses, and `cu` imports it back from
21
+ * there. Undefined where the store isn't declared so, or where what moves is used by what stays.
22
+ */
23
+ export async function splitEntryStore(cu: JS.CompilationUnit, name: string, modulePath: string, ctx: ExecutionContext): Promise<EntrySplit | undefined> {
24
+ const statements = cu.statements.map(s => s.element);
25
+ const functions = storeFunctions(cu);
26
+ const index = statements.findIndex(statement => {
27
+ if (statement.kind !== J.Kind.VariableDeclarations) return false;
28
+ const declarations = statement as J.VariableDeclarations;
29
+ const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
30
+ const call = variable?.initializer?.element;
31
+ return !!variable && isIdentifier(variable.name) && variable.name.simpleName === name &&
32
+ !declarations.modifiers.some(m => m.keyword === "export") && call?.kind === J.Kind.MethodInvocation &&
33
+ !(call as J.MethodInvocation).select && (functions.legacy.has((call as J.MethodInvocation).name.simpleName) || functions.configure.has((call as J.MethodInvocation).name.simpleName));
34
+ });
35
+ if (index < 0) return undefined;
36
+ // What each top-level statement declares: its variables, or the local names of its imports
37
+ const declared = statements.map((statement, i) => {
38
+ if (statement.kind === JS.Kind.Import) return new Set(importBindings({...cu, statements: [cu.statements[i]]}).map(b => b.local));
39
+ if (statement.kind === J.Kind.VariableDeclarations) {
40
+ const variables = (statement as J.VariableDeclarations).variables.map(v => v.element.name);
41
+ return variables.every(isIdentifier) ? new Set(variables.map(v => (v as J.Identifier).simpleName)) : undefined;
42
+ }
43
+ if (statement.kind === J.Kind.MethodDeclaration) return new Set([(statement as J.MethodDeclaration).name.simpleName]);
44
+ if (statement.kind === J.Kind.ClassDeclaration) return new Set([(statement as J.ClassDeclaration).name.simpleName]);
45
+ return new Set<string>();
46
+ });
47
+ // The store's declaration, and the declarations and imports of the names it refers to, and of those they refer to
48
+ const moved = new Set([index]);
49
+ const pending = [index];
50
+ while (pending.length > 0) {
51
+ const referenced = namesReferencedWithin(statements[pending.pop()!]);
52
+ for (let i = 0; i < statements.length; i++) {
53
+ if (moved.has(i) || ![...referenced].some(n => declared[i]?.has(n))) continue;
54
+ // A function or class moves with what it may close over, which the store's source doesn't say
55
+ if (declared[i] === undefined || statements[i].kind !== JS.Kind.Import && statements[i].kind !== J.Kind.VariableDeclarations) return undefined;
56
+ moved.add(i);
57
+ pending.push(i);
58
+ }
59
+ }
60
+ // What stays may refer to the store, which it imports back, and to nothing else that moves
61
+ const movedNames = new Set([...moved].flatMap(i => [...declared[i]!]).filter(n => n !== name));
62
+ for (let i = 0; i < statements.length; i++) {
63
+ if (!moved.has(i) && [...namesReferencedWithin(statements[i])].some(n => movedNames.has(n))) return undefined;
64
+ }
65
+ // The source's own prefix, such as a license header, prints once, at the top of what the source keeps
66
+ const nothing = {...cu.prefix, whitespace: "", comments: []};
67
+ const printed = async (statement: J.RightPadded<J>) => await TreePrinters.print({...cu, prefix: nothing, statements: [statement], eof: {...cu.eof, whitespace: ""}} as JS.CompilationUnit);
68
+ const print = async (i: number) => await printed(cu.statements[i]);
69
+ const bare = async (i: number) => await printed({...cu.statements[i], element: {...statements[i], prefix: {...statements[i].prefix, whitespace: "", comments: []}}});
70
+ const header = await TreePrinters.print({...cu, statements: [], eof: {...cu.eof, whitespace: ""}} as JS.CompilationUnit);
71
+ // So does what comes before the first statement, where that statement moves
72
+ const lead = moved.has(0) ? (await print(0)).slice(0, (await print(0)).length - (await bare(0)).length) : "";
73
+ const order = [...moved].sort((a, b) => a - b);
74
+ let module = "";
75
+ for (const i of order) {
76
+ const text = i === 0 ? await bare(0) : await print(i);
77
+ if (i !== index) {
78
+ module += text;
79
+ continue;
80
+ }
81
+ const stripped = await bare(i);
82
+ module += text.slice(0, text.length - stripped.length) + "export " + stripped;
83
+ }
84
+ module = module.replace(/^\s+/, "") + "\n";
85
+ // The store comes back where the first import that moved was, or after the imports
86
+ const firstImport = order.find(i => statements[i].kind === JS.Kind.Import);
87
+ const lastImport = statements.reduce((last, s, i) => s.kind === JS.Kind.Import && !moved.has(i) ? i : last, -1);
88
+ const at = firstImport ?? lastImport + 1;
89
+ const quote = quoteOf(statements) ?? "'";
90
+ const imports = statements.map((_, i) => i).filter(i => statements[i].kind === JS.Kind.Import);
91
+ const semicolon = imports.length === 0 || (await print(imports[0])).trimEnd().endsWith(";");
92
+ const specifier = `./${modulePath.slice(modulePath.lastIndexOf("/") + 1).replace(/\.[^.]+$/, "")}`;
93
+ const back = `import {${name}} from ${quote}${specifier}${quote}${semicolon ? ";" : ""}`;
94
+ let entry = header + lead;
95
+ // What follows statements that moved keeps the blank lines before the first of them
96
+ let gap: string | undefined;
97
+ for (let i = 0; i < statements.length; i++) {
98
+ if (i === at) entry += (i === 0 ? "" : "\n") + back;
99
+ if (moved.has(i)) {
100
+ gap ??= statements[i].prefix.whitespace;
101
+ continue;
102
+ }
103
+ let text = await print(i);
104
+ const space = text.match(/^\s*/)![0];
105
+ if (gap !== undefined && i !== at && newlines(gap) > newlines(space)) text = gap + text.slice(space.length);
106
+ gap = undefined;
107
+ entry += text;
108
+ }
109
+ if (at >= statements.length) entry += "\n" + back;
110
+ entry += cu.eof.whitespace;
111
+ const parser = new JavaScriptParser({ctx});
112
+ const parsed = await parser.parseOne({text: entry, sourcePath: cu.sourcePath}) as JS.CompilationUnit;
113
+ const generated = await parser.parseOne({text: module, sourcePath: modulePath}) as JS.CompilationUnit;
114
+ return {
115
+ // The source stays the file it was, which the host matches by id and writes in its charset
116
+ entry: {...parsed, id: cu.id, markers: cu.markers, charsetName: cu.charsetName, charsetBomMarked: cu.charsetBomMarked, checksum: cu.checksum, fileAttributes: cu.fileAttributes},
117
+ module: {...generated, charsetName: generated.charsetName ?? cu.charsetName ?? "UTF-8", charsetBomMarked: false}
118
+ };
119
+ }
120
+
121
+ const newlines = (whitespace: string) => whitespace.split("\n").length - 1;
122
+
123
+ function quoteOf(statements: readonly J[]): "'" | '"' | undefined {
124
+ for (const element of statements) {
125
+ const specifier = element.kind === JS.Kind.Import ? (element as JS.Import).moduleSpecifier?.element : undefined;
126
+ const source = specifier?.kind === J.Kind.Literal ? (specifier as J.Literal).valueSource : undefined;
127
+ if (source?.startsWith("'")) return "'";
128
+ if (source?.startsWith('"')) return '"';
129
+ }
130
+ return undefined;
131
+ }
@@ -1,7 +1,7 @@
1
1
  import {Column, Cursor} from "@openrewrite/rewrite";
2
- import {JS, walk} from "@openrewrite/rewrite/javascript";
2
+ import {JS, namesReferencedWithin, walk} from "@openrewrite/rewrite/javascript";
3
3
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
- import {importBindings, resolveRelative} from "../util/module-imports";
4
+ import {importBindings, Resolve, resolveRelative} from "../util/module-imports";
5
5
 
6
6
  export const REDUX = "redux";
7
7
  export const RTK = "@reduxjs/toolkit";
@@ -342,12 +342,13 @@ export function localSlices(cu: JS.CompilationUnit): LocalSlices {
342
342
  }
343
343
 
344
344
  /** Resolves a reducer expression of a store to the slice it is the reducer of. */
345
- export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: LocalSlices, modules: ReadonlyMap<string, SliceModule>): SliceFacts | undefined {
345
+ export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: LocalSlices, modules: ReadonlyMap<string, SliceModule>,
346
+ resolve: Resolve = (from, specifier) => resolveRelative(from, specifier, modules)): SliceFacts | undefined {
346
347
  const inFile = reducerOf(node, local.localSlices) ?? (isIdentifier(node) ? local.localReducers.get(node.simpleName) : undefined);
347
348
  if (inFile) return inFile;
348
349
  const imported = (name: string) => {
349
350
  const binding = importBindings(cu).find(b => b.local === name);
350
- const path = binding && resolveRelative(cu.sourcePath, binding.module, modules);
351
+ const path = binding && resolve(cu.sourcePath, binding.module);
351
352
  return path ? {binding, module: modules.get(path)!} : undefined;
352
353
  };
353
354
  if (isIdentifier(node)) {
@@ -379,7 +380,7 @@ export const SUGGESTED_ACTIONS: Readonly<Record<string, string>> = {
379
380
  UNKNOWN_OPTION: "Review this `configureStore` option by hand."
380
381
  };
381
382
 
382
- export const TEST_SOURCE = /(^|\/)(__tests__|__mocks__|tests?|stories)\/|\.(test|spec|stories)\.[jt]sx?$/i;
383
+ export {TEST_SOURCE} from "../util/test-source";
383
384
 
384
385
  /** The options of `configureStore` that keep a store from converting, by the reason they are recorded under. */
385
386
  const BLOCKING_OPTIONS: Readonly<Record<string, string>> = {
@@ -389,6 +390,8 @@ const BLOCKING_OPTIONS: Readonly<Record<string, string>> = {
389
390
  export interface Finding {
390
391
  reason: string;
391
392
  detail: string;
393
+ /** What to do about this finding, where it says more than the reason's own action. */
394
+ action?: string;
392
395
  }
393
396
 
394
397
  /** The local names a source calls to create a Redux store: legacy `createStore` and Redux Toolkit's `configureStore`. */
@@ -466,6 +469,8 @@ export function legacyEnhancer(expression: J, cu: JS.CompilationUnit): LegacyEnh
466
469
  const name = ((node as JS.Spread).expression as J.Identifier).simpleName;
467
470
  const array = constant(name);
468
471
  if (array?.kind !== J.Kind.NewArray) return `middleware spread from \`${name}\``;
472
+ // An array that another statement refers to, such as one that pushes more middleware into it, may not hold only what it declares
473
+ if (cu.statements.filter(st => [...namesReferencedWithin(st.element)].includes(name)).length > 1) return `middleware spread from \`${name}\`, which is used elsewhere too`;
469
474
  for (const element of (array as J.NewArray).initializer?.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty) ?? []) {
470
475
  const why = middleware(element);
471
476
  if (why) return why;
@@ -543,7 +548,7 @@ export function preloadedValue(expression: J, cu: JS.CompilationUnit): boolean {
543
548
  * `undefined` when `call` creates no store.
544
549
  */
545
550
  export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule>,
546
- functions = storeFunctions(cu)): {api: string, findings: Finding[], slices: Map<string, SliceFacts>, reducerStore?: ReducerStoreKind} | undefined {
551
+ functions = storeFunctions(cu), resolve?: Resolve): {api: string, findings: Finding[], slices: Map<string, SliceFacts>, reducerStore?: ReducerStoreKind} | undefined {
547
552
  if (call.select) return undefined;
548
553
  const api = call.name.simpleName;
549
554
  if (functions.legacy.has(api)) {
@@ -575,7 +580,7 @@ export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit,
575
580
  if (!reducers) return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: ""}], slices, reducerStore};
576
581
  const local = localSlices(cu);
577
582
  for (const [key, value] of reducers) {
578
- const slice = resolveSliceReducer(value, cu, local, modules);
583
+ const slice = resolveSliceReducer(value, cu, local, modules, resolve);
579
584
  if (!slice) findings.push({reason: "NON_SLICE_REDUCER", detail: key});
580
585
  else if (slice.blocker) findings.push(slice.blocker);
581
586
  else slices.set(key, slice);