@openrewrite/recipes-react 0.16.0 → 0.17.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 (172) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/index.js +1 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
  6. package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
  7. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
  8. package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
  9. package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
  10. package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
  11. package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
  12. package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
  13. package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
  14. package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
  15. package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
  16. package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
  17. package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
  18. package/dist/migration/cra-to-vite/cra-script.js +82 -0
  19. package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
  20. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
  21. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
  22. package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
  23. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
  24. package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
  25. package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
  26. package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
  27. package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
  28. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  29. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +2 -1
  30. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  31. package/dist/migration/cra-to-vite/index.d.ts +8 -2
  32. package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
  33. package/dist/migration/cra-to-vite/index.js +17 -2
  34. package/dist/migration/cra-to-vite/index.js.map +1 -1
  35. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
  36. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
  37. package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
  38. package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
  39. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
  40. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
  41. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
  42. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
  43. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
  44. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
  45. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
  46. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
  47. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
  48. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
  49. package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
  50. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
  51. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
  52. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
  53. package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
  54. package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
  55. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
  56. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
  57. package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
  58. package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
  59. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
  60. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
  61. package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
  62. package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
  63. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
  64. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
  65. package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
  66. package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
  67. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
  68. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
  69. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
  70. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
  71. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
  72. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
  73. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  74. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
  75. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  76. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
  77. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
  78. package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
  79. package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
  80. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
  81. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
  82. package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
  83. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
  84. package/dist/migration/cra-to-vite/shared.d.ts +1 -1
  85. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  86. package/dist/migration/cra-to-vite/shared.js +19 -4
  87. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  88. package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
  89. package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
  90. package/dist/migration/cra-to-vite/svg-component.js +60 -0
  91. package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
  92. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  93. package/dist/migration/cra-to-vite/update-react-app-env-types.js +8 -2
  94. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  95. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
  96. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  97. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
  98. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  99. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  100. package/dist/react18/replace-reactdom-render.js +16 -8
  101. package/dist/react18/replace-reactdom-render.js.map +1 -1
  102. package/dist/testing/enzyme-constant-strings.d.ts +12 -0
  103. package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
  104. package/dist/testing/enzyme-constant-strings.js +101 -0
  105. package/dist/testing/enzyme-constant-strings.js.map +1 -0
  106. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  107. package/dist/testing/enzyme-host-components.js +5 -2
  108. package/dist/testing/enzyme-host-components.js.map +1 -1
  109. package/dist/testing/enzyme-portals.d.ts +38 -0
  110. package/dist/testing/enzyme-portals.d.ts.map +1 -0
  111. package/dist/testing/enzyme-portals.js +226 -0
  112. package/dist/testing/enzyme-portals.js.map +1 -0
  113. package/dist/testing/enzyme-selector-names.d.ts +9 -0
  114. package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
  115. package/dist/testing/enzyme-selector-names.js +50 -0
  116. package/dist/testing/enzyme-selector-names.js.map +1 -0
  117. package/dist/testing/enzyme-to-react-testing-library.d.ts +71 -8
  118. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  119. package/dist/testing/enzyme-to-react-testing-library.js +321 -34
  120. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  121. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  122. package/dist/testing/enzyme-usage.js +27 -4
  123. package/dist/testing/enzyme-usage.js.map +1 -1
  124. package/dist/testing/enzyme-wrapper-scope.d.ts +12 -6
  125. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  126. package/dist/testing/enzyme-wrapper-scope.js +140 -16
  127. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  128. package/dist/util/java-recipe-proxy.d.ts +16 -0
  129. package/dist/util/java-recipe-proxy.d.ts.map +1 -0
  130. package/dist/util/java-recipe-proxy.js +85 -0
  131. package/dist/util/java-recipe-proxy.js.map +1 -0
  132. package/dist/util/module-imports.d.ts +1 -0
  133. package/dist/util/module-imports.d.ts.map +1 -1
  134. package/dist/util/module-imports.js +5 -1
  135. package/dist/util/module-imports.js.map +1 -1
  136. package/package.json +2 -2
  137. package/src/index.ts +2 -1
  138. package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
  139. package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
  140. package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
  141. package/src/migration/cra-to-vite/cra-script.ts +61 -0
  142. package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
  143. package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
  144. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +2 -1
  145. package/src/migration/cra-to-vite/index.ts +10 -2
  146. package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
  147. package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
  148. package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
  149. package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
  150. package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
  151. package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
  152. package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
  153. package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
  154. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
  155. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
  156. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
  157. package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
  158. package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
  159. package/src/migration/cra-to-vite/shared.ts +20 -10
  160. package/src/migration/cra-to-vite/svg-component.ts +39 -0
  161. package/src/migration/cra-to-vite/update-react-app-env-types.ts +11 -4
  162. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
  163. package/src/react18/replace-reactdom-render.ts +17 -8
  164. package/src/testing/enzyme-constant-strings.ts +95 -0
  165. package/src/testing/enzyme-host-components.ts +6 -2
  166. package/src/testing/enzyme-portals.ts +279 -0
  167. package/src/testing/enzyme-selector-names.ts +59 -0
  168. package/src/testing/enzyme-to-react-testing-library.ts +425 -50
  169. package/src/testing/enzyme-usage.ts +29 -4
  170. package/src/testing/enzyme-wrapper-scope.ts +181 -30
  171. package/src/util/java-recipe-proxy.ts +81 -0
  172. package/src/util/module-imports.ts +6 -1
