@openrewrite/recipes-react 0.16.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -5
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
- package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
- package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
- package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
- package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
- package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
- package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
- package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
- package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-script.js +82 -0
- package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
- package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
- package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
- package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
- package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +5 -6
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
- package/dist/migration/cra-to-vite/index.d.ts +8 -2
- package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/index.js +17 -2
- package/dist/migration/cra-to-vite/index.js.map +1 -1
- package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
- package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
- package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
- package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
- package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/shared.js +19 -4
- package/dist/migration/cra-to-vite/shared.js.map +1 -1
- package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
- package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/svg-component.js +60 -0
- package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +12 -3
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
- package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
- package/dist/react18/replace-reactdom-render.js +16 -8
- package/dist/react18/replace-reactdom-render.js.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +8 -1
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
- package/dist/react19/find-legacy-context-api.js +21 -38
- package/dist/react19/find-legacy-context-api.js.map +1 -1
- package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
- package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
- package/dist/react19/remove-unstable-batched-updates.js +295 -0
- package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
- package/dist/react19/replace-default-props.d.ts +1 -0
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +198 -151
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +10 -25
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/class-to-functional.d.ts.map +1 -1
- package/dist/refactoring/class-to-functional.js +2 -0
- package/dist/refactoring/class-to-functional.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +14 -49
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/search/find-function-component-default-props.d.ts.map +1 -1
- package/dist/search/find-function-component-default-props.js +6 -15
- package/dist/search/find-function-component-default-props.js.map +1 -1
- package/dist/search/find-redux-stores.d.ts +12 -0
- package/dist/search/find-redux-stores.d.ts.map +1 -0
- package/dist/search/find-redux-stores.js +87 -0
- package/dist/search/find-redux-stores.js.map +1 -0
- package/dist/simplify-object-pattern-property.d.ts.map +1 -1
- package/dist/simplify-object-pattern-property.js +14 -21
- package/dist/simplify-object-pattern-property.js.map +1 -1
- package/dist/simplify-react-imports.d.ts.map +1 -1
- package/dist/simplify-react-imports.js +10 -59
- package/dist/simplify-react-imports.js.map +1 -1
- package/dist/testing/enzyme-constant-strings.d.ts +12 -0
- package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
- package/dist/testing/enzyme-constant-strings.js +101 -0
- package/dist/testing/enzyme-constant-strings.js.map +1 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +5 -2
- package/dist/testing/enzyme-host-components.js.map +1 -1
- package/dist/testing/enzyme-portals.d.ts +38 -0
- package/dist/testing/enzyme-portals.d.ts.map +1 -0
- package/dist/testing/enzyme-portals.js +226 -0
- package/dist/testing/enzyme-portals.js.map +1 -0
- package/dist/testing/enzyme-selector-names.d.ts +9 -0
- package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
- package/dist/testing/enzyme-selector-names.js +50 -0
- package/dist/testing/enzyme-selector-names.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +80 -8
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +384 -40
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +27 -4
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +14 -6
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +143 -16
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +18 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -0
- package/dist/util/java-recipe-proxy.js +97 -0
- package/dist/util/java-recipe-proxy.js.map +1 -0
- package/dist/util/module-imports.d.ts +1 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +5 -1
- package/dist/util/module-imports.js.map +1 -1
- package/dist/util/reindent.d.ts +5 -0
- package/dist/util/reindent.d.ts.map +1 -0
- package/dist/util/reindent.js +44 -0
- package/dist/util/reindent.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +74 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -0
- package/dist/zustand/redux-stores.js +402 -0
- package/dist/zustand/redux-stores.js.map +1 -0
- package/dist/zustand/redux-to-zustand.d.ts +76 -0
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
- package/dist/zustand/redux-to-zustand.js +653 -0
- package/dist/zustand/redux-to-zustand.js.map +1 -0
- package/dist/zustand/zustand-plan.d.ts +96 -0
- package/dist/zustand/zustand-plan.d.ts.map +1 -0
- package/dist/zustand/zustand-plan.js +822 -0
- package/dist/zustand/zustand-plan.js.map +1 -0
- package/package.json +2 -2
- package/src/index.ts +9 -4
- package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
- package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
- package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
- package/src/migration/cra-to-vite/cra-script.ts +61 -0
- package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
- package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +5 -6
- package/src/migration/cra-to-vite/index.ts +10 -2
- package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
- package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
- package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
- package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
- package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
- package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
- package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
- package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
- package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
- package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
- package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
- package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
- package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
- package/src/migration/cra-to-vite/shared.ts +20 -10
- package/src/migration/cra-to-vite/svg-component.ts +39 -0
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +13 -6
- package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
- package/src/react18/replace-reactdom-render.ts +17 -8
- package/src/react18/replace-unmount-component-at-node.ts +13 -2
- package/src/react19/find-legacy-context-api.ts +21 -42
- package/src/react19/remove-unstable-batched-updates.ts +301 -0
- package/src/react19/replace-default-props.ts +212 -159
- package/src/react19/replace-react-shallow-renderer.ts +13 -36
- package/src/refactoring/class-to-functional.ts +3 -1
- package/src/refactoring/create-class-to-es6.ts +12 -63
- package/src/search/find-function-component-default-props.ts +8 -10
- package/src/search/find-redux-stores.ts +76 -0
- package/src/simplify-object-pattern-property.ts +22 -49
- package/src/simplify-react-imports.ts +12 -66
- package/src/testing/enzyme-constant-strings.ts +95 -0
- package/src/testing/enzyme-host-components.ts +6 -2
- package/src/testing/enzyme-portals.ts +279 -0
- package/src/testing/enzyme-selector-names.ts +59 -0
- package/src/testing/enzyme-to-react-testing-library.ts +517 -57
- package/src/testing/enzyme-usage.ts +29 -4
- package/src/testing/enzyme-wrapper-scope.ts +186 -30
- package/src/util/java-recipe-proxy.ts +94 -0
- package/src/util/module-imports.ts +6 -1
- package/src/util/reindent.ts +35 -0
- package/src/zustand/redux-stores.ts +409 -0
- package/src/zustand/redux-to-zustand.ts +657 -0
- package/src/zustand/zustand-plan.ts +843 -0
- package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
- package/dist/react18/remove-unstable-batched-updates.js +0 -170
- package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
- package/src/react18/remove-unstable-batched-updates.ts +0 -192
|
@@ -47,9 +47,8 @@ export function migrationReason(api: string): {reason: string, suggestedAction:
|
|
|
47
47
|
if (api === "shallow" || api === "dive") {
|
|
48
48
|
return {reason: "SHALLOW_RENDERING", suggestedAction: "Review child rendering and effects before replacing shallow rendering with RTL render."};
|
|
49
49
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
50
|
+
const internal = INTERNAL_STATE_ACTIONS[api];
|
|
51
|
+
if (internal) return {reason: "INTERNAL_STATE", suggestedAction: internal};
|
|
53
52
|
if (api === "simulate") {
|
|
54
53
|
return {reason: "UNSUPPORTED_EVENT", suggestedAction: "Review event payloads and async control flow before selecting user-event or fireEvent."};
|
|
55
54
|
}
|
|
@@ -65,9 +64,35 @@ export function migrationReason(api: string): {reason: string, suggestedAction:
|
|
|
65
64
|
if (api === "configure") {
|
|
66
65
|
return {reason: "ENZYME_SETUP", suggestedAction: "Keep Enzyme setup until no tests or helpers in the owning package need it."};
|
|
67
66
|
}
|
|
68
|
-
return {reason: "WRAPPER_API", suggestedAction:
|
|
67
|
+
return {reason: "WRAPPER_API", suggestedAction: WRAPPER_API_ACTIONS[api] ??
|
|
68
|
+
"Review this Enzyme wrapper API for an equivalent RTL interaction or DOM assertion."};
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
// What to write by hand for each, in RTL's terms: RTL has no component tree, so each becomes a DOM read or a user action
|
|
72
|
+
const INTERNAL_STATE_ACTIONS: Readonly<Record<string, string>> = {
|
|
73
|
+
state: "Assert what the state renders, such as text, a class, or an `aria-*` attribute, with `screen.getByText` or `getByRole`, instead of reading component state.",
|
|
74
|
+
setState: "Reach the state as a user does: fire the event that sets it with `fireEvent` or `userEvent`, or `rerender` with the props that lead to it.",
|
|
75
|
+
instance: "Trigger the method through the UI that calls it and assert the result in the DOM, or move its logic into a function and test that directly.",
|
|
76
|
+
invoke: "Fire the DOM event that calls the handler, with `fireEvent` or `userEvent`, instead of invoking the prop."
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const WRAPPER_API_ACTIONS: Readonly<Record<string, string>> = {
|
|
80
|
+
prop: "Assert what the prop produces in the DOM, such as text, an attribute, or a role. For a callback prop, fire the event that calls it and assert on a `jest.fn()`.",
|
|
81
|
+
props: "Assert what the props produce in the DOM. To check what a child component receives, mock that component with `jest.mock` and assert on the mock's calls.",
|
|
82
|
+
setProps: "Call the `rerender` that RTL's `render` returns, with the element and its new props.",
|
|
83
|
+
text: "Read `textContent` of the queried element, or find it with `screen.getByText`.",
|
|
84
|
+
html: "Assert on `container.innerHTML` or the queried element's `outerHTML`; Enzyme's `html()` of a component is its rendered markup.",
|
|
85
|
+
at: "Index the `querySelectorAll` or `getAllBy*` result; for a component selector, query the DOM element the component renders instead.",
|
|
86
|
+
first: "Take the first element of the `querySelectorAll` or `getAllBy*` result, or use `querySelector` or `getBy*` for a single match.",
|
|
87
|
+
last: "Take the last element of the `querySelectorAll` or `getAllBy*` result.",
|
|
88
|
+
children: "Read the queried element's `children`, or query its descendants with `within(element)`.",
|
|
89
|
+
exists: "Use `queryBy*` with `toBeNull()` or `not.toBeNull()`, or test the length of a `querySelectorAll`.",
|
|
90
|
+
hasClass: "Use `element.classList.contains`, or `toHaveClass` from `@testing-library/jest-dom`.",
|
|
91
|
+
getDOMNode: "Query the element directly with `screen.getBy*` or `container.querySelector`; RTL already returns DOM nodes.",
|
|
92
|
+
update: "Remove it: RTL renders the latest state on every query. Await `findBy*` or `waitFor` where the change is asynchronous.",
|
|
93
|
+
unmount: "Call the `unmount` that RTL's `render` returns, or rely on RTL's automatic cleanup after each test."
|
|
94
|
+
};
|
|
95
|
+
|
|
71
96
|
export function enclosingScope(start: Cursor): string {
|
|
72
97
|
for (let cursor = start.parent; cursor; cursor = cursor.parent) {
|
|
73
98
|
const node = cursor.value as J;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import {Cursor, ExecutionContext} from "@openrewrite/rewrite";
|
|
2
|
-
import {isObjectLiteral, JavaScriptVisitor, JS, referencesOf, walk} from "@openrewrite/rewrite/javascript";
|
|
2
|
+
import {compilationUnitOf, isObjectLiteral, JavaScriptVisitor, JS, JSX, referencesOf, walk} from "@openrewrite/rewrite/javascript";
|
|
3
3
|
import {emptySpace, Expression, isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
4
|
import {create} from "mutative";
|
|
5
5
|
import {enzymeMethod, enzymeWrapper} from "./enzyme-usage";
|
|
6
|
+
import {importBindings} from "../util/module-imports";
|
|
6
7
|
|
|
7
8
|
const HTML_TAGS = new Set(["a", "abbr", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo",
|
|
8
9
|
"blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data",
|
|
@@ -44,10 +45,10 @@ function compoundTags(value: string): (string | undefined)[] | undefined {
|
|
|
44
45
|
* descendants. Enzyme compares an attribute value strictly against the
|
|
45
46
|
* prop, while the DOM sees it stringified, so values that a number or boolean prop renders to are
|
|
46
47
|
* excluded. Enzyme additionally matches composite elements whose props satisfy a class, ID, or
|
|
47
|
-
* attribute compound
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* combinators and pseudo-classes are excluded.
|
|
48
|
+
* attribute compound. In the last compound that only adds matches, so counts can only drop, which a
|
|
49
|
+
* converted assertion shows, while positions can shift, which {@link positional} guards. In an ancestor
|
|
50
|
+
* compound it can also lose them, which {@link selectorLiteral} guards. A composite element between a
|
|
51
|
+
* parent and its child breaks a child combinator, and other combinators and pseudo-classes are excluded.
|
|
51
52
|
*/
|
|
52
53
|
export function domSelector(value: unknown): value is string {
|
|
53
54
|
if (typeof value !== "string" || value === "") return false;
|
|
@@ -60,13 +61,45 @@ function onlyStringPropsRenderTo(value: string): boolean {
|
|
|
60
61
|
return value !== "true" && value !== "false" && String(Number(value)) !== value;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
|
|
64
|
-
|
|
64
|
+
/**
|
|
65
|
+
* A selector literal {@link domSelector} accepts, whose ancestor compounds name a tag or only names that
|
|
66
|
+
* `hostNames` finds on host elements alone. A component that receives an ancestor compound's class or
|
|
67
|
+
* attribute passes it to the element it renders, as `<Button className="close">` does to its `button`:
|
|
68
|
+
* Enzyme then finds `.close button` and the DOM, where that `button` has the class itself, does not.
|
|
69
|
+
*/
|
|
70
|
+
export function selectorLiteral(node: J | undefined, hostNames: HostNames): node is J.Literal {
|
|
71
|
+
return node?.kind === J.Kind.Literal && acceptedSelector((node as J.Literal).value, hostNames);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A selector string {@link selectorLiteral} accepts, however it is written. */
|
|
75
|
+
function acceptedSelector(value: unknown, hostNames: HostNames): value is string {
|
|
76
|
+
if (!domSelector(value)) return false;
|
|
77
|
+
const names = untaggedAncestorNames(value as string);
|
|
78
|
+
return names !== undefined && (names.length === 0 || hostNames(names));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Whether only host elements carry each of the classes, IDs, and attribute values. */
|
|
82
|
+
export type HostNames = (names: readonly string[]) => boolean;
|
|
83
|
+
|
|
84
|
+
const NAME = new RegExp(String.raw`[.#](-?[_a-zA-Z][\w-]*)|\[${ATTRIBUTE}(?:="([^"\\]*)"|='([^'\\]*)')?\]`, "g");
|
|
85
|
+
|
|
86
|
+
/** The names in the ancestor compounds of a selector that name no tag, or undefined where one tests an attribute's presence. */
|
|
87
|
+
function untaggedAncestorNames(selector: string): string[] | undefined {
|
|
88
|
+
const compounds = selector.split(" ").slice(0, -1).filter(compound => !/^[a-z]/.test(compound));
|
|
89
|
+
const names: string[] = [];
|
|
90
|
+
for (const compound of compounds) {
|
|
91
|
+
for (const [, name, double, single] of compound.matchAll(NAME)) {
|
|
92
|
+
const value = name ?? double ?? single;
|
|
93
|
+
if (value === undefined) return undefined;
|
|
94
|
+
names.push(value);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return names;
|
|
65
98
|
}
|
|
66
99
|
|
|
67
100
|
/** The tag of the elements a selector matches. */
|
|
68
|
-
function selectorTag(selector:
|
|
69
|
-
const tags = compoundTags(selector
|
|
101
|
+
function selectorTag(selector: string): string | undefined {
|
|
102
|
+
const tags = compoundTags(selector);
|
|
70
103
|
return tags?.[tags.length - 1];
|
|
71
104
|
}
|
|
72
105
|
|
|
@@ -75,15 +108,27 @@ function selectorTag(selector: J.Literal): string | undefined {
|
|
|
75
108
|
* into the matches depends on: where every compound names a tag, or `hostNodes()` keeps the host
|
|
76
109
|
* elements a single compound matches.
|
|
77
110
|
*/
|
|
78
|
-
function positional(selector:
|
|
79
|
-
const tags = compoundTags(selector
|
|
111
|
+
function positional(selector: string, hostNodes: boolean): boolean {
|
|
112
|
+
const tags = compoundTags(selector)!;
|
|
80
113
|
return tags.every(tag => tag !== undefined) || (hostNodes && tags.length === 1);
|
|
81
114
|
}
|
|
82
115
|
|
|
116
|
+
/**
|
|
117
|
+
* Whether a `find(within)` from an element that `selector` matches finds only elements below it. Enzyme's
|
|
118
|
+
* `find` also tests the element it is called on, as `querySelectorAll` does not, and matches the compounds of
|
|
119
|
+
* a selector among the element and what is below it, where `querySelectorAll` matches the ancestor compounds
|
|
120
|
+
* anywhere in the document. So `within` is a single compound naming a tag other than the element's.
|
|
121
|
+
*/
|
|
122
|
+
function onlyBelow(selector: string, within: string): boolean {
|
|
123
|
+
const tag = selectorTag(selector);
|
|
124
|
+
const tags = compoundTags(within);
|
|
125
|
+
return tag !== undefined && tags?.length === 1 && tags[0] !== undefined && tags[0] !== tag;
|
|
126
|
+
}
|
|
127
|
+
|
|
83
128
|
// Enzyme's `simulate` calls the React handler directly, while `fireEvent` dispatches a DOM event that
|
|
84
129
|
// React 17 receives through its root container. A dispatched click also runs the default action, such
|
|
85
130
|
// as toggling a checkbox or following a link, so clicks on those elements stay excluded.
|
|
86
|
-
const SIMULATED_EVENTS = new Set(["click", "doubleClick", "mouseDown", "mouseUp", "mouseEnter", "mouseLeave",
|
|
131
|
+
export const SIMULATED_EVENTS: ReadonlySet<string> = new Set(["click", "doubleClick", "mouseDown", "mouseUp", "mouseEnter", "mouseLeave",
|
|
87
132
|
"mouseOver", "mouseOut", "mouseMove", "focus", "blur", "submit", "keyDown", "keyUp", "change", "touchStart",
|
|
88
133
|
"touchMove", "touchEnd", "wheel"]);
|
|
89
134
|
// Enzyme also accepts the DOM's lowercase names of these events, and `dblclick` for a double click
|
|
@@ -106,7 +151,7 @@ export function simpleChain(node: Expression): boolean {
|
|
|
106
151
|
return isIdentifier(node);
|
|
107
152
|
}
|
|
108
153
|
|
|
109
|
-
export type WrapperUse = "length" | "exists" | "positionExists" | "nodes" | "selectorText" | "html" | "text" | "hasClass" | "simulate" | "setProps";
|
|
154
|
+
export type WrapperUse = "length" | "exists" | "positionExists" | "nodes" | "selectorText" | "html" | "rootHtml" | "node" | "text" | "hasClass" | "simulate" | "setProps" | "snapshot";
|
|
110
155
|
|
|
111
156
|
/** `first` and `last` index like Enzyme's methods of the same name; a literal like `at(n)`. */
|
|
112
157
|
export type ElementIndex = J.Literal | "first" | "last";
|
|
@@ -114,14 +159,17 @@ export type ElementIndex = J.Literal | "first" | "last";
|
|
|
114
159
|
export interface WrapperRead {
|
|
115
160
|
use: WrapperUse;
|
|
116
161
|
wrapper: J.Identifier;
|
|
117
|
-
selector
|
|
162
|
+
/** The selector as the test writes it, a string literal or a template of constant strings. */
|
|
163
|
+
selector?: Expression;
|
|
118
164
|
index?: ElementIndex;
|
|
119
165
|
/** A `find` within the positioned element. */
|
|
120
|
-
within?:
|
|
166
|
+
within?: Expression;
|
|
121
167
|
/** Found nodes asserted only to be truthy, which any wrapper and any node list are. */
|
|
122
168
|
vacuous?: boolean;
|
|
123
169
|
/** A read outside an assertion, which throws where nothing is found, as Enzyme's single-node methods do. */
|
|
124
170
|
unasserted?: boolean;
|
|
171
|
+
/** A root `html()` a snapshot assertion stores, where Enzyme's `null` for an empty render and RTL's `""` differ. */
|
|
172
|
+
snapshot?: boolean;
|
|
125
173
|
className?: J.Literal;
|
|
126
174
|
event?: string;
|
|
127
175
|
eventInit?: Expression;
|
|
@@ -171,6 +219,24 @@ export function mountedElement(mount: J.MethodInvocation): boolean {
|
|
|
171
219
|
return mount.arguments.elements.length === 1 && element.element.kind !== J.Kind.Empty && element.element.kind !== JS.Kind.Spread;
|
|
172
220
|
}
|
|
173
221
|
|
|
222
|
+
/**
|
|
223
|
+
* Whether the element a mount renders passes a `ref` anywhere in it. A bare mount statement keeps no wrapper, so
|
|
224
|
+
* such a test renders to take the nodes or instances the ref receives. Enzyme never unmounts them, while RTL's
|
|
225
|
+
* cleanup unmounts every render after the test, which throws where the test moved them, as a test of a library
|
|
226
|
+
* that reparents fibers does.
|
|
227
|
+
*/
|
|
228
|
+
export function passesRef(mount: J.MethodInvocation): boolean {
|
|
229
|
+
let ref = false;
|
|
230
|
+
walk(mount.arguments.elements[0].element, tree => {
|
|
231
|
+
if (tree.kind === JS.Kind.JsxAttribute) {
|
|
232
|
+
const key = (tree as JSX.Attribute).key;
|
|
233
|
+
if (isIdentifier(key) && key.simpleName === "ref") ref = true;
|
|
234
|
+
}
|
|
235
|
+
return !ref;
|
|
236
|
+
});
|
|
237
|
+
return ref;
|
|
238
|
+
}
|
|
239
|
+
|
|
174
240
|
/** The matcher a node list can take the place of found nodes for, as `expect`'s subject. */
|
|
175
241
|
function nodesMatcher(expectCursor: Cursor): "length" | "truthy" | undefined {
|
|
176
242
|
const expect = expectCursor.value as J;
|
|
@@ -229,6 +295,41 @@ function nativeEventInit(event: string, init: J | undefined): [string, Expressio
|
|
|
229
295
|
return event !== "change" && properties?.size === 1 && nativeEvent ? [...nativeEvent] : undefined;
|
|
230
296
|
}
|
|
231
297
|
|
|
298
|
+
/**
|
|
299
|
+
* `expect(wrapper.html())` with a matcher RTL's container meets as Enzyme's `html()` does: `"snapshot"` where only the
|
|
300
|
+
* container's `null` for an empty render keeps a stored snapshot, `"string"` where a non-empty string fails either way.
|
|
301
|
+
*/
|
|
302
|
+
function innerHtmlAssertion(read: Cursor, html: J): "snapshot" | "string" | undefined {
|
|
303
|
+
if (!expectArgument(read, html)) return undefined;
|
|
304
|
+
const expect = read.parentTree()!;
|
|
305
|
+
const matcherCursor = expect.parentTree();
|
|
306
|
+
const matcher = matcherCursor?.value as J | undefined;
|
|
307
|
+
if (!selectOf(matcher, expect.value) || !statement(matcherCursor!)) return undefined;
|
|
308
|
+
const args = (matcher as J.MethodInvocation).arguments.elements.filter(arg => arg.element.kind !== J.Kind.Empty).map(arg => arg.element);
|
|
309
|
+
if (call(matcher, "toMatchSnapshot")) return args.length === 0 || args.length === 1 && stringLiteral(args[0]) ? "snapshot" : undefined;
|
|
310
|
+
return (call(matcher, "toBe") || call(matcher, "toEqual") || call(matcher, "toContain")) &&
|
|
311
|
+
args.length === 1 && stringLiteral(args[0]) && (args[0] as J.Literal).value !== "" ? "string" : undefined;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** `expect(() => wrapper.unmount()).not.toThrow();`, which unmounts where it stands, as the statement `wrapper.unmount();` does. */
|
|
315
|
+
function unmountsWithoutThrowing(unmount: Cursor): boolean {
|
|
316
|
+
const lambdaCursor = unmount.parentTree();
|
|
317
|
+
const lambda = lambdaCursor?.value as J.Lambda | undefined;
|
|
318
|
+
if (lambda?.kind !== J.Kind.Lambda || lambda.body !== unmount.value ||
|
|
319
|
+
lambda.parameters.parameters.some(parameter => parameter.element.kind !== J.Kind.Empty)) return false;
|
|
320
|
+
const arrowCursor = lambdaCursor!.parentTree();
|
|
321
|
+
const arrow = arrowCursor?.value as JS.ArrowFunction | undefined;
|
|
322
|
+
if (arrow?.kind !== JS.Kind.ArrowFunction || arrow.lambda !== lambda || !expectArgument(arrowCursor!, arrow)) return false;
|
|
323
|
+
const expectCursor = arrowCursor!.parentTree()!;
|
|
324
|
+
const not = expectCursor.parentTree()?.value as J | undefined;
|
|
325
|
+
if (not?.kind !== J.Kind.FieldAccess || (not as J.FieldAccess).target !== expectCursor.value ||
|
|
326
|
+
(not as J.FieldAccess).name.element.simpleName !== "not") return false;
|
|
327
|
+
const matcherCursor = expectCursor.parentTree()!.parentTree();
|
|
328
|
+
const matcher = matcherCursor?.value as J | undefined;
|
|
329
|
+
return call(matcher, "toThrow") && (matcher as J.MethodInvocation).select?.element === not &&
|
|
330
|
+
noArguments(matcher as J.MethodInvocation) && statement(matcherCursor!) !== undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
232
333
|
function expectArgument(cursor: Cursor, node: J): boolean {
|
|
233
334
|
const parent = cursor.parentTree()?.value as J | undefined;
|
|
234
335
|
if (!call(parent, "expect")) return false;
|
|
@@ -265,17 +366,29 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
|
|
|
265
366
|
/**
|
|
266
367
|
* Proves that every reference to a block-scoped wrapper is a supported DOM read, so the
|
|
267
368
|
* declaration and all its uses can be converted together. Any other reference, including
|
|
268
|
-
* arguments, returns, and shorthand properties, rejects the whole scope. `
|
|
269
|
-
*
|
|
369
|
+
* arguments, returns, and shorthand properties, rejects the whole scope. `optionalChaining` says whether the test's
|
|
370
|
+
* toolchain parses `?.` and `??`, without which a find within a positioned element is not converted. `events` are those `simulate`
|
|
371
|
+
* may dispatch, and `html` admits `html()` and the DOM node of a host element, none of which a shallow wrapper reads as the DOM does. `snapshots`
|
|
372
|
+
* admits `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()`, whose
|
|
373
|
+
* snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
|
|
270
374
|
*/
|
|
271
375
|
export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
|
|
272
|
-
{events, html, untaggedPositions}: {events:
|
|
376
|
+
{events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined}): WrapperScope | undefined {
|
|
377
|
+
let serializers: ReadonlySet<string> | undefined;
|
|
273
378
|
const uses = new Map<string, WrapperRead>();
|
|
274
379
|
const removedStatements = new Set<string>();
|
|
275
380
|
const unmounts = new Set<string>();
|
|
276
381
|
let unmounted = false;
|
|
277
382
|
const variable = declaration.variables[0].element;
|
|
278
383
|
|
|
384
|
+
// The string a selector argument holds where Enzyme and the DOM read it alike, written as a literal or built from constants
|
|
385
|
+
const selectorValue = (node: J | undefined): string | undefined => {
|
|
386
|
+
if (!node) return undefined;
|
|
387
|
+
if (selectorLiteral(node, hostNames)) return node.value as string;
|
|
388
|
+
const value = node.kind === JS.Kind.TemplateExpression ? constant(node) : undefined;
|
|
389
|
+
return acceptedSelector(value, hostNames) ? value : undefined;
|
|
390
|
+
};
|
|
391
|
+
|
|
279
392
|
const record = (node: Expression, read: WrapperRead): boolean => {
|
|
280
393
|
if (!simpleChain(node)) return false;
|
|
281
394
|
uses.set(node.id, read);
|
|
@@ -298,12 +411,18 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
298
411
|
const ancestors: Cursor[] = [];
|
|
299
412
|
for (let c: Cursor | undefined = reference.parentTree(); c && ancestors.length < 5; c = c.parentTree()) ancestors.push(c);
|
|
300
413
|
const first = ancestors[0]?.value as J | undefined;
|
|
414
|
+
if (snapshots) {
|
|
415
|
+
serializers ??= snapshotSerializers(block);
|
|
416
|
+
const assertion = snapshotAssertion(identifier, ancestors, serializers);
|
|
417
|
+
if (assertion) return record(assertion, {wrapper: identifier, use: "snapshot"});
|
|
418
|
+
}
|
|
301
419
|
if (!selectOf(first, identifier)) return false;
|
|
302
420
|
const method = first as J.MethodInvocation;
|
|
303
421
|
if (call(method, "find")) {
|
|
304
422
|
const args = method.arguments.elements;
|
|
305
|
-
|
|
306
|
-
|
|
423
|
+
const selectorText = args.length === 1 ? selectorValue(args[0].element) : undefined;
|
|
424
|
+
if (selectorText === undefined) return false;
|
|
425
|
+
const selector = args[0].element as Expression;
|
|
307
426
|
let k = 1;
|
|
308
427
|
let inner: J = method;
|
|
309
428
|
let hostNodes = false;
|
|
@@ -312,15 +431,17 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
312
431
|
hostNodes = true;
|
|
313
432
|
}
|
|
314
433
|
const index = elementIndex(ancestors[k]?.value, inner);
|
|
315
|
-
let within:
|
|
434
|
+
let within: Expression | undefined;
|
|
316
435
|
if (index) {
|
|
317
|
-
if (!untaggedPositions && !positional(
|
|
436
|
+
if (!untaggedPositions && !positional(selectorText, hostNodes)) return false;
|
|
318
437
|
inner = ancestors[k++].value;
|
|
319
438
|
const nested = ancestors[k]?.value as J | undefined;
|
|
320
439
|
if (call(nested, "find") && selectOf(nested, inner)) {
|
|
440
|
+
if (!optionalChaining) return false;
|
|
321
441
|
const [argument] = (nested as J.MethodInvocation).arguments.elements;
|
|
322
|
-
|
|
323
|
-
|
|
442
|
+
const withinText = (nested as J.MethodInvocation).arguments.elements.length === 1 ? selectorValue(argument.element) : undefined;
|
|
443
|
+
if (withinText === undefined || !onlyBelow(selectorText, withinText)) return false;
|
|
444
|
+
within = argument.element as Expression;
|
|
324
445
|
inner = ancestors[k++].value;
|
|
325
446
|
}
|
|
326
447
|
}
|
|
@@ -340,6 +461,10 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
340
461
|
const terminalArgs = terminal.arguments.elements.filter(arg => arg.element.kind !== J.Kind.Empty).map(arg => arg.element);
|
|
341
462
|
if (call(terminal, "exists") && terminalArgs.length === 0) return record(terminal, {...read, use: !index || within ? "exists" : "positionExists"});
|
|
342
463
|
if (within) return false;
|
|
464
|
+
// A mounted host element's instance is its DOM node, as is the node `getDOMNode` returns; a shallow one has neither
|
|
465
|
+
if (html && (call(terminal, "instance") || call(terminal, "getDOMNode")) && terminalArgs.length === 0 && positional(selectorText, hostNodes)) {
|
|
466
|
+
return record(terminal, {...read, use: "node"});
|
|
467
|
+
}
|
|
343
468
|
if ((call(terminal, "text") || html && call(terminal, "html")) && terminalArgs.length === 0) {
|
|
344
469
|
return record(terminal, {...read, use: call(terminal, "text") ? "selectorText" : "html",
|
|
345
470
|
unasserted: !expectArgument(outerCursor, terminal)});
|
|
@@ -348,33 +473,35 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
348
473
|
/^-?[_a-zA-Z][\w-]*$/.test(terminalArgs[0].value as string)) {
|
|
349
474
|
return record(terminal, {...read, use: "hasClass", className: terminalArgs[0]});
|
|
350
475
|
}
|
|
351
|
-
if (call(terminal, "simulate") && events && statement(outerCursor) && terminalArgs.length >= 1 && terminalArgs.length <= 2 &&
|
|
476
|
+
if (call(terminal, "simulate") && events.size > 0 && statement(outerCursor) && terminalArgs.length >= 1 && terminalArgs.length <= 2 &&
|
|
352
477
|
stringLiteral(terminalArgs[0])) {
|
|
353
478
|
const name = terminalArgs[0].value as string;
|
|
354
479
|
const event = SIMULATED_EVENTS.has(name) ? name : NATIVE_EVENT_NAMES.get(name);
|
|
355
|
-
if (!event) return false;
|
|
480
|
+
if (!event || !events.has(event)) return false;
|
|
356
481
|
const nativeEvent = nativeEventInit(event, terminalArgs[1]);
|
|
357
482
|
if (!nativeEvent && !eventInit(event, terminalArgs[1])) return false;
|
|
358
|
-
if (event === "click" && CLICK_DEFAULT_ACTIONS.has(selectorTag(
|
|
483
|
+
if (event === "click" && CLICK_DEFAULT_ACTIONS.has(selectorTag(selectorText) ?? "")) return false;
|
|
359
484
|
return record(terminal, {...read, use: "simulate", event, ...nativeEvent ? {nativeEvent} : {eventInit: terminalArgs[1]}});
|
|
360
485
|
}
|
|
361
486
|
return false;
|
|
362
487
|
}
|
|
363
488
|
const [argument] = method.arguments.elements;
|
|
364
|
-
if (call(method, "exists") && method.arguments.elements.length === 1 &&
|
|
365
|
-
return record(method, {wrapper: identifier, selector: argument.element, use: "exists"});
|
|
489
|
+
if (call(method, "exists") && method.arguments.elements.length === 1 && selectorValue(argument.element) !== undefined) {
|
|
490
|
+
return record(method, {wrapper: identifier, selector: argument.element as Expression, use: "exists"});
|
|
366
491
|
}
|
|
367
492
|
if (call(method, "setProps") && method.arguments.elements.length === 1 && statement(ancestors[0]) &&
|
|
368
493
|
argument.element.kind !== J.Kind.Empty && argument.element.kind !== JS.Kind.Spread) {
|
|
369
494
|
return record(method, {wrapper: identifier, use: "setProps", props: argument.element as Expression});
|
|
370
495
|
}
|
|
371
496
|
if (!noArguments(method)) return false;
|
|
497
|
+
const htmlAssertion = html && call(method, "html") ? innerHtmlAssertion(ancestors[0], method) : undefined;
|
|
498
|
+
if (htmlAssertion) return record(method, {wrapper: identifier, use: "rootHtml", snapshot: htmlAssertion === "snapshot"});
|
|
372
499
|
if (call(method, "text")) return record(method, {wrapper: identifier, use: "text", unasserted: !expectArgument(ancestors[0], method)});
|
|
373
500
|
if (call(method, "update") && statement(ancestors[0])?.prefix.comments.length === 0 && method.prefix.comments.length === 0) {
|
|
374
501
|
removedStatements.add(method.id);
|
|
375
502
|
return simpleChain(method);
|
|
376
503
|
}
|
|
377
|
-
if (call(method, "unmount") && statement(ancestors[0])) {
|
|
504
|
+
if (call(method, "unmount") && (statement(ancestors[0]) || unmountsWithoutThrowing(ancestors[0]))) {
|
|
378
505
|
unmounted = true;
|
|
379
506
|
unmounts.add(method.id);
|
|
380
507
|
return simpleChain(method);
|
|
@@ -392,6 +519,35 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
392
519
|
return {declaration, name, uses, removedStatements, unmounts};
|
|
393
520
|
}
|
|
394
521
|
|
|
522
|
+
/** The local names a source binds to `enzyme-to-json`'s serializers, such as its default export `toJson`. */
|
|
523
|
+
function snapshotSerializers(cursor: Cursor): ReadonlySet<string> {
|
|
524
|
+
const cu = compilationUnitOf(cursor);
|
|
525
|
+
return new Set(cu ? importBindings(cu).filter(({module}) => module === "enzyme-to-json").map(({local}) => local) : []);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* The `expect(wrapper)` or `expect(toJson(wrapper))` call of a `toMatchSnapshot()` assertion of the
|
|
530
|
+
* wrapper, with no property matcher and at most a snapshot name.
|
|
531
|
+
*/
|
|
532
|
+
function snapshotAssertion(identifier: J.Identifier, ancestors: Cursor[], serializers: ReadonlySet<string>): J.MethodInvocation | undefined {
|
|
533
|
+
let k = 0;
|
|
534
|
+
const onlyArgument = (call: J | undefined, argument: J) => call?.kind === J.Kind.MethodInvocation && !(call as J.MethodInvocation).select &&
|
|
535
|
+
(call as J.MethodInvocation).arguments.elements.length === 1 && (call as J.MethodInvocation).arguments.elements[0].element === argument;
|
|
536
|
+
let subject: J = identifier;
|
|
537
|
+
const serialized = ancestors[k]?.value as J | undefined;
|
|
538
|
+
if (onlyArgument(serialized, subject) && serializers.has((serialized as J.MethodInvocation).name.simpleName)) {
|
|
539
|
+
subject = serialized!;
|
|
540
|
+
k++;
|
|
541
|
+
}
|
|
542
|
+
const expectCall = ancestors[k]?.value as J | undefined;
|
|
543
|
+
if (!onlyArgument(expectCall, subject) || (expectCall as J.MethodInvocation).name.simpleName !== "expect") return undefined;
|
|
544
|
+
const matcher = ancestors[k + 1]?.value as J | undefined;
|
|
545
|
+
if (!call(matcher, "toMatchSnapshot") || !selectOf(matcher, expectCall!) || !statement(ancestors[k + 1])) return undefined;
|
|
546
|
+
const args = (matcher as J.MethodInvocation).arguments.elements.filter(arg => arg.element.kind !== J.Kind.Empty);
|
|
547
|
+
if (args.length > 1 || (args.length === 1 && !stringLiteral(args[0].element))) return undefined;
|
|
548
|
+
return expectCall as J.MethodInvocation;
|
|
549
|
+
}
|
|
550
|
+
|
|
395
551
|
/** The call a chain of calls and field accesses starts with, such as `mount(...)` in `mount(...).find(...).length`. */
|
|
396
552
|
export function innermostCall(node: J): J.MethodInvocation | undefined {
|
|
397
553
|
let call: J.MethodInvocation | undefined;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import {check, Cursor, ExecutionContext, or, RecipeRef, ScanningRecipe, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {DelegatingRecipe} from "@openrewrite/rewrite/rpc";
|
|
3
|
+
|
|
4
|
+
/** The host's own tree-type gate, the one it derives for a JsonVisitor or JavaScriptVisitor. */
|
|
5
|
+
export const treesOfType = (type: string) => new RecipeRef("org.openrewrite.rpc.internal.FindTreesOfType", {type});
|
|
6
|
+
|
|
7
|
+
// The files the dependency delegates normally send to Java.
|
|
8
|
+
const NODE_MANIFESTS = /(^|\/)(package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|pnpm-workspace\.yaml|bun\.lock)$/;
|
|
9
|
+
const NODE_MANIFEST_TREES = ["org.openrewrite.json.tree.Json", "org.openrewrite.yaml.tree.Yaml", "org.openrewrite.text.PlainText"];
|
|
10
|
+
|
|
11
|
+
// Native lock transactions also need package-manager policy, patches and hooks they must refuse.
|
|
12
|
+
const NODE_INPUTS = /(^|\/)(\.npmrc|\.yarnrc(?:\.yml)?|bunfig\.toml|\.?pnpmfile\.cjs)$|\.patch$/;
|
|
13
|
+
|
|
14
|
+
const manifestTrees = () => or(...NODE_MANIFEST_TREES.map(treesOfType));
|
|
15
|
+
|
|
16
|
+
export function isNodeDependencyInput(path: string, includeInputs = false): boolean {
|
|
17
|
+
return NODE_MANIFESTS.test(path) || includeInputs && NODE_INPUTS.test(path);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Runs a Java npm dependency recipe through this side's RPC connection rather than as a stand-in the host
|
|
22
|
+
* builds itself, so the host prepares it from its class with every option.
|
|
23
|
+
*/
|
|
24
|
+
export abstract class JavaDependencyRecipe extends ScanningRecipe<number> {
|
|
25
|
+
// HACK: not a `DelegatingRecipe` itself, which the host would build from its marketplace listing. A listing
|
|
26
|
+
// older than the recipe drops the options it does not name: Moderne's lists rewrite-javascript 8.94's
|
|
27
|
+
// `AddDependency`, without `onlyIfDeclaring` and `onlyIfResolving`.
|
|
28
|
+
// An ordinary field: `PrepareRecipe` copies a recipe whose scanner it gates, and a copy has no `#private` field
|
|
29
|
+
protected readonly java: DelegatingRecipe;
|
|
30
|
+
|
|
31
|
+
protected constructor(javaRecipeName: string, options: object, private readonly includePackageManagerInputs = false) {
|
|
32
|
+
super();
|
|
33
|
+
this.java = new DelegatingRecipe(javaRecipeName, {...options});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
initialValue(): number {
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async scanner(acc: number): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
41
|
+
return manifestsOnly(async () => this.java.scanner(acc), manifest => this.scanned(manifest), this.includePackageManagerInputs);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Called with each manifest as it is scanned; one it returns false for is kept from the Java recipe, which then edits nothing for it. */
|
|
45
|
+
protected scanned(_manifest: SourceFile): boolean {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Whether the Java recipe's edit of this manifest or lockfile is applied; one it returns false for is left as it was. */
|
|
50
|
+
protected edits(_manifest: SourceFile): boolean {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
|
|
55
|
+
// host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
|
|
56
|
+
override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
57
|
+
return this.includePackageManagerInputs ? super.editor() : check(manifestTrees(), super.editor());
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async editorWithData(acc: number): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
61
|
+
return manifestsOnly(async () => this.java.editorWithData(acc), manifest => this.edits(manifest), this.includePackageManagerInputs);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
65
|
+
return this.java.generate(acc, ctx);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async onComplete(ctx: ExecutionContext): Promise<void> {
|
|
69
|
+
await this.java.onComplete(ctx);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The remote visitor is prepared on first use, since the host prepares this recipe's visitors before a run
|
|
74
|
+
async function manifestsOnly(remote: () => Promise<TreeVisitor<any, ExecutionContext>>, admit?: (manifest: SourceFile) => boolean, includeInputs = false): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
75
|
+
const accepts = (path: string) => isNodeDependencyInput(path, includeInputs);
|
|
76
|
+
let visitor: Promise<TreeVisitor<any, ExecutionContext>> | undefined;
|
|
77
|
+
const manifests = new class extends TreeVisitor<any, ExecutionContext> {
|
|
78
|
+
override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
|
|
79
|
+
return accepts(sourceFile.sourcePath);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
83
|
+
if (!accepts((tree as SourceFile).sourcePath ?? "")) return tree as R;
|
|
84
|
+
if (admit && !admit(tree as SourceFile)) return tree as R;
|
|
85
|
+
visitor ??= remote();
|
|
86
|
+
return await (await visitor).visit<R>(tree, ctx, parent);
|
|
87
|
+
}
|
|
88
|
+
}();
|
|
89
|
+
// HACK: the host infers which trees to send only from a typed visitor, and sends a plain TreeVisitor every
|
|
90
|
+
// tree, so this names the types for it. It reads the gate of a scanner only (openrewrite/rewrite#9734).
|
|
91
|
+
// Config and hook files can have any parser type; a plain visitor avoids requiring optional Java parser modules.
|
|
92
|
+
if (includeInputs) return manifests;
|
|
93
|
+
return await check(manifestTrees(), manifests);
|
|
94
|
+
}
|
|
@@ -47,9 +47,14 @@ export function namespaceImports(cu: JS.CompilationUnit): string[] {
|
|
|
47
47
|
// Node resolves a relative specifier to the file before the directory's index
|
|
48
48
|
const RESOLVED = ["", ".js", ".jsx", ".ts", ".tsx", "/index.js", "/index.jsx", "/index.ts", "/index.tsx"];
|
|
49
49
|
|
|
50
|
+
/** Whether a module specifier names a file by a path relative to the importing source. */
|
|
51
|
+
export function isRelativeSpecifier(specifier: string): boolean {
|
|
52
|
+
return /^\.\.?(?:\/|$)/.test(specifier);
|
|
53
|
+
}
|
|
54
|
+
|
|
50
55
|
/** The source a relative module specifier resolves to from the source at `from`, as Node resolves it among `sources`. */
|
|
51
56
|
export function resolveRelative(from: string, specifier: string, sources: {has(path: string): boolean}): string | undefined {
|
|
52
|
-
if (
|
|
57
|
+
if (!isRelativeSpecifier(specifier)) return undefined;
|
|
53
58
|
const base = posix.normalize(posix.join(posix.dirname(from), specifier));
|
|
54
59
|
return RESOLVED.map(suffix => base + suffix).find(path => sources.has(path));
|
|
55
60
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {Marker} from "@openrewrite/rewrite";
|
|
2
|
+
import {JavaScriptVisitor} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Comment, isTextComment, J, TextComment} from "@openrewrite/rewrite/java";
|
|
4
|
+
|
|
5
|
+
/** The tree with each line it spans that is indented by `from` indented by `to` instead. */
|
|
6
|
+
export async function reindent<T extends J>(tree: T, from: string, to: string): Promise<T> {
|
|
7
|
+
if (from === to) return tree;
|
|
8
|
+
const shift = (text: string) => shiftLines(text, from, to);
|
|
9
|
+
const shiftSpace = (space: J.Space): J.Space => ({
|
|
10
|
+
...space,
|
|
11
|
+
whitespace: shift(space.whitespace),
|
|
12
|
+
comments: space.comments.map(c => ({...shiftComment(c, shift), suffix: shift(c.suffix)}))
|
|
13
|
+
});
|
|
14
|
+
return await new class extends JavaScriptVisitor<void> {
|
|
15
|
+
override async visitSpace(space: J.Space, p: void): Promise<J.Space> {
|
|
16
|
+
return shiftSpace(space);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// A trailing comma keeps the whitespace after it
|
|
20
|
+
protected override async visitMarker<M extends Marker>(marker: M, p: void): Promise<M> {
|
|
21
|
+
const suffix = (marker as any).suffix;
|
|
22
|
+
return suffix?.kind === J.Kind.Space ? {...marker, suffix: shiftSpace(suffix)} : marker;
|
|
23
|
+
}
|
|
24
|
+
}().visit(tree, undefined) as T;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The text with each line after its first that is indented by `from` indented by `to` instead. */
|
|
28
|
+
export function shiftLines(text: string, from: string, to: string): string {
|
|
29
|
+
return text.split('\n').map((line, i) => i > 0 && line.startsWith(from) ? to + line.substring(from.length) : line).join('\n');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The comment with `shift` applied to the lines its text spans, as only a block comment's can. */
|
|
33
|
+
export function shiftComment(comment: Comment, shift: (text: string) => string): Comment {
|
|
34
|
+
return isTextComment(comment) && comment.multiline ? {...comment, text: shift(comment.text)} as TextComment : comment;
|
|
35
|
+
}
|