@openrewrite/recipes-react 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -5
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +3 -5
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +5 -2
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +8 -1
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
- package/dist/react19/find-legacy-context-api.js +21 -38
- package/dist/react19/find-legacy-context-api.js.map +1 -1
- package/dist/react19/no-implicit-ref-callback-return.d.ts.map +1 -1
- package/dist/react19/no-implicit-ref-callback-return.js +25 -5
- package/dist/react19/no-implicit-ref-callback-return.js.map +1 -1
- package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
- package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
- package/dist/react19/remove-unstable-batched-updates.js +295 -0
- package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
- package/dist/react19/replace-default-props.d.ts +1 -0
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +198 -151
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +10 -25
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/class-to-functional.d.ts.map +1 -1
- package/dist/refactoring/class-to-functional.js +2 -0
- package/dist/refactoring/class-to-functional.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +14 -49
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/search/find-function-component-default-props.d.ts.map +1 -1
- package/dist/search/find-function-component-default-props.js +6 -15
- package/dist/search/find-function-component-default-props.js.map +1 -1
- package/dist/search/find-redux-stores.d.ts +12 -0
- package/dist/search/find-redux-stores.d.ts.map +1 -0
- package/dist/search/find-redux-stores.js +87 -0
- package/dist/search/find-redux-stores.js.map +1 -0
- package/dist/simplify-object-pattern-property.d.ts.map +1 -1
- package/dist/simplify-object-pattern-property.js +14 -21
- package/dist/simplify-object-pattern-property.js.map +1 -1
- package/dist/simplify-react-imports.d.ts.map +1 -1
- package/dist/simplify-react-imports.js +10 -59
- package/dist/simplify-react-imports.js.map +1 -1
- package/dist/testing/enzyme-host-components.d.ts +2 -1
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +33 -2
- package/dist/testing/enzyme-host-components.js.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +83 -24
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +4 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +36 -7
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +2 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -1
- package/dist/util/java-recipe-proxy.js +14 -2
- package/dist/util/java-recipe-proxy.js.map +1 -1
- package/dist/util/reindent.d.ts +5 -0
- package/dist/util/reindent.d.ts.map +1 -0
- package/dist/util/reindent.js +44 -0
- package/dist/util/reindent.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +74 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -0
- package/dist/zustand/redux-stores.js +439 -0
- package/dist/zustand/redux-stores.js.map +1 -0
- package/dist/zustand/redux-to-zustand.d.ts +76 -0
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
- package/dist/zustand/redux-to-zustand.js +654 -0
- package/dist/zustand/redux-to-zustand.js.map +1 -0
- package/dist/zustand/zustand-plan.d.ts +97 -0
- package/dist/zustand/zustand-plan.d.ts.map +1 -0
- package/dist/zustand/zustand-plan.js +833 -0
- package/dist/zustand/zustand-plan.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +7 -3
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +3 -5
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +3 -3
- package/src/react18/replace-unmount-component-at-node.ts +13 -2
- package/src/react19/find-legacy-context-api.ts +21 -42
- package/src/react19/no-implicit-ref-callback-return.ts +34 -8
- package/src/react19/remove-unstable-batched-updates.ts +301 -0
- package/src/react19/replace-default-props.ts +212 -159
- package/src/react19/replace-react-shallow-renderer.ts +13 -36
- package/src/refactoring/class-to-functional.ts +3 -1
- package/src/refactoring/create-class-to-es6.ts +12 -63
- package/src/search/find-function-component-default-props.ts +8 -10
- package/src/search/find-redux-stores.ts +76 -0
- package/src/simplify-object-pattern-property.ts +22 -49
- package/src/simplify-react-imports.ts +12 -66
- package/src/testing/enzyme-host-components.ts +38 -3
- package/src/testing/enzyme-to-react-testing-library.ts +118 -31
- package/src/testing/enzyme-wrapper-scope.ts +39 -10
- package/src/util/java-recipe-proxy.ts +15 -2
- package/src/util/reindent.ts +35 -0
- package/src/zustand/redux-stores.ts +441 -0
- package/src/zustand/redux-to-zustand.ts +660 -0
- package/src/zustand/zustand-plan.ts +854 -0
- package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
- package/dist/react18/remove-unstable-batched-updates.js +0 -170
- package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
- package/src/react18/remove-unstable-batched-updates.ts +0 -192
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
1
|
+
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isPlainText} from "@openrewrite/rewrite/text";
|
|
2
3
|
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
4
|
import {Expression, J} from "@openrewrite/rewrite/java";
|
|
4
5
|
import {create} from "mutative";
|
|
@@ -10,21 +11,21 @@ import {FindEnzymeUsage} from "../search/find-enzyme-usage";
|
|
|
10
11
|
import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
|
|
11
12
|
import {importBindings} from "../util/module-imports";
|
|
12
13
|
import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
|
|
13
|
-
import {HostComponents, hostComponentExports, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
|
|
14
|
+
import {HostComponents, hostComponentExports, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
|
|
14
15
|
import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
|
|
15
16
|
import {evaluate, stringParts} from "./enzyme-constant-strings";
|
|
16
17
|
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";
|
|
18
|
+
import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mountedElement, passesRef, selectorLiteral, simpleChain, statementPosition, throwingPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead, WrapperUse} from "./enzyme-wrapper-scope";
|
|
18
19
|
|
|
19
20
|
const RTL = "@testing-library/react";
|
|
20
21
|
|
|
21
|
-
const REACT_RANGE = ">=
|
|
22
|
+
const REACT_RANGE = ">=15.5.0 <18";
|
|
22
23
|
|
|
23
24
|
const REACT_18_RANGE = ">=18.0.0 <19";
|
|
24
25
|
|
|
25
26
|
const resolvingReact = (range: string) => [`react@${range}`, `react-dom@${range}`];
|
|
26
27
|
|
|
27
|
-
/** RTL 12
|
|
28
|
+
/** RTL 12 renders with React 15.5 to 17, through its own act polyfill before 16.8, so it goes where Enzyme is used with those. */
|
|
28
29
|
const RTL_ADDITION: AddDependencyOptions = {
|
|
29
30
|
packageName: RTL, version: "^12.1.5", scope: "devDependencies",
|
|
30
31
|
onlyIfDeclaring: ["enzyme"], onlyIfResolving: resolvingReact(REACT_RANGE)
|
|
@@ -142,7 +143,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
|
|
|
142
143
|
export class AddTestingLibraryReact extends EnzymeTestDependency {
|
|
143
144
|
readonly name = "org.openrewrite.react.migrate.add-testing-library-react";
|
|
144
145
|
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
|
|
146
|
+
readonly description = "Adds `@testing-library/react` 12 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 15.5 to 17.";
|
|
146
147
|
|
|
147
148
|
constructor(forecast: ConversionForecast = {}) {
|
|
148
149
|
super(RTL_ADDITION, forecast);
|
|
@@ -283,10 +284,16 @@ interface PackageDeclarations {
|
|
|
283
284
|
reactDom: Declaration;
|
|
284
285
|
rtl: Declaration;
|
|
285
286
|
enzyme: boolean;
|
|
287
|
+
/** Its `name`, by which packages of the same repository depend on it. */
|
|
288
|
+
name: string | undefined;
|
|
289
|
+
/** For a workspace root, the package roots of its members, which share its `node_modules` and lockfile. */
|
|
290
|
+
members: ReadonlySet<string>;
|
|
286
291
|
/** The names of every package it depends on, in any dependency section. */
|
|
287
292
|
dependencies: ReadonlySet<string>;
|
|
288
293
|
/** Whether its lockfile resolves a package that puts styles into the root node of a render's container. */
|
|
289
294
|
rootStyles: boolean;
|
|
295
|
+
/** Whether its test toolchain parses `?.` and `??`: JavaScript through Babel 7.8+ or react-scripts 3.3+, TypeScript also through TypeScript 3.7+. */
|
|
296
|
+
optionalChaining: {js: boolean, ts: boolean};
|
|
290
297
|
}
|
|
291
298
|
|
|
292
299
|
/**
|
|
@@ -302,6 +309,16 @@ export function injectsRootStyles(packages: Packages, sourcePath: string): boole
|
|
|
302
309
|
return [...packages.entries()].some(([root, declarations]) => sourcePath.startsWith(root) && declarations.rootStyles);
|
|
303
310
|
}
|
|
304
311
|
|
|
312
|
+
/** Whether every package a test is in has a toolchain that parses optional chaining for it. */
|
|
313
|
+
export function parsesOptionalChaining(packages: Packages, sourcePath: string, typescript: boolean): boolean {
|
|
314
|
+
return [...packages.entries()].every(([root, {optionalChaining}]) => !sourcePath.startsWith(root) ||
|
|
315
|
+
(typescript ? optionalChaining.ts : optionalChaining.js));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** A declared or resolved version below `major.minor`. */
|
|
319
|
+
const below = (version: Declaration, major: number, minor: number) => typeof version === "object" &&
|
|
320
|
+
(version.major < major || version.major === major && version.minor !== undefined && version.minor < minor);
|
|
321
|
+
|
|
305
322
|
/** The reads of a whole container, which see what a component inserts into it besides what React renders. */
|
|
306
323
|
const CONTAINER_READS: ReadonlySet<WrapperUse> = new Set<WrapperUse>(["text", "rootHtml", "snapshot"]);
|
|
307
324
|
|
|
@@ -314,8 +331,15 @@ interface Scanned {
|
|
|
314
331
|
modules: Modules;
|
|
315
332
|
/** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
|
|
316
333
|
names: Map<string, SelectorNames>;
|
|
334
|
+
/** The tests whose stored Jest snapshots include Enzyme's `null` for an empty render. */
|
|
335
|
+
nullSnapshots: Set<string>;
|
|
317
336
|
}
|
|
318
337
|
|
|
338
|
+
// REGEX: `<dir>/__snapshots__/<test file>.snap`, Jest's default location of a test file's snapshots
|
|
339
|
+
const SNAPSHOT_FILE = /^(.*?)__snapshots__\/([^/]+)\.snap$/;
|
|
340
|
+
// REGEX: a stored snapshot entry whose value is `null`
|
|
341
|
+
const NULL_SNAPSHOT = /^exports\[`.*`\] = `null`;$/m;
|
|
342
|
+
|
|
319
343
|
/** A dry run of the editor: the package roots it takes RTL to have, and the sources it converts. */
|
|
320
344
|
interface DryRun {
|
|
321
345
|
landed: ReadonlySet<string>;
|
|
@@ -347,7 +371,8 @@ const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Ex
|
|
|
347
371
|
* The React major version the tests of a source file run with, or 0 where they cannot migrate. A
|
|
348
372
|
* dependency the owning package does not declare comes from the nearest enclosing package that
|
|
349
373
|
* 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
|
|
374
|
+
* Enzyme, one of the `landed` package roots, it is there for every package within it, and for the
|
|
375
|
+
* workspace packages that take Enzyme from it as a dependency, as from a shared Jest preset.
|
|
351
376
|
*/
|
|
352
377
|
export function reactMajor(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): number {
|
|
353
378
|
return compatibility(packages, sourcePath, landed).react;
|
|
@@ -366,14 +391,14 @@ const HOVER_EVENTS = new Set(["mouseEnter", "mouseLeave", "mouseOver", "mouseOut
|
|
|
366
391
|
/**
|
|
367
392
|
* Which `simulate` calls can become `fireEvent` for a source file. On React 17, every supported event,
|
|
368
393
|
* 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
|
|
394
|
+
* listens to, which RTL 10 does only from 10.4.9. On React 15 and 16, which listen on the document rather than
|
|
370
395
|
* the root, every one but the hover events, in a render attached to the document.
|
|
371
396
|
*/
|
|
372
397
|
export function simulatesEvents(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): SimulatedEvents {
|
|
373
398
|
const {react, rtl} = compatibility(packages, sourcePath, landed);
|
|
374
399
|
// React 18 listens on the root, as React 17 does
|
|
375
400
|
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};
|
|
401
|
+
if ((react === 15 || react === 16) && rtl >= 10) return {events: new Set([...SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true};
|
|
377
402
|
return {events: new Set(), attached: false};
|
|
378
403
|
}
|
|
379
404
|
|
|
@@ -383,16 +408,18 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
|
|
|
383
408
|
const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
|
|
384
409
|
from.map(root => packages.get(root)![name]).find(version => version !== undefined);
|
|
385
410
|
const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
|
|
386
|
-
(
|
|
411
|
+
([16, 17, 18].includes(version.major) || version.major === 15 && version.minor !== undefined && version.minor >= 5);
|
|
387
412
|
const react = declared("react");
|
|
388
413
|
const rtl = declared("rtl");
|
|
389
414
|
const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
415
|
+
// The package roots RTL goes to and resolves React from: those of the package declaring Enzyme
|
|
416
|
+
const enzymeRoots = enzyme >= 0 ? roots.slice(enzyme) : providerRoots(packages, roots);
|
|
417
|
+
const enzymeReact = enzymeRoots.length ? declared("react", enzymeRoots) : undefined;
|
|
418
|
+
const added = rtl === undefined && enzymeRoots.length > 0 && landed.has(enzymeRoots[0]) &&
|
|
419
|
+
supportedReact(enzymeReact) && supportedReact(declared("reactDom", enzymeRoots));
|
|
393
420
|
// RTL renders with the React DOM it resolves from its own package
|
|
394
|
-
const rtlRoot =
|
|
395
|
-
const reactDom = declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
|
|
421
|
+
const rtlRoot = roots.findIndex(root => packages.get(root)!.rtl !== undefined);
|
|
422
|
+
const reactDom = added ? declared("reactDom", enzymeRoots) : declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
|
|
396
423
|
// `render` with a container, `rerender`, `unmount`, and `fireEvent` are all there since RTL 10
|
|
397
424
|
const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
|
|
398
425
|
const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
|
|
@@ -401,13 +428,43 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
|
|
|
401
428
|
}
|
|
402
429
|
|
|
403
430
|
/**
|
|
404
|
-
*
|
|
405
|
-
*
|
|
431
|
+
* The package roots, nearest first, of a workspace member that declares Enzyme and that the workspace's root or
|
|
432
|
+
* another of its members, owning the source, depends on by name, as a workspace's packages do on a shared Jest preset. Its dependencies are
|
|
433
|
+
* hoisted to the workspace's `node_modules`, where the source resolves Enzyme today and RTL once it is added there.
|
|
434
|
+
*/
|
|
435
|
+
function providerRoots(packages: Packages, roots: readonly string[]): string[] {
|
|
436
|
+
// A package outside the provider's workspace installs a published package of that name in its own `node_modules`
|
|
437
|
+
const workspace = (root: string) => [...packages.entries()].find(([, declarations]) => declarations.members.has(root))?.[0];
|
|
438
|
+
const provider = [...packages.entries()].find(([path, declarations]) => declarations.enzyme && declarations.name !== undefined &&
|
|
439
|
+
workspace(path) !== undefined && roots.some(root => packages.get(root)!.dependencies.has(declarations.name!) &&
|
|
440
|
+
(root === workspace(path) || workspace(root) === workspace(path))))?.[0];
|
|
441
|
+
if (provider === undefined) return [];
|
|
442
|
+
return [...packages.keys()].filter(root => provider.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Whether an RTL major renders with a React major as the runtime tests show: RTL 12 with React 15.5+, RTL 10 to 12 with
|
|
447
|
+
* React 16 and 17, and RTL 16 with React 18, where RTL 13 to 15 also render but are not covered.
|
|
406
448
|
*/
|
|
407
449
|
function rtlSupports(rtl: number, react: number): boolean {
|
|
450
|
+
if (react === 15) return rtl === 12;
|
|
408
451
|
return react <= 17 ? rtl <= 12 : rtl === 16;
|
|
409
452
|
}
|
|
410
453
|
|
|
454
|
+
// Babel 6 presets and their core, which parse neither `?.` nor `??`
|
|
455
|
+
const BABEL_6 = ["babel-preset-es2015", "babel-preset-es2016", "babel-preset-es2017", "babel-preset-latest", "babel-preset-stage-0", "babel-preset-stage-1"];
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Whether a package's own dependencies parse optional chaining: not with Babel 6, Babel 7 before 7.8 (whose preset-env
|
|
459
|
+
* lacks the proposal), or react-scripts before 3.3, and in TypeScript tests not with TypeScript before 3.7.
|
|
460
|
+
*/
|
|
461
|
+
function optionalChainingOf(declares: (name: string) => boolean, version: (name: string) => Declaration): {js: boolean, ts: boolean} {
|
|
462
|
+
const babel6 = !declares("@babel/core") && (BABEL_6.some(declares) || below(version("babel-core"), 7, 0) ||
|
|
463
|
+
below(version("babel-preset-env"), 2, 0) || below(version("babel-cli"), 7, 0));
|
|
464
|
+
const js = !babel6 && !below(version("@babel/core"), 7, 8) && !below(version("react-scripts"), 3, 3);
|
|
465
|
+
return {js, ts: js && !below(version("typescript"), 3, 7)};
|
|
466
|
+
}
|
|
467
|
+
|
|
411
468
|
/**
|
|
412
469
|
* A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
|
|
413
470
|
* whose minor version is known only where it is a lower bound.
|
|
@@ -448,7 +505,7 @@ function declaredVersion(version: string | undefined): Declaration {
|
|
|
448
505
|
export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
449
506
|
readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
|
|
450
507
|
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
|
|
508
|
+
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 15.5 and 16) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16 or 17 with RTL 10 to 12, React 15.5+ with RTL 12, or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. On React 15, whose markup differs, `html()` and DOM nodes are left for review. 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.";
|
|
452
509
|
|
|
453
510
|
@Option({
|
|
454
511
|
displayName: "Convert positions into untagged selector matches",
|
|
@@ -481,7 +538,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
481
538
|
|
|
482
539
|
initialValue(): Scanned {
|
|
483
540
|
this.tests.length = 0;
|
|
484
|
-
return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map()};
|
|
541
|
+
return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map(), nullSnapshots: new Set()};
|
|
485
542
|
}
|
|
486
543
|
|
|
487
544
|
// The host may prepare the visitors before there is an accumulator, so it is read only while visiting
|
|
@@ -522,28 +579,42 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
522
579
|
reactDom: declaredVersion(version("react-dom")),
|
|
523
580
|
rtl: declaredVersion(version(RTL)),
|
|
524
581
|
enzyme: dependencies.some(dep => dep.name === "enzyme"),
|
|
582
|
+
name: resolution?.name,
|
|
583
|
+
members: new Set((resolution?.workspacePackagePaths ?? []).map(member => member.replace(/^\.\//, "").slice(0, -"package.json".length))),
|
|
525
584
|
dependencies: new Set(dependencies.map(dep => dep.name)),
|
|
526
585
|
rootStyles: (resolution?.resolvedDependencies ?? []).some(dep => {
|
|
527
586
|
const range = ROOT_STYLES.get(dep.name);
|
|
528
587
|
return range !== undefined && valid(dep.version) !== null && satisfies(dep.version, range);
|
|
529
|
-
})
|
|
588
|
+
}),
|
|
589
|
+
optionalChaining: optionalChainingOf(name => dependencies.some(dep => dep.name === name), name => declaredVersion(version(name)))
|
|
530
590
|
});
|
|
531
591
|
return doc;
|
|
532
592
|
}
|
|
533
593
|
}();
|
|
534
594
|
const scan = new class extends TreeVisitor<any, ExecutionContext> {
|
|
535
595
|
override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
|
|
536
|
-
return await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
|
|
596
|
+
return isPlainText(sourceFile) && SNAPSHOT_FILE.test(sourceFile.sourcePath) || await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
|
|
537
597
|
}
|
|
538
598
|
|
|
539
599
|
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
600
|
+
if (isPlainText(tree)) {
|
|
601
|
+
const snapshot = SNAPSHOT_FILE.exec(tree.sourcePath);
|
|
602
|
+
if (snapshot && NULL_SNAPSHOT.test(tree.text)) scanned.nullSnapshots.add(snapshot[1] + snapshot[2]);
|
|
603
|
+
}
|
|
540
604
|
if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
|
|
541
605
|
return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
|
|
542
606
|
}
|
|
543
607
|
}();
|
|
544
608
|
// 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")
|
|
609
|
+
// plain TreeVisitor every tree, including Python ones the TypeScript side has no codec for; of plain text, only Jest snapshot files
|
|
610
|
+
return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS"),
|
|
611
|
+
and(treesOfType("org.openrewrite.text.PlainText"), new RecipeRef("org.openrewrite.FindSourceFiles", {filePattern: "**/__snapshots__/*.snap"}))), scan);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
|
|
615
|
+
// host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
|
|
616
|
+
override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
617
|
+
return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
|
|
547
618
|
}
|
|
548
619
|
|
|
549
620
|
async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
@@ -609,11 +680,14 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
609
680
|
private reactMajor = 0;
|
|
610
681
|
private events: SimulatedEvents = {events: new Set(), attached: false};
|
|
611
682
|
private rootStyles = false;
|
|
683
|
+
private optionalChaining = true;
|
|
684
|
+
private nullSnapshots = false;
|
|
612
685
|
private typescript = false;
|
|
613
686
|
private sourcePath = "";
|
|
614
687
|
private readonly mounts = new Map<string, ConvertedRender>();
|
|
615
688
|
private imports: ReadonlyMap<string, ImportedExport> = new Map();
|
|
616
689
|
private importedNames: ReadonlySet<string> = new Set();
|
|
690
|
+
private declaredHost: ReadonlySet<string> = new Set();
|
|
617
691
|
private readonly uses = new Map<string, WrapperRead>();
|
|
618
692
|
private readonly removedStatements = new Set<string>();
|
|
619
693
|
private readonly unmounts = new Set<string>();
|
|
@@ -643,11 +717,14 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
643
717
|
this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, landed);
|
|
644
718
|
this.events = simulatesEvents(scanned.packages, cu.sourcePath, landed);
|
|
645
719
|
this.rootStyles = injectsRootStyles(scanned.packages, cu.sourcePath);
|
|
720
|
+
this.nullSnapshots = scanned.nullSnapshots.has(cu.sourcePath);
|
|
646
721
|
this.typescript = isTypeScript(cu);
|
|
722
|
+
this.optionalChaining = parsesOptionalChaining(scanned.packages, cu.sourcePath, this.typescript);
|
|
647
723
|
this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
|
|
648
724
|
if (!this.enabled) return cu;
|
|
649
725
|
this.imports = relativeImports(cu, scanned.components);
|
|
650
726
|
this.importedNames = importedNames(cu);
|
|
727
|
+
this.declaredHost = hostComponentsDeclared(cu);
|
|
651
728
|
// 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
729
|
const foreign = prettierStyle !== undefined && !this.prettier;
|
|
653
730
|
const visiting = foreign ? create(cu, draft => {
|
|
@@ -675,7 +752,9 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
675
752
|
if (!candidate) continue;
|
|
676
753
|
const api = candidate.render;
|
|
677
754
|
const reads = READS[api];
|
|
678
|
-
|
|
755
|
+
// React 15 marks its markup with `data-reactroot` and empty renders with comments, which Enzyme's html() leaves out
|
|
756
|
+
const markup = this.reactMajor >= 16;
|
|
757
|
+
const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html && markup, untaggedPositions, hostNames, snapshots: snapshots && markup, optionalChaining: this.optionalChaining,
|
|
679
758
|
constant: node => this.constantString(node)});
|
|
680
759
|
if (!scope) continue;
|
|
681
760
|
if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
|
|
@@ -803,7 +882,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
803
882
|
this.pending.delete(method.id);
|
|
804
883
|
return withRenderOptionsOnElementLine(result, ctx);
|
|
805
884
|
}
|
|
806
|
-
const statementOf = mountedElement(visited) && statementPosition(this.cursor) && !passesRef(visited) ? this.renderOf(visited, false) : undefined;
|
|
885
|
+
const statementOf = mountedElement(visited) && (statementPosition(this.cursor) || throwingPosition(this.cursor)) && !passesRef(visited) ? this.renderOf(visited, false) : undefined;
|
|
807
886
|
const statement = statementOf && await this.tryInline(statementOf, "mount", visited, statementOf, enclosingScope(this.cursor), "MOUNT_STATEMENT", ctx);
|
|
808
887
|
if (statement) return statement;
|
|
809
888
|
const existsOf = visited.name.simpleName === "exists" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
|
|
@@ -871,13 +950,21 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
871
950
|
// An element's text content is never null, though its type allows it
|
|
872
951
|
case "text":
|
|
873
952
|
return code.param(read.wrapper).code(".container.textContent" + (read.unasserted && this.typescript ? "!" : "")).build();
|
|
953
|
+
// Without optional chaining, a read that throws where nothing is found, as Enzyme's does
|
|
874
954
|
case "selectorText":
|
|
875
|
-
if (read.unasserted) return element(true).code(".textContent" + (this.typescript ? "!" : "")).build();
|
|
955
|
+
if (read.unasserted || !this.optionalChaining) return element(true).code(".textContent" + (this.typescript ? "!" : "")).build();
|
|
876
956
|
return element(false).code("?.textContent").build();
|
|
877
|
-
case "html":
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
957
|
+
case "html": {
|
|
958
|
+
const throwing = !!read.unasserted || !this.optionalChaining;
|
|
959
|
+
return element(throwing).code(throwing ? ".outerHTML" : "?.outerHTML").build();
|
|
960
|
+
}
|
|
961
|
+
// Enzyme's html() is null where nothing renders, as a container without child nodes is; only a stored
|
|
962
|
+
// snapshot of that null tells the two apart, so other snapshots keep the plain markup
|
|
963
|
+
case "rootHtml": {
|
|
964
|
+
const nullable = read.snapshot && this.nullSnapshots;
|
|
965
|
+
if (nullable) code.param(read.wrapper).code(".container.childNodes.length ? ");
|
|
966
|
+
return code.param(read.wrapper).code(".container.innerHTML" + (nullable ? " : null" : "")).build();
|
|
967
|
+
}
|
|
881
968
|
case "node":
|
|
882
969
|
return element(true).build();
|
|
883
970
|
case "hasClass":
|
|
@@ -925,7 +1012,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
925
1012
|
const api = enzymeMethod(call);
|
|
926
1013
|
if (api === "mount") return read && this.rendersPortal(call) ? undefined : api;
|
|
927
1014
|
const element = call.arguments.elements[0]?.element;
|
|
928
|
-
return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
|
|
1015
|
+
return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost) ? api : undefined;
|
|
929
1016
|
}
|
|
930
1017
|
|
|
931
1018
|
/**
|
|
@@ -168,6 +168,8 @@ export interface WrapperRead {
|
|
|
168
168
|
vacuous?: boolean;
|
|
169
169
|
/** A read outside an assertion, which throws where nothing is found, as Enzyme's single-node methods do. */
|
|
170
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;
|
|
171
173
|
className?: J.Literal;
|
|
172
174
|
event?: string;
|
|
173
175
|
eventInit?: Expression;
|
|
@@ -211,6 +213,30 @@ export function statementPosition(cursor: Cursor): boolean {
|
|
|
211
213
|
return statement(cursor) !== undefined;
|
|
212
214
|
}
|
|
213
215
|
|
|
216
|
+
const THROW_MATCHERS = new Set(["toThrow", "toThrowError"]);
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Whether a render is the whole body of an arrow function that `expect` takes for `toThrow` or `toThrowError`,
|
|
220
|
+
* plain or negated, as in `expect(() => mount(<Broken />)).toThrow()`. React rethrows an error that no boundary
|
|
221
|
+
* catches from Enzyme's render and from RTL's alike, and the arrow keeps no wrapper.
|
|
222
|
+
*/
|
|
223
|
+
export function throwingPosition(cursor: Cursor): boolean {
|
|
224
|
+
const trees: J[] = [];
|
|
225
|
+
for (let parent = cursor.parentTree(); parent && trees.length < 5; parent = parent.parentTree()) trees.push(parent.value as J);
|
|
226
|
+
const [lambda, arrow, expectCall, ...rest] = trees;
|
|
227
|
+
if (lambda?.kind !== J.Kind.Lambda || (lambda as J.Lambda).body !== cursor.value) return false;
|
|
228
|
+
if (arrow?.kind !== JS.Kind.ArrowFunction || (arrow as JS.ArrowFunction).lambda.parameters.parameters.some(({element}) => element.kind !== J.Kind.Empty)) return false;
|
|
229
|
+
if (expectCall?.kind !== J.Kind.MethodInvocation) return false;
|
|
230
|
+
const expectation = expectCall as J.MethodInvocation;
|
|
231
|
+
if (expectation.name.simpleName !== "expect" || expectation.select || expectation.arguments.elements.length !== 1 ||
|
|
232
|
+
expectation.arguments.elements[0].element !== arrow) return false;
|
|
233
|
+
const [negated, matcher] = rest[0]?.kind === J.Kind.FieldAccess ? rest : [undefined, rest[0]];
|
|
234
|
+
if (negated && ((negated as J.FieldAccess).name.element.simpleName !== "not" || (negated as J.FieldAccess).target !== expectation)) return false;
|
|
235
|
+
if (matcher?.kind !== J.Kind.MethodInvocation) return false;
|
|
236
|
+
const call = matcher as J.MethodInvocation;
|
|
237
|
+
return THROW_MATCHERS.has(call.name.simpleName) && call.select?.element === (negated ?? expectation);
|
|
238
|
+
}
|
|
239
|
+
|
|
214
240
|
/** The argument `mount` renders, which `render` accepts as it is. */
|
|
215
241
|
export function mountedElement(mount: J.MethodInvocation): boolean {
|
|
216
242
|
const [element] = mount.arguments.elements;
|
|
@@ -294,19 +320,19 @@ function nativeEventInit(event: string, init: J | undefined): [string, Expressio
|
|
|
294
320
|
}
|
|
295
321
|
|
|
296
322
|
/**
|
|
297
|
-
* `expect(wrapper.html())` with a matcher RTL's
|
|
298
|
-
*
|
|
323
|
+
* `expect(wrapper.html())` with a matcher RTL's container meets as Enzyme's `html()` does: `"snapshot"` where only the
|
|
324
|
+
* container's `null` for an empty render keeps a stored snapshot, `"string"` where a non-empty string fails either way.
|
|
299
325
|
*/
|
|
300
|
-
function innerHtmlAssertion(read: Cursor, html: J):
|
|
301
|
-
if (!expectArgument(read, html)) return
|
|
326
|
+
function innerHtmlAssertion(read: Cursor, html: J): "snapshot" | "string" | undefined {
|
|
327
|
+
if (!expectArgument(read, html)) return undefined;
|
|
302
328
|
const expect = read.parentTree()!;
|
|
303
329
|
const matcherCursor = expect.parentTree();
|
|
304
330
|
const matcher = matcherCursor?.value as J | undefined;
|
|
305
|
-
if (!selectOf(matcher, expect.value) || !statement(matcherCursor!)) return
|
|
331
|
+
if (!selectOf(matcher, expect.value) || !statement(matcherCursor!)) return undefined;
|
|
306
332
|
const args = (matcher as J.MethodInvocation).arguments.elements.filter(arg => arg.element.kind !== J.Kind.Empty).map(arg => arg.element);
|
|
307
|
-
if (call(matcher, "toMatchSnapshot")) return args.length === 0 || args.length === 1 && stringLiteral(args[0]);
|
|
333
|
+
if (call(matcher, "toMatchSnapshot")) return args.length === 0 || args.length === 1 && stringLiteral(args[0]) ? "snapshot" : undefined;
|
|
308
334
|
return (call(matcher, "toBe") || call(matcher, "toEqual") || call(matcher, "toContain")) &&
|
|
309
|
-
args.length === 1 && stringLiteral(args[0]) && (args[0] as J.Literal).value !== "";
|
|
335
|
+
args.length === 1 && stringLiteral(args[0]) && (args[0] as J.Literal).value !== "" ? "string" : undefined;
|
|
310
336
|
}
|
|
311
337
|
|
|
312
338
|
/** `expect(() => wrapper.unmount()).not.toThrow();`, which unmounts where it stands, as the statement `wrapper.unmount();` does. */
|
|
@@ -364,13 +390,14 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
|
|
|
364
390
|
/**
|
|
365
391
|
* Proves that every reference to a block-scoped wrapper is a supported DOM read, so the
|
|
366
392
|
* declaration and all its uses can be converted together. Any other reference, including
|
|
367
|
-
* arguments, returns, and shorthand properties, rejects the whole scope. `
|
|
393
|
+
* arguments, returns, and shorthand properties, rejects the whole scope. `optionalChaining` says whether the test's
|
|
394
|
+
* toolchain parses `?.` and `??`, without which a find within a positioned element is not converted. `events` are those `simulate`
|
|
368
395
|
* 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`
|
|
369
396
|
* admits `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()`, whose
|
|
370
397
|
* snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
|
|
371
398
|
*/
|
|
372
399
|
export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
|
|
373
|
-
{events, html, untaggedPositions, hostNames, snapshots = false, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, constant?: (node: J) => string | undefined}): WrapperScope | undefined {
|
|
400
|
+
{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 {
|
|
374
401
|
let serializers: ReadonlySet<string> | undefined;
|
|
375
402
|
const uses = new Map<string, WrapperRead>();
|
|
376
403
|
const removedStatements = new Set<string>();
|
|
@@ -434,6 +461,7 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
434
461
|
inner = ancestors[k++].value;
|
|
435
462
|
const nested = ancestors[k]?.value as J | undefined;
|
|
436
463
|
if (call(nested, "find") && selectOf(nested, inner)) {
|
|
464
|
+
if (!optionalChaining) return false;
|
|
437
465
|
const [argument] = (nested as J.MethodInvocation).arguments.elements;
|
|
438
466
|
const withinText = (nested as J.MethodInvocation).arguments.elements.length === 1 ? selectorValue(argument.element) : undefined;
|
|
439
467
|
if (withinText === undefined || !onlyBelow(selectorText, withinText)) return false;
|
|
@@ -490,7 +518,8 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
490
518
|
return record(method, {wrapper: identifier, use: "setProps", props: argument.element as Expression});
|
|
491
519
|
}
|
|
492
520
|
if (!noArguments(method)) return false;
|
|
493
|
-
|
|
521
|
+
const htmlAssertion = html && call(method, "html") ? innerHtmlAssertion(ancestors[0], method) : undefined;
|
|
522
|
+
if (htmlAssertion) return record(method, {wrapper: identifier, use: "rootHtml", snapshot: htmlAssertion === "snapshot"});
|
|
494
523
|
if (call(method, "text")) return record(method, {wrapper: identifier, use: "text", unasserted: !expectArgument(ancestors[0], method)});
|
|
495
524
|
if (call(method, "update") && statement(ancestors[0])?.prefix.comments.length === 0 && method.prefix.comments.length === 0) {
|
|
496
525
|
removedStatements.add(method.id);
|
|
@@ -11,6 +11,8 @@ const NODE_MANIFEST_TREES = ["org.openrewrite.json.tree.Json", "org.openrewrite.
|
|
|
11
11
|
// Native lock transactions also need package-manager policy, patches and hooks they must refuse.
|
|
12
12
|
const NODE_INPUTS = /(^|\/)(\.npmrc|\.yarnrc(?:\.yml)?|bunfig\.toml|\.?pnpmfile\.cjs)$|\.patch$/;
|
|
13
13
|
|
|
14
|
+
const manifestTrees = () => or(...NODE_MANIFEST_TREES.map(treesOfType));
|
|
15
|
+
|
|
14
16
|
export function isNodeDependencyInput(path: string, includeInputs = false): boolean {
|
|
15
17
|
return NODE_MANIFESTS.test(path) || includeInputs && NODE_INPUTS.test(path);
|
|
16
18
|
}
|
|
@@ -44,8 +46,19 @@ export abstract class JavaDependencyRecipe extends ScanningRecipe<number> {
|
|
|
44
46
|
return true;
|
|
45
47
|
}
|
|
46
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
|
+
|
|
47
60
|
async editorWithData(acc: number): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
48
|
-
return manifestsOnly(async () => this.java.editorWithData(acc),
|
|
61
|
+
return manifestsOnly(async () => this.java.editorWithData(acc), manifest => this.edits(manifest), this.includePackageManagerInputs);
|
|
49
62
|
}
|
|
50
63
|
|
|
51
64
|
async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
@@ -77,5 +90,5 @@ async function manifestsOnly(remote: () => Promise<TreeVisitor<any, ExecutionCon
|
|
|
77
90
|
// tree, so this names the types for it. It reads the gate of a scanner only (openrewrite/rewrite#9734).
|
|
78
91
|
// Config and hook files can have any parser type; a plain visitor avoids requiring optional Java parser modules.
|
|
79
92
|
if (includeInputs) return manifests;
|
|
80
|
-
return await check(
|
|
93
|
+
return await check(manifestTrees(), manifests);
|
|
81
94
|
}
|
|
@@ -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
|
+
}
|