@@ -1,26 +1,203 @@
1
- import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
- import {addDependency, AddDependencyOptions, autoFormat, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
1
+ import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
3
3
  import {Expression, J} from "@openrewrite/rewrite/java";
4
4
  import {create} from "mutative";
5
5
  import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
6
6
  import {readFileSync} from "fs";
7
7
  import {dirname, join} from "path";
8
- import {satisfies, validRange} from "semver";
8
+ import {satisfies, valid, validRange} from "semver";
9
9
  import {FindEnzymeUsage} from "../search/find-enzyme-usage";
10
+ import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
11
+ import {importBindings} from "../util/module-imports";
10
12
  import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
11
13
  import {HostComponents, hostComponentExports, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
12
- import {analyzeWrapperScope, idsWithin, innermostCall, mountedElement, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead} from "./enzyme-wrapper-scope";
14
+ import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
15
+ import {evaluate, stringParts} from "./enzyme-constant-strings";
16
+ import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
17
+ import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mountedElement, passesRef, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead, WrapperUse} from "./enzyme-wrapper-scope";
13
18
 
14
19
  const RTL = "@testing-library/react";
15
20
 
16
21
  const REACT_RANGE = ">=16.9.0 <18";
17
22
 
23
+ const REACT_18_RANGE = ">=18.0.0 <19";
24
+
25
+ const resolvingReact = (range: string) => [`react@${range}`, `react-dom@${range}`];
26
+
18
27
  /** RTL 12 supports React 16.9 to 17, so it goes where Enzyme is used with those. */
19
28
  const RTL_ADDITION: AddDependencyOptions = {
20
29
  packageName: RTL, version: "^12.1.5", scope: "devDependencies",
21
- onlyIfDeclaring: ["enzyme"], onlyIfResolving: [`react@${REACT_RANGE}`, `react-dom@${REACT_RANGE}`]
30
+ onlyIfDeclaring: ["enzyme"], onlyIfResolving: resolvingReact(REACT_RANGE)
22
31
  };
23
32
 
33
+ /** RTL 16 supports React 18 with `@testing-library/dom` 10 as a peer, which a package must declare itself. */
34
+ const RTL_18_ADDITION: AddDependencyOptions = {...RTL_ADDITION, version: "^16.3.0", onlyIfResolving: resolvingReact(REACT_18_RANGE)};
35
+
36
+ const DOM = "@testing-library/dom";
37
+ const DOM_18_ADDITION: AddDependencyOptions = {...RTL_18_ADDITION, packageName: DOM, version: "^10.4.0"};
38
+
39
+ /**
40
+ * The test sources the converter would convert were RTL added to every package that may take it, which the
41
+ * dependency steps read so that they add RTL only where a source converts. The converter sets it while it
42
+ * scans. Mutated in place, as copies of a prepared recipe share it.
43
+ */
44
+ export interface ConversionForecast {
45
+ converting?: () => Promise<ReadonlySet<string>>;
46
+ }
47
+
48
+ /** The directory of a `package.json`, such as `packages/ui/`, or `""` at the repository's root. */
49
+ function packageRoot(manifestPath: string): string {
50
+ return manifestPath.slice(0, -"package.json".length);
51
+ }
52
+
53
+ /**
54
+ * Each manifest's lockfile scope: the root of the workspace it is a member of, or its own root. A package manager
55
+ * installs a workspace's members together, and `AddDependency` declines the edit for every member when one is
56
+ * kept from it, so a workspace takes RTL as a whole or not at all.
57
+ */
58
+ export function lockfileScopes(manifests: readonly Json.Document[]): Map<string, string> {
59
+ const scopes = new Map<string, string>();
60
+ for (const manifest of manifests) {
61
+ const root = packageRoot(manifest.sourcePath);
62
+ if (!scopes.has(manifest.sourcePath)) scopes.set(manifest.sourcePath, root);
63
+ // NOTE: the parser lists members from the same base as `sourcePath`, the repository's root, not the workspace's
64
+ for (const member of findNodeResolutionResult(manifest)?.workspacePackagePaths ?? []) {
65
+ scopes.set(member.replace(/^\.\//, ""), root);
66
+ }
67
+ }
68
+ return scopes;
69
+ }
70
+
71
+ /** Adds a test dependency where Enzyme tests are migrated, with its gates, as Java's `AddDependency` does. */
72
+ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
73
+ /**
74
+ * The package roots, such as `packages/ui/`, whose `package.json` declares the dependency once this run's
75
+ * edit lands, known from the end of `generate` on. Mutated in place, as copies of a prepared recipe share it.
76
+ */
77
+ readonly landed = new Set<string>();
78
+
79
+ private readonly manifests: Json.Document[] = [];
80
+
81
+ /** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
82
+ private readonly held: Json.Document[] = [];
83
+
84
+ protected constructor(private readonly addition: AddDependencyOptions, private readonly forecast: ConversionForecast) {
85
+ super("org.openrewrite.javascript.AddDependency", addition);
86
+ }
87
+
88
+ override initialValue(): number {
89
+ this.landed.clear();
90
+ this.manifests.length = 0;
91
+ this.held.length = 0;
92
+ return super.initialValue();
93
+ }
94
+
95
+ /** The package roots that would take the dependency, such as `packages/ui/`, known once the scan is done. */
96
+ candidates(): Set<string> {
97
+ return new Set(this.manifests.map(manifest => packageRoot(manifest.sourcePath)));
98
+ }
99
+
100
+ // PERF: only manifests the edit's gate admits are visited again, one RPC round trip each; a monorepo
101
+ // such as next.js holds thousands of fixture manifests
102
+ protected override scanned(manifest: SourceFile): boolean {
103
+ if (manifest.kind !== Json.Kind.Document || !/(^|\/)package\.json$/.test(manifest.sourcePath)) return true;
104
+ if (!this.admits(manifest as Json.Document)) return false;
105
+ if (this.addition.onlyIfDeclaring!.some(name => declares(manifest as Json.Document, name))) this.manifests.push(manifest as Json.Document);
106
+ this.held.push(manifest as Json.Document);
107
+ return false;
108
+ }
109
+
110
+ /** Whether the dependency may go into this `package.json`, beyond the gates `AddDependency` applies itself. */
111
+ protected admits(_manifest: Json.Document): boolean {
112
+ return true;
113
+ }
114
+
115
+ // NOTE: `AddDependency` decides each edit and regenerates the lockfile while it generates, declining a
116
+ // package whose package manager rejects the edit, such as an npm peer conflict. Its editor then returns
117
+ // that decision for a manifest, and the same one again when the run visits it.
118
+ override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
119
+ // Without a forecast, as when the step runs alone, every admitted manifest goes on as before
120
+ const converting = await this.forecast.converting?.();
121
+ const scopes = lockfileScopes(this.held);
122
+ const forwarded = new Set(this.held.filter(manifest => {
123
+ const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
124
+ return !converting || [...converting].some(source => source.startsWith(scope));
125
+ }));
126
+ const scanner = await this.java.scanner(acc);
127
+ for (const manifest of forwarded) await scanner.visit(manifest, ctx);
128
+ const kept = this.manifests.filter(manifest => forwarded.has(manifest));
129
+ this.manifests.length = 0;
130
+ this.manifests.push(...kept);
131
+ const generated = await super.generate(acc, ctx);
132
+ const editor = await this.java.editorWithData(acc);
133
+ for (const manifest of this.manifests) {
134
+ const edited = await editor.visit<Json.Document>(manifest, ctx);
135
+ if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
136
+ }
137
+ return generated;
138
+ }
139
+ }
140
+
141
+ /** Adds {@link RTL_ADDITION}. */
142
+ export class AddTestingLibraryReact extends EnzymeTestDependency {
143
+ readonly name = "org.openrewrite.react.migrate.add-testing-library-react";
144
+ readonly displayName = "Add `@testing-library/react` where Enzyme tests are migrated";
145
+ readonly description = "Adds `@testing-library/react` 12 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 16.9 to 17.";
146
+
147
+ constructor(forecast: ConversionForecast = {}) {
148
+ super(RTL_ADDITION, forecast);
149
+ }
150
+ }
151
+
152
+ /** Adds {@link RTL_18_ADDITION}. */
153
+ export class AddTestingLibraryReact18 extends EnzymeTestDependency {
154
+ readonly name = "org.openrewrite.react.migrate.add-testing-library-react-18";
155
+ readonly displayName = "Add `@testing-library/react` 16 where Enzyme tests on React 18 are migrated";
156
+ readonly description = "Adds `@testing-library/react` 16 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
157
+
158
+ constructor(forecast: ConversionForecast = {}) {
159
+ super(RTL_18_ADDITION, forecast);
160
+ }
161
+ }
162
+
163
+ /** Adds {@link DOM_18_ADDITION}, the peer of {@link RTL_18_ADDITION}. */
164
+ export class AddTestingLibraryDom18 extends EnzymeTestDependency {
165
+ readonly name = "org.openrewrite.react.migrate.add-testing-library-dom-18";
166
+ readonly displayName = "Add `@testing-library/dom` where Enzyme tests on React 18 are migrated";
167
+ readonly description = "Adds `@testing-library/dom` 10, the peer of `@testing-library/react` 16, as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
168
+
169
+ constructor(forecast: ConversionForecast = {}) {
170
+ super(DOM_18_ADDITION, forecast);
171
+ }
172
+
173
+ // NOTE: an RTL other than 16 depends on its own `@testing-library/dom`, and the converter leaves its package alone.
174
+ // Only a manifest the step would edit is kept from the Java recipe, which regenerates a workspace's lockfile from
175
+ // every member it scanned: one keeping a member back declines the edit for its siblings too.
176
+ protected override admits(manifest: Json.Document): boolean {
177
+ const rtl = declaration(manifest, RTL);
178
+ if (rtl === undefined || !declares(manifest, ENZYME) || declares(manifest, DOM)) return true;
179
+ const resolved = rtl.resolved?.version.match(/^(\d+)\./)?.[1];
180
+ if (resolved !== undefined) return Number(resolved) === 16;
181
+ const version = declaredVersion(rtl.versionConstraint);
182
+ return version !== undefined && version !== "unsupported" && version.major === 16;
183
+ }
184
+ }
185
+
186
+ /** The package roots where the run added an RTL: RTL 12, or RTL 16 where its peer `@testing-library/dom` landed too. */
187
+ export function rtlLanded(rtl: ReadonlySet<string>, rtl18: ReadonlySet<string>, dom18: ReadonlySet<string>): ReadonlySet<string> {
188
+ return new Set([...rtl, ...[...rtl18].filter(root => dom18.has(root))]);
189
+ }
190
+
191
+ function declaration(manifest: Json.Document, name: string) {
192
+ const resolution = findNodeResolutionResult(manifest);
193
+ return [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
194
+ ...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []].find(dep => dep.name === name);
195
+ }
196
+
197
+ function declares(manifest: Json.Document, name: string): boolean {
198
+ return declaration(manifest, name) !== undefined;
199
+ }
200
+
24
201
  /**
25
202
  * Older hosts drop the `onlyIfResolving` option they do not know, which would add RTL to every
26
203
  * package declaring Enzyme, so RTL is only added where the host has it.
@@ -67,6 +244,20 @@ function documentAt(cursor: Cursor): DocumentReference | undefined {
67
244
  return scope.declares("globalThis", "value") ? undefined : "globalThis.document";
68
245
  }
69
246
 
247
+ /**
248
+ * Whether a source is laid out as its Prettier config would lay it out, judged by its indentation. A
249
+ * package can declare a config, such as for its styles, while another formatter, such as ESLint, lays out
250
+ * its tests, and converted statements then keep that layout instead of Prettier's.
251
+ */
252
+ async function formattedBy(cu: JS.CompilationUnit, style: PrettierStyle): Promise<boolean> {
253
+ const detector = Autodetect.detector();
254
+ await detector.sampleJavaScript(cu);
255
+ const detected = detector.getTabsAndIndentsStyle();
256
+ const useTabs = style.config.useTabs === true;
257
+ const tabWidth = typeof style.config.tabWidth === "number" ? style.config.tabWidth : 2;
258
+ return detected.useTabCharacter === useTabs && (useTabs || detected.indentSize === tabWidth);
259
+ }
260
+
70
261
  function renderOptions(document: DocumentReference): string {
71
262
  return `{container: ${document}.createElement('div')}`;
72
263
  }
@@ -92,19 +283,43 @@ interface PackageDeclarations {
92
283
  reactDom: Declaration;
93
284
  rtl: Declaration;
94
285
  enzyme: boolean;
95
- /**
96
- * `addDependency` leaves a package unchanged when it cannot regenerate its lockfile, as for pnpm
97
- * versions it does not reproduce, so only npm and Yarn packages are counted on to receive RTL.
98
- */
99
- lockfileRegenerated: boolean;
286
+ /** The names of every package it depends on, in any dependency section. */
287
+ dependencies: ReadonlySet<string>;
288
+ /** Whether its lockfile resolves a package that puts styles into the root node of a render's container. */
289
+ rootStyles: boolean;
290
+ }
291
+
292
+ /**
293
+ * Packages whose components insert a `<style>` into the root node of the element they render, by the versions that
294
+ * do. In a detached container that root is the container itself, so its `textContent` and `innerHTML` show the
295
+ * style, while Enzyme's `text()` and `html()` read only the nodes React rendered. `@ant-design/icons` does from
296
+ * 5.1.1, for shadow DOM support, and antd 5 bundles it.
297
+ */
298
+ const ROOT_STYLES: ReadonlyMap<string, string> = new Map([["@ant-design/icons", ">=5.1.1"]]);
299
+
300
+ /** Whether the tests of a source file render components that insert styles into a detached container, as {@link ROOT_STYLES} lists. */
301
+ export function injectsRootStyles(packages: Packages, sourcePath: string): boolean {
302
+ return [...packages.entries()].some(([root, declarations]) => sourcePath.startsWith(root) && declarations.rootStyles);
100
303
  }
101
304
 
305
+ /** The reads of a whole container, which see what a component inserts into it besides what React renders. */
306
+ const CONTAINER_READS: ReadonlySet<WrapperUse> = new Set<WrapperUse>(["text", "rootHtml", "snapshot"]);
307
+
102
308
  /** Package roots, such as `packages/ui/`, mapped to their declarations. */
103
309
  type Packages = Map<string, PackageDeclarations>;
104
310
 
105
311
  interface Scanned {
106
312
  packages: Packages;
107
313
  components: HostComponents;
314
+ modules: Modules;
315
+ /** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
316
+ names: Map<string, SelectorNames>;
317
+ }
318
+
319
+ /** A dry run of the editor: the package roots it takes RTL to have, and the sources it converts. */
320
+ interface DryRun {
321
+ landed: ReadonlySet<string>;
322
+ converted: Set<string>;
108
323
  }
109
324
 
110
325
  /** The Enzyme render a converted wrapper comes from. */
@@ -114,6 +329,8 @@ type Render = "mount" | "shallow";
114
329
  interface ConvertedRender {
115
330
  document: DocumentReference;
116
331
  api: Render;
332
+ /** Whether RTL renders into its default container, attached to the document, for React 16 to receive dispatched events. */
333
+ attached: boolean;
117
334
  }
118
335
 
119
336
  /**
@@ -129,44 +346,68 @@ const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Ex
129
346
  /**
130
347
  * The React major version the tests of a source file run with, or 0 where they cannot migrate. A
131
348
  * dependency the owning package does not declare comes from the nearest enclosing package that
132
- * does, where Node resolves it from. Where the run adds RTL, as {@link RTL_ADDITION} does, it is
133
- * there for every package within the nearest package declaring Enzyme.
349
+ * does, where Node resolves it from. Where the run added RTL to the nearest package declaring
350
+ * Enzyme, one of the `landed` package roots, it is there for every package within it.
134
351
  */
135
- export function reactMajor(packages: Packages, sourcePath: string, addsRtl = false): number {
136
- return compatibility(packages, sourcePath, addsRtl).react;
352
+ export function reactMajor(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): number {
353
+ return compatibility(packages, sourcePath, landed).react;
354
+ }
355
+
356
+ /** The events `simulate` can dispatch as `fireEvent` in a source file, and whether its render must be attached to the document for them. */
357
+ export interface SimulatedEvents {
358
+ events: ReadonlySet<string>;
359
+ attached: boolean;
137
360
  }
138
361
 
362
+ // React 16 makes `onMouseEnter` and `onMouseLeave` of `mouseover` and `mouseout`, so a dispatched hover event
363
+ // runs the handlers of its pair as well, which `simulate` does not
364
+ const HOVER_EVENTS = new Set(["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"]);
365
+
139
366
  /**
140
- * Whether `simulate` can become `fireEvent` for a source file: on React 17, with an RTL whose
141
- * `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
142
- * listens to, which RTL 10 does only from 10.4.9.
367
+ * Which `simulate` calls can become `fireEvent` for a source file. On React 17, every supported event,
368
+ * with an RTL whose `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
369
+ * listens to, which RTL 10 does only from 10.4.9. On React 16.9+, which listens on the document rather than
370
+ * the root, every one but the hover events, in a render attached to the document.
143
371
  */
144
- export function simulatesEvents(packages: Packages, sourcePath: string, addsRtl = false): boolean {
145
- const {react, rtl} = compatibility(packages, sourcePath, addsRtl);
146
- return react === 17 && rtl >= 11;
372
+ export function simulatesEvents(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): SimulatedEvents {
373
+ const {react, rtl} = compatibility(packages, sourcePath, landed);
374
+ // React 18 listens on the root, as React 17 does
375
+ if (react >= 17 && rtl >= 11) return {events: SIMULATED_EVENTS, attached: false};
376
+ if (react === 16 && rtl >= 10) return {events: new Set([...SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true};
377
+ return {events: new Set(), attached: false};
147
378
  }
148
379
 
149
380
  /** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
150
- function compatibility(packages: Packages, sourcePath: string, addsRtl: boolean): {react: number, rtl: number} {
381
+ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number} {
151
382
  const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
152
383
  const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
153
384
  from.map(root => packages.get(root)![name]).find(version => version !== undefined);
154
385
  const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
155
- (version.major === 17 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
386
+ (version.major === 17 || version.major === 18 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
156
387
  const react = declared("react");
157
388
  const rtl = declared("rtl");
158
389
  const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
159
- const added = addsRtl && rtl === undefined && enzyme >= 0 && packages.get(roots[enzyme])!.lockfileRegenerated &&
160
- supportedReact(declared("react", roots.slice(enzyme))) && supportedReact(declared("reactDom", roots.slice(enzyme)));
390
+ const enzymeReact = enzyme >= 0 ? declared("react", roots.slice(enzyme)) : undefined;
391
+ const added = rtl === undefined && enzyme >= 0 && landed.has(roots[enzyme]) &&
392
+ supportedReact(enzymeReact) && supportedReact(declared("reactDom", roots.slice(enzyme)));
161
393
  // RTL renders with the React DOM it resolves from its own package
162
394
  const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root)!.rtl !== undefined);
163
395
  const reactDom = declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
164
396
  // `render` with a container, `rerender`, `unmount`, and `fireEvent` are all there since RTL 10
165
- const rtlMajor = added ? 12 : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 12 ? rtl.major : 0;
166
- const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major && rtlMajor > 0;
397
+ const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
398
+ const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
399
+ rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
167
400
  return {react: compatible ? react.major : 0, rtl: rtlMajor};
168
401
  }
169
402
 
403
+ /**
404
+ * Whether an RTL major renders with a React major as the runtime tests show: RTL 10 to 12 with React 16 and 17,
405
+ * and RTL 16 with React 18, where RTL 13 to 15 also render but are not covered.
406
+ */
407
+ function rtlSupports(rtl: number, react: number): boolean {
408
+ return react <= 17 ? rtl <= 12 : rtl === 16;
409
+ }
410
+
170
411
  /**
171
412
  * A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
172
413
  * whose minor version is known only where it is a lower bound.
@@ -205,9 +446,9 @@ function declaredVersion(version: string | undefined): Declaration {
205
446
  */
206
447
 
207
448
  export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
208
- readonly name = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
209
- readonly displayName = "Migrate Enzyme to React Testing Library";
210
- readonly description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. Converts `shallow` wrappers the same way, without `simulate` or `html()`, where the component is imported from a source in the repository that creates host elements only and runs no effects, so a full render produces the DOM the shallow render does. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, snapshots, and shallow rendering of other components are left for review.";
449
+ readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
450
+ readonly displayName: string = "Migrate Enzyme to React Testing Library";
451
+ readonly description: string = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks, on React 17 and 18 and, without the hover events and in a render attached to the document, on React 16.9+) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12 or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. Converts `shallow` wrappers the same way, without `simulate` or `html()`, where the component is imported from a source in the repository that creates host elements only and runs no effects, so a full render produces the DOM the shallow render does. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, snapshots, and shallow rendering of other components are left for review.";
211
452
 
212
453
  @Option({
213
454
  displayName: "Convert positions into untagged selector matches",
@@ -216,10 +457,22 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
216
457
  })
217
458
  untaggedSelectorPositions?: boolean;
218
459
 
460
+ // The editor reads where it added RTL, so this is the instance the run prepares as a child
461
+ private readonly forecast: ConversionForecast = {};
462
+
463
+ // PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
464
+ // their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
465
+ private readonly tests: JS.CompilationUnit[] = [];
466
+ private readonly dependencySteps = ADDS_RTL ? {rtl: new AddTestingLibraryReact(this.forecast), rtl18: new AddTestingLibraryReact18(this.forecast),
467
+ dom18: new AddTestingLibraryDom18(this.forecast)} : undefined;
468
+
219
469
  constructor(options?: {untaggedSelectorPositions?: boolean}) {
220
470
  super(options);
221
471
  }
222
472
 
473
+ /** Whether snapshot assertions of a wrapper convert, recording a new snapshot of the DOM; see {@link EnzymeSnapshotsToReactTestingLibrary}. */
474
+ protected readonly snapshots: boolean = false;
475
+
223
476
  private readonly usages = new DataTable<EnzymeUsageRow>(
224
477
  ENZYME_USAGE_TABLE, "Enzyme migration inventory",
225
478
  "Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.",
@@ -227,14 +480,23 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
227
480
  );
228
481
 
229
482
  initialValue(): Scanned {
230
- return {packages: new Map(), components: new Map()};
483
+ this.tests.length = 0;
484
+ return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map()};
231
485
  }
232
486
 
233
487
  // The host may prepare the visitors before there is an accumulator, so it is read only while visiting
234
488
  async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
489
+ const steps = this.dependencySteps;
490
+ const tests = this.tests;
491
+ let converting: Promise<ReadonlySet<string>> | undefined;
492
+ // PERF: a second pass of the editor over the sources that import Enzyme, once, for all three steps
493
+ this.forecast.converting = steps && (() => converting ??= this.dryRun(scanned, rtlLanded(steps.rtl.candidates(), steps.rtl18.candidates(), steps.dom18.candidates())));
235
494
  const sources = new class extends JavaScriptVisitor<ExecutionContext> {
236
495
  override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
237
496
  scanned.components.set(cu.sourcePath, hostComponentExports(cu));
497
+ scanned.modules.set(cu.sourcePath, moduleFacts(cu));
498
+ scanned.names.set(cu.sourcePath, selectorNames(cu));
499
+ if (importBindings(cu).some(({module}) => module === ENZYME)) tests.push(cu);
238
500
  return cu;
239
501
  }
240
502
  }();
@@ -260,22 +522,48 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
260
522
  reactDom: declaredVersion(version("react-dom")),
261
523
  rtl: declaredVersion(version(RTL)),
262
524
  enzyme: dependencies.some(dep => dep.name === "enzyme"),
263
- lockfileRegenerated: resolution?.packageManager !== "Pnpm" && resolution?.packageManager !== "Bun"
525
+ dependencies: new Set(dependencies.map(dep => dep.name)),
526
+ rootStyles: (resolution?.resolvedDependencies ?? []).some(dep => {
527
+ const range = ROOT_STYLES.get(dep.name);
528
+ return range !== undefined && valid(dep.version) !== null && satisfies(dep.version, range);
529
+ })
264
530
  });
265
531
  return doc;
266
532
  }
267
533
  }();
268
- return new class extends TreeVisitor<any, ExecutionContext> {
534
+ const scan = new class extends TreeVisitor<any, ExecutionContext> {
535
+ override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
536
+ return await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
537
+ }
538
+
269
539
  override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
270
540
  if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
271
541
  return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
272
542
  }
273
543
  }();
544
+ // HACK: the host infers which trees to send only from a JsonVisitor or JavaScriptVisitor, and sends a
545
+ // plain TreeVisitor every tree, including Python ones the TypeScript side has no codec for
546
+ return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
274
547
  }
275
548
 
276
549
  async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
550
+ return this.conversionEditor(scanned);
551
+ }
552
+
553
+ /** The sources the editor converts where RTL lands in every package root of `landed`, recording no rows. */
554
+ private async dryRun(scanned: Scanned, landed: ReadonlySet<string>): Promise<ReadonlySet<string>> {
555
+ const dry: DryRun = {landed, converted: new Set()};
556
+ const editor = await this.conversionEditor(scanned, dry);
557
+ const ctx = new ExecutionContext();
558
+ for (const cu of this.tests) await editor.visit(cu, ctx);
559
+ this.tests.length = 0;
560
+ return dry.converted;
561
+ }
562
+
563
+ private async conversionEditor(scanned: Scanned, dry?: DryRun): Promise<TreeVisitor<any, ExecutionContext>> {
277
564
  const jsx = capture<Expression>({name: "element", constraint: node => node.kind !== JS.Kind.Spread});
278
- const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node)});
565
+ const hostNames = (names: readonly string[]) => hostOnlyNames(names, scanned.names);
566
+ const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node, hostNames)});
279
567
  const after = {context: [`import {render} from "${RTL}";`], dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}};
280
568
  const patterns = (api: Render) => {
281
569
  const before = {lenientTypeMatching: false, context: [`import {${api}} from "enzyme";`], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
@@ -301,6 +589,10 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
301
589
  mount: rewrite(() => ({
302
590
  before: from.render,
303
591
  after: template`render(${jsx}, ${options})`.configure(after)
592
+ })),
593
+ attachedMount: rewrite(() => ({
594
+ before: from.render,
595
+ after: template`render(${jsx})`.configure(after)
304
596
  }))
305
597
  };
306
598
  };
@@ -309,11 +601,14 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
309
601
  "globalThis.document": {mount: renderRules("globalThis.document", "mount"), shallow: renderRules("globalThis.document", "shallow")}
310
602
  };
311
603
  const usages = this.usages;
604
+ const steps = this.dependencySteps;
312
605
  const untaggedPositions = this.untaggedSelectorPositions !== false;
606
+ const snapshots = this.snapshots;
313
607
  return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
314
608
  private enabled = false;
315
609
  private reactMajor = 0;
316
- private events = false;
610
+ private events: SimulatedEvents = {events: new Set(), attached: false};
611
+ private rootStyles = false;
317
612
  private typescript = false;
318
613
  private sourcePath = "";
319
614
  private readonly mounts = new Map<string, ConvertedRender>();
@@ -328,6 +623,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
328
623
  private readonly hoists = new Map<string, HoistedElement>();
329
624
  private readonly hoistedMounts = new Map<string, string>();
330
625
  private names: ReadonlySet<string> = new Set();
626
+ private cu?: JS.CompilationUnit;
627
+ private readonly portals = new Set<string>();
331
628
  private readonly rows: EnzymeUsageRow[] = [];
332
629
  private prettier = false;
333
630
  private printWidth = 80;
@@ -340,18 +637,34 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
340
637
  this.rows.length = 0;
341
638
  this.names = namesUsedIn(cu);
342
639
  const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
343
- this.prettier = prettierStyle !== undefined;
640
+ this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
344
641
  this.printWidth = typeof prettierStyle?.config.printWidth === "number" ? prettierStyle.config.printWidth : 80;
345
- this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, ADDS_RTL);
346
- this.events = simulatesEvents(scanned.packages, cu.sourcePath, ADDS_RTL);
642
+ const landed = dry ? dry.landed : steps ? rtlLanded(steps.rtl.landed, steps.rtl18.landed, steps.dom18.landed) : undefined;
643
+ this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, landed);
644
+ this.events = simulatesEvents(scanned.packages, cu.sourcePath, landed);
645
+ this.rootStyles = injectsRootStyles(scanned.packages, cu.sourcePath);
347
646
  this.typescript = isTypeScript(cu);
348
647
  this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
349
648
  if (!this.enabled) return cu;
350
649
  this.imports = relativeImports(cu, scanned.components);
351
650
  this.importedNames = importedNames(cu);
352
- const visited = await super.visitJsCompilationUnit(cu, ctx);
353
- this.rows.forEach(row => usages.insertRow(ctx, row));
354
- return visited;
651
+ // Templates lay out what they insert with the source's Prettier style, which a source its config does not lay out keeps out of
652
+ const foreign = prettierStyle !== undefined && !this.prettier;
653
+ const visiting = foreign ? create(cu, draft => {
654
+ draft.markers.markers = draft.markers.markers.filter(marker => marker.kind !== StyleKind.PrettierStyle);
655
+ }) : cu;
656
+ // Templates find the style through the cursor, which `visit` set to the source as it came
657
+ if (foreign) this.cursor = new Cursor(visiting, this.cursor.parent);
658
+ this.cu = cu;
659
+ this.portals.clear();
660
+ const visited = await super.visitJsCompilationUnit(visiting, ctx);
661
+ if (dry) {
662
+ if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
663
+ } else this.rows.forEach(row => usages.insertRow(ctx, row));
664
+ if (!foreign || !visited) return visited;
665
+ return visited === visiting ? cu : create(visited as JS.CompilationUnit, draft => {
666
+ draft.markers.markers.push(prettierStyle as any);
667
+ });
355
668
  }
356
669
 
357
670
  override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
@@ -362,13 +675,16 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
362
675
  if (!candidate) continue;
363
676
  const api = candidate.render;
364
677
  const reads = READS[api];
365
- const scope = analyzeWrapperScope(this.cursor, candidate, {events: this.events && reads.simulate, html: reads.html, untaggedPositions});
678
+ const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html, untaggedPositions, hostNames, snapshots,
679
+ constant: node => this.constantString(node)});
366
680
  if (!scope) continue;
367
681
  if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
368
682
  const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
369
683
  const document = documentAt(mount);
370
684
  if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
371
- this.mounts.set(candidate.mount.id, {document, api});
685
+ const attached = this.events.attached && [...scope.uses.values()].some(use => use.use === "simulate");
686
+ if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) continue;
687
+ this.mounts.set(candidate.mount.id, {document, api, attached});
372
688
  apis.push(api);
373
689
  this.declarations.add(candidate.declaration.id);
374
690
  scope.uses.forEach((use, id) => this.uses.set(id, use));
@@ -481,13 +797,13 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
481
797
  if (mounted) {
482
798
  const hoisted = this.hoistedMounts.get(method.id);
483
799
  const result = hoisted ?
484
- await this.applyTemplate(Template.builder().code(`render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
485
- await rules[mounted.document][mounted.api].mount.tryOn(this.cursor, visited, {visitor: this});
800
+ await this.applyTemplate(Template.builder().code(mounted.attached ? `render(${hoisted})` : `render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
801
+ await rules[mounted.document][mounted.api][mounted.attached ? "attachedMount" : "mount"].tryOn(this.cursor, visited, {visitor: this});
486
802
  if (!result) return visited;
487
803
  this.pending.delete(method.id);
488
804
  return withRenderOptionsOnElementLine(result, ctx);
489
805
  }
490
- const statementOf = mountedElement(visited) && statementPosition(this.cursor) ? this.renderOf(visited) : undefined;
806
+ const statementOf = mountedElement(visited) && statementPosition(this.cursor) && !passesRef(visited) ? this.renderOf(visited, false) : undefined;
491
807
  const statement = statementOf && await this.tryInline(statementOf, "mount", visited, statementOf, enclosingScope(this.cursor), "MOUNT_STATEMENT", ctx);
492
808
  if (statement) return statement;
493
809
  const existsOf = visited.name.simpleName === "exists" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
@@ -560,8 +876,15 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
560
876
  return element(false).code("?.textContent").build();
561
877
  case "html":
562
878
  return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").build();
879
+ case "rootHtml":
880
+ return code.param(read.wrapper).code(".container.innerHTML").build();
881
+ case "node":
882
+ return element(true).build();
563
883
  case "hasClass":
564
884
  return element(true).code(".classList.contains(").param(read.className!).code(")").build();
885
+ // RTL's fragment holds the rendered DOM, which Jest serializes in place of Enzyme's tree
886
+ case "snapshot":
887
+ return code.code("expect(").param(read.wrapper).code(".asFragment())").build();
565
888
  case "setProps":
566
889
  code.param(read.wrapper).code(`.rerender(${read.reassigned ? `(${read.element} = ` : ""}cloneElement(${read.element}, `);
567
890
  return code.param(read.props!).code(read.reassigned ? ")))" : "))").build().configure({
@@ -592,24 +915,63 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
592
915
  }
593
916
 
594
917
  /**
595
- * The Enzyme render a call is, where RTL's `render` renders the same DOM: any `mount`, and a
596
- * `shallow` of a component that renders host elements only, as {@link rendersHostElements} decides.
918
+ * The Enzyme render a call is, where RTL's `render` renders the same DOM: a `mount`, unless its
919
+ * wrapper is `read` and a component it renders may render into a portal, and a `shallow` of a
920
+ * component that renders host elements only, as {@link rendersHostElements} decides.
597
921
  */
598
- private renderOf(node: J | undefined): Render | undefined {
922
+ private renderOf(node: J | undefined, read = true): Render | undefined {
599
923
  if (node?.kind !== J.Kind.MethodInvocation) return undefined;
600
924
  const call = node as J.MethodInvocation;
601
925
  const api = enzymeMethod(call);
602
- if (api === "mount") return api;
926
+ if (api === "mount") return read && this.rendersPortal(call) ? undefined : api;
603
927
  const element = call.arguments.elements[0]?.element;
604
928
  return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
605
929
  }
606
930
 
931
+ /**
932
+ * Whether a component that a `mount` renders may render into a portal. Enzyme finds portal content
933
+ * in the wrapper, and RTL's container does not hold it, so a converted read would count none and
934
+ * an assertion of its absence would hold vacuously.
935
+ */
936
+ private rendersPortal(call: J.MethodInvocation): boolean {
937
+ const element = call.arguments.elements[0]?.element;
938
+ const {roots, declares, resolve} = this.moduleResolution();
939
+ const portal = !!element && !!this.cu && rendersPortal(element, this.cu, {
940
+ sourcePath: this.sourcePath,
941
+ modules: scanned.modules,
942
+ resolve,
943
+ declares,
944
+ packagePortals: () => [...scanned.modules].some(([path, facts]) => facts.portal &&
945
+ path.startsWith(roots[0] ?? "") && !/(^|\/)__tests?__\/|\.(test|spec)\.[cm]?[jt]sx?$/.test(path))
946
+ });
947
+ if (portal && !this.portals.has(call.id)) {
948
+ this.portals.add(call.id);
949
+ this.rows.push({sourcePath: this.sourcePath, scope: enclosingScope(this.cursor), api: "mount", status: "REVIEW", reason: "PORTAL",
950
+ suggestedAction: "A component it renders may render into a portal, which RTL renders outside the container: query `screen` or `baseElement` for that content."});
951
+ }
952
+ return portal;
953
+ }
954
+
955
+ /** How the test's module specifiers resolve: from the packages enclosing it, as {@link resolver} does. */
956
+ private moduleResolution() {
957
+ const roots = [...scanned.packages.keys()].filter(root => this.sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
958
+ const declares = (name: string) => roots.some(root => scanned.packages.get(root)!.dependencies.has(name));
959
+ return {roots, declares, resolve: resolver(scanned.modules, [...new Set([...roots, ""])], declares)};
960
+ }
961
+
962
+ /** The string a template of `const` strings holds, from the test or the modules it imports them from. */
963
+ private constantString(node: J): string | undefined {
964
+ const parts = stringParts(node);
965
+ return parts && evaluate(parts, this.sourcePath, scanned.modules, this.moduleResolution().resolve);
966
+ }
967
+
607
968
  private laidOutByPrettier(node: J): void {
608
969
  if (this.prettier) this.reformat.add(node.id);
609
970
  }
610
971
 
611
972
  private converted(api: string, scope: string, reason: string): void {
612
973
  maybeRemoveImport(this, ENZYME);
974
+ if (snapshots) maybeRemoveImport(this, "enzyme-to-json");
613
975
  this.rows.push({sourcePath: this.sourcePath, scope, api, status: "CONVERTED", reason,
614
976
  suggestedAction: "Run the migrated test and review whether an accessible RTL query would better express its intent."});
615
977
  }
@@ -617,6 +979,19 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
617
979
  }
618
980
 
619
981
  async recipeList() {
620
- return [...ADDS_RTL ? [await addDependency(RTL_ADDITION)] : [], new FindEnzymeUsage()];
982
+ const steps = this.dependencySteps;
983
+ return [...steps ? [steps.rtl, steps.rtl18, steps.dom18] : [], new FindEnzymeUsage()];
621
984
  }
622
985
  }
986
+
987
+ /**
988
+ * {@link EnzymeToReactTestingLibrary}, also converting snapshot assertions of the wrappers it converts. RTL
989
+ * snapshots the rendered DOM, which Enzyme's serializer records as a component tree, so every converted
990
+ * snapshot is written anew on the next run with `--updateSnapshot` and should be reviewed then.
991
+ */
992
+ export class EnzymeSnapshotsToReactTestingLibrary extends EnzymeToReactTestingLibrary {
993
+ override readonly name = "org.openrewrite.react.migrate.enzyme-snapshots-to-react-testing-library";
994
+ override readonly displayName = "Migrate Enzyme to React Testing Library, snapshots included";
995
+ override readonly description = "Migrates Enzyme wrappers as `org.openrewrite.react.migrate.enzyme-to-react-testing-library` does, and also converts `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()` of those wrappers to `expect(wrapper.asFragment()).toMatchSnapshot()`, removing the `enzyme-to-json` import where nothing else uses it. RTL snapshots the rendered DOM where Enzyme's serializer recorded a component tree, so the stored snapshots of converted tests no longer match: run the tests with `--updateSnapshot` once and review the new snapshots. Inline snapshots and snapshots of shallow renders that are not converted are left for review.";
996
+ protected override readonly snapshots: boolean = true;
997
+ }