@openrewrite/recipes-react 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +10 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/search/find-enzyme-usage.d.ts +4 -0
  10. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  11. package/dist/search/find-enzyme-usage.js +64 -4
  12. package/dist/search/find-enzyme-usage.js.map +1 -1
  13. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  14. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  15. package/dist/search/find-hard-coded-strings.js +987 -0
  16. package/dist/search/find-hard-coded-strings.js.map +1 -0
  17. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  18. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  19. package/dist/search/find-missing-use-client-directive.js +1 -0
  20. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  21. package/dist/testing/enzyme-portals.d.ts +3 -5
  22. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  23. package/dist/testing/enzyme-portals.js +8 -39
  24. package/dist/testing/enzyme-portals.js.map +1 -1
  25. package/dist/testing/enzyme-render-blockers.d.ts +10 -0
  26. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  27. package/dist/testing/enzyme-render-blockers.js +119 -0
  28. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  29. package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
  30. package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
  31. package/dist/testing/enzyme-shared-wrapper.js +213 -0
  32. package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
  33. package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
  34. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  35. package/dist/testing/enzyme-to-react-testing-library.js +355 -16
  36. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  37. package/dist/testing/enzyme-usage.d.ts +5 -1
  38. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  39. package/dist/testing/enzyme-usage.js +48 -6
  40. package/dist/testing/enzyme-usage.js.map +1 -1
  41. package/dist/testing/enzyme-wrapper-scope.d.ts +7 -1
  42. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  43. package/dist/testing/enzyme-wrapper-scope.js +24 -9
  44. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  45. package/dist/util/json-and-javascript.d.ts +4 -0
  46. package/dist/util/json-and-javascript.d.ts.map +1 -0
  47. package/dist/util/json-and-javascript.js +37 -0
  48. package/dist/util/json-and-javascript.js.map +1 -0
  49. package/dist/util/module-imports.d.ts +36 -0
  50. package/dist/util/module-imports.d.ts.map +1 -1
  51. package/dist/util/module-imports.js +216 -0
  52. package/dist/util/module-imports.js.map +1 -1
  53. package/dist/util/test-source.d.ts +2 -0
  54. package/dist/util/test-source.d.ts.map +1 -0
  55. package/dist/util/test-source.js +5 -0
  56. package/dist/util/test-source.js.map +1 -0
  57. package/dist/zustand/entry-store.d.ts +9 -0
  58. package/dist/zustand/entry-store.d.ts.map +1 -0
  59. package/dist/zustand/entry-store.js +136 -0
  60. package/dist/zustand/entry-store.js.map +1 -0
  61. package/dist/zustand/redux-stores.d.ts +15 -4
  62. package/dist/zustand/redux-stores.d.ts.map +1 -1
  63. package/dist/zustand/redux-stores.js +155 -10
  64. package/dist/zustand/redux-stores.js.map +1 -1
  65. package/dist/zustand/redux-to-zustand.d.ts +29 -5
  66. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  67. package/dist/zustand/redux-to-zustand.js +629 -42
  68. package/dist/zustand/redux-to-zustand.js.map +1 -1
  69. package/dist/zustand/zustand-plan.d.ts +31 -6
  70. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  71. package/dist/zustand/zustand-plan.js +320 -31
  72. package/dist/zustand/zustand-plan.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  75. package/src/index.ts +7 -0
  76. package/src/search/find-enzyme-usage.ts +59 -6
  77. package/src/search/find-hard-coded-strings.ts +1006 -0
  78. package/src/search/find-missing-use-client-directive.ts +1 -1
  79. package/src/testing/enzyme-portals.ts +4 -44
  80. package/src/testing/enzyme-render-blockers.ts +113 -0
  81. package/src/testing/enzyme-shared-wrapper.ts +224 -0
  82. package/src/testing/enzyme-to-react-testing-library.ts +354 -19
  83. package/src/testing/enzyme-usage.ts +62 -5
  84. package/src/testing/enzyme-wrapper-scope.ts +24 -6
  85. package/src/util/json-and-javascript.ts +26 -0
  86. package/src/util/module-imports.ts +223 -0
  87. package/src/util/test-source.ts +2 -0
  88. package/src/zustand/entry-store.ts +131 -0
  89. package/src/zustand/redux-stores.ts +171 -11
  90. package/src/zustand/redux-to-zustand.ts +689 -48
  91. package/src/zustand/zustand-plan.ts +350 -29
@@ -1,7 +1,7 @@
1
1
  import {Column, Cursor} from "@openrewrite/rewrite";
2
- import {JS, walk} from "@openrewrite/rewrite/javascript";
2
+ import {JS, namesReferencedWithin, walk} from "@openrewrite/rewrite/javascript";
3
3
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
- import {importBindings, resolveRelative} from "../util/module-imports";
4
+ import {importBindings, Resolve, resolveRelative} from "../util/module-imports";
5
5
 
6
6
  export const REDUX = "redux";
7
7
  export const RTK = "@reduxjs/toolkit";
@@ -342,12 +342,13 @@ export function localSlices(cu: JS.CompilationUnit): LocalSlices {
342
342
  }
343
343
 
344
344
  /** Resolves a reducer expression of a store to the slice it is the reducer of. */
345
- export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: LocalSlices, modules: ReadonlyMap<string, SliceModule>): SliceFacts | undefined {
345
+ export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: LocalSlices, modules: ReadonlyMap<string, SliceModule>,
346
+ resolve: Resolve = (from, specifier) => resolveRelative(from, specifier, modules)): SliceFacts | undefined {
346
347
  const inFile = reducerOf(node, local.localSlices) ?? (isIdentifier(node) ? local.localReducers.get(node.simpleName) : undefined);
347
348
  if (inFile) return inFile;
348
349
  const imported = (name: string) => {
349
350
  const binding = importBindings(cu).find(b => b.local === name);
350
- const path = binding && resolveRelative(cu.sourcePath, binding.module, modules);
351
+ const path = binding && resolve(cu.sourcePath, binding.module);
351
352
  return path ? {binding, module: modules.get(path)!} : undefined;
352
353
  };
353
354
  if (isIdentifier(node)) {
@@ -365,7 +366,7 @@ export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: Loca
365
366
 
366
367
  export const SUGGESTED_ACTIONS: Readonly<Record<string, string>> = {
367
368
  SLICE_STORE: "A store of `createSlice` reducers with the default middleware: each slice can become a zustand store. Check its consumers next.",
368
- LEGACY_STORE: "Move the store to Redux Toolkit's `configureStore` and its reducers to `createSlice` first, or write the zustand store by hand.",
369
+ LEGACY_STORE: "A `createStore` of a reducer, perhaps a preloaded state, and perhaps `applyMiddleware(thunk)` or Redux DevTools, moves whole; move a store with other middleware or enhancers to Redux Toolkit's `configureStore` first, or write the zustand store by hand.",
369
370
  OPTIONS_NOT_LITERAL: "Write the `configureStore` options as an object literal, so that the setup can be read.",
370
371
  ROOT_REDUCER: "Pass `reducer` as an object of slice reducers; a single root reducer, such as `combineReducers(...)`, can't be split into zustand stores.",
371
372
  NON_SLICE_REDUCER: "Rewrite this reducer with `createSlice`, or keep it in Redux; zustand has no place for a hand-written reducer.",
@@ -379,7 +380,7 @@ export const SUGGESTED_ACTIONS: Readonly<Record<string, string>> = {
379
380
  UNKNOWN_OPTION: "Review this `configureStore` option by hand."
380
381
  };
381
382
 
382
- export const TEST_SOURCE = /(^|\/)(__tests__|__mocks__|tests?|stories)\/|\.(test|spec|stories)\.[jt]sx?$/i;
383
+ export {TEST_SOURCE} from "../util/test-source";
383
384
 
384
385
  /** The options of `configureStore` that keep a store from converting, by the reason they are recorded under. */
385
386
  const BLOCKING_OPTIONS: Readonly<Record<string, string>> = {
@@ -389,6 +390,8 @@ const BLOCKING_OPTIONS: Readonly<Record<string, string>> = {
389
390
  export interface Finding {
390
391
  reason: string;
391
392
  detail: string;
393
+ /** What to do about this finding, where it says more than the reason's own action. */
394
+ action?: string;
392
395
  }
393
396
 
394
397
  /** The local names a source calls to create a Redux store: legacy `createStore` and Redux Toolkit's `configureStore`. */
@@ -399,15 +402,169 @@ export function storeFunctions(cu: JS.CompilationUnit): {legacy: Set<string>, co
399
402
  };
400
403
  }
401
404
 
405
+ /**
406
+ * How a store can move to zustand whole: a `configureStore` of an object of reducers it combines (`combined`) or of a
407
+ * reducer of its own (`reducer`), or a legacy `createStore` of a reducer and perhaps a preloaded state (`legacy`).
408
+ */
409
+ export type ReducerStoreKind = "combined" | "reducer" | "legacy" | "legacyThunk";
410
+
411
+ const REDUX_THUNK = "redux-thunk";
412
+ const DEVTOOLS = ["redux-devtools-extension", "@redux-devtools/extension"];
413
+
414
+ /**
415
+ * What a legacy store's enhancer does, when it is one the conversion reproduces: whether it applies redux-thunk, and
416
+ * the names of the top-level `const`s it is written with. Otherwise why it isn't one.
417
+ */
418
+ export type LegacyEnhancer = {thunk: boolean, consts: Set<string>} | {unsupported: string};
419
+
420
+ /**
421
+ * Reads a legacy store's enhancer: `applyMiddleware` of redux-thunk alone, perhaps spread from a `const` array, inside
422
+ * `compose`, Redux DevTools' compose or `composeWithDevTools`, or DevTools' own enhancer. DevTools only shows the store
423
+ * in the browser extension, so dropping it changes nothing the app does.
424
+ */
425
+ export function legacyEnhancer(expression: J, cu: JS.CompilationUnit): LegacyEnhancer {
426
+ const bindings = importBindings(cu);
427
+ const imported = (name: string, modules: string[], member: string) => bindings.some(b => b.local === name && modules.includes(b.module) && b.name === member);
428
+ const thunk = (name: string) => imported(name, [REDUX_THUNK], "default") || imported(name, [REDUX_THUNK], "thunk");
429
+ const consts = new Set<string>();
430
+ const constant = (name: string): J | undefined => {
431
+ const declarations = cu.statements.map(st => st.element).flatMap(statement => {
432
+ if (statement.kind !== J.Kind.VariableDeclarations) return [];
433
+ const variables = statement as J.VariableDeclarations;
434
+ return variables.variables.map(v => v.element).filter(v => isIdentifier(v.name) && v.name.simpleName === name)
435
+ .map(v => ({constant: variables.variables.length === 1 && variables.modifiers.some(m => m.keyword === "const"), initializer: v.initializer?.element}));
436
+ });
437
+ if (declarations.length !== 1 || !declarations[0].constant || !declarations[0].initializer) return undefined;
438
+ consts.add(name);
439
+ return declarations[0].initializer;
440
+ };
441
+ const unwrap = (node: J): J => node.kind === J.Kind.Parentheses ? unwrap((node as J.Parentheses<J>).tree.element) : node;
442
+ const window = (node: J, member: string) => {
443
+ const n = unwrap(node);
444
+ return n.kind === J.Kind.FieldAccess && isIdentifier((n as J.FieldAccess).target) && ((n as J.FieldAccess).target as J.Identifier).simpleName === "window" &&
445
+ (n as J.FieldAccess).name.element.simpleName === member;
446
+ };
447
+ const binary = (node: J, operator: string) => {
448
+ const n = unwrap(node);
449
+ return n.kind === J.Kind.Binary && (n as J.Binary).operator.element === operator ? n as J.Binary : undefined;
450
+ };
451
+ // `window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose`, perhaps guarded by `typeof window !== "undefined" &&`
452
+ const devtoolsCompose = (node: J): boolean => {
453
+ const or = binary(node, "Or");
454
+ if (!or || !isIdentifier(unwrap(or.right)) || !imported((unwrap(or.right) as J.Identifier).simpleName, [REDUX], "compose")) return false;
455
+ const guarded = binary(or.left, "And");
456
+ if (guarded) return guarded.left.kind === JS.Kind.Binary && (guarded.left as JS.Binary).left.kind === JS.Kind.TypeOf && window(guarded.right, "__REDUX_DEVTOOLS_EXTENSION_COMPOSE__");
457
+ return window(or.left, "__REDUX_DEVTOOLS_EXTENSION_COMPOSE__");
458
+ };
459
+ const composer = (callee: J): boolean => {
460
+ if (!isIdentifier(callee)) return false;
461
+ const name = callee.simpleName;
462
+ if (imported(name, [REDUX], "compose") || imported(name, DEVTOOLS, "composeWithDevTools")) return true;
463
+ const initializer = constant(name);
464
+ return initializer !== undefined && devtoolsCompose(initializer);
465
+ };
466
+ const middleware = (node: J): string | undefined => {
467
+ if (isIdentifier(node)) return thunk(node.simpleName) ? undefined : `the middleware \`${node.simpleName}\``;
468
+ if (node.kind === JS.Kind.Spread && isIdentifier((node as JS.Spread).expression)) {
469
+ const name = ((node as JS.Spread).expression as J.Identifier).simpleName;
470
+ const array = constant(name);
471
+ if (array?.kind !== J.Kind.NewArray) return `middleware spread from \`${name}\``;
472
+ // An array that another statement refers to, such as one that pushes more middleware into it, may not hold only what it declares
473
+ if (cu.statements.filter(st => [...namesReferencedWithin(st.element)].includes(name)).length > 1) return `middleware spread from \`${name}\`, which is used elsewhere too`;
474
+ for (const element of (array as J.NewArray).initializer?.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty) ?? []) {
475
+ const why = middleware(element);
476
+ if (why) return why;
477
+ }
478
+ return undefined;
479
+ }
480
+ return "middleware other than redux-thunk";
481
+ };
482
+ let thunked = false;
483
+ const enhancer = (node: J): string | undefined => {
484
+ node = unwrap(node);
485
+ if (isIdentifier(node)) {
486
+ const initializer = constant(node.simpleName);
487
+ return initializer ? enhancer(initializer) : `an enhancer \`${node.simpleName}\``;
488
+ }
489
+ // `window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()`
490
+ const and = binary(node, "And");
491
+ if (and && window(and.left, "__REDUX_DEVTOOLS_EXTENSION__")) {
492
+ const call = unwrap(and.right);
493
+ return call.kind === J.Kind.MethodInvocation && (call as J.MethodInvocation).name.simpleName === "__REDUX_DEVTOOLS_EXTENSION__" ? undefined : "an enhancer other than Redux DevTools";
494
+ }
495
+ if (node.kind !== J.Kind.MethodInvocation || (node as J.MethodInvocation).select) return "an enhancer other than applyMiddleware and Redux DevTools";
496
+ const call = node as J.MethodInvocation;
497
+ const args = call.arguments.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
498
+ const name = call.name.simpleName;
499
+ if (imported(name, [REDUX], "applyMiddleware")) {
500
+ for (const arg of args) {
501
+ const why = middleware(arg);
502
+ if (why) return why;
503
+ }
504
+ thunked ||= args.length > 0;
505
+ return undefined;
506
+ }
507
+ if (imported(name, DEVTOOLS, "devToolsEnhancer") || imported(name, DEVTOOLS, "devToolsEnhancerLogOnlyInProduction")) return undefined;
508
+ if (composer(call.name)) {
509
+ for (const arg of args) {
510
+ const why = enhancer(arg);
511
+ if (why) return why;
512
+ }
513
+ return undefined;
514
+ }
515
+ return `an enhancer \`${name}\``;
516
+ };
517
+ const why = enhancer(expression);
518
+ return why ? {unsupported: why} : {thunk: thunked, consts};
519
+ }
520
+
521
+ /** Whether `expression` is a function or a call of `applyMiddleware` or `compose`, which `createStore` takes as an enhancer. */
522
+ function isFunction(expression: J): boolean {
523
+ return expression.kind === J.Kind.Lambda || expression.kind === JS.Kind.ArrowFunction ||
524
+ (expression.kind === J.Kind.MethodInvocation && ["applyMiddleware", "compose"].includes((expression as J.MethodInvocation).name.simpleName));
525
+ }
526
+
527
+ /**
528
+ * Whether `expression`, passed after the reducer to `createStore`, is surely not a function, so Redux takes it as the
529
+ * preloaded state: a literal, an object or array literal, or a top-level `const` the source declares once as one.
530
+ */
531
+ export function preloadedValue(expression: J, cu: JS.CompilationUnit): boolean {
532
+ const literal = (node: J | undefined): boolean => node !== undefined && (node.kind === J.Kind.Literal || node.kind === J.Kind.NewArray ||
533
+ (node.kind === J.Kind.NewClass && !(node as J.NewClass).class));
534
+ if (literal(expression)) return true;
535
+ if (expression.kind !== J.Kind.Identifier) return false;
536
+ const name = (expression as J.Identifier).simpleName;
537
+ const declarations = cu.statements.map(s => s.element).flatMap(statement => {
538
+ if (statement.kind !== J.Kind.VariableDeclarations) return [];
539
+ const variables = statement as J.VariableDeclarations;
540
+ return variables.variables.map(v => v.element).filter(v => v.name.kind === J.Kind.Identifier && (v.name as J.Identifier).simpleName === name)
541
+ .map(v => ({constant: variables.modifiers.some(m => m.keyword === "const"), initializer: v.initializer?.element}));
542
+ });
543
+ return declarations.length === 1 && declarations[0].constant && literal(declarations[0].initializer);
544
+ }
545
+
402
546
  /**
403
547
  * Why the store `call` creates can't move to zustand, or `[]` for a candidate, with the slices of its reducers by key.
404
548
  * `undefined` when `call` creates no store.
405
549
  */
406
550
  export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule>,
407
- functions = storeFunctions(cu)): {api: string, findings: Finding[], slices: Map<string, SliceFacts>} | undefined {
551
+ functions = storeFunctions(cu), resolve?: Resolve): {api: string, findings: Finding[], slices: Map<string, SliceFacts>, reducerStore?: ReducerStoreKind} | undefined {
408
552
  if (call.select) return undefined;
409
553
  const api = call.name.simpleName;
410
- if (functions.legacy.has(api)) return {api, findings: [{reason: "LEGACY_STORE", detail: api}], slices: new Map()};
554
+ if (functions.legacy.has(api)) {
555
+ // Redux takes a function after the reducer as an enhancer, and anything else as the preloaded state
556
+ const args = call.arguments.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
557
+ // With three arguments, Redux always takes the second as the preloaded state and the third as the enhancer
558
+ const preloaded = args.length === 3 || (args.length === 2 && preloadedValue(args[1], cu));
559
+ const read = args.length === 3 || (args.length === 2 && !preloaded) ? legacyEnhancer(args[args.length - 1], cu) : undefined;
560
+ if (args.length === 1 || args.length === 2 && preloaded || read && !("unsupported" in read)) {
561
+ const thunk = read !== undefined && !("unsupported" in read) && read.thunk;
562
+ return {api, findings: [{reason: "LEGACY_STORE", detail: api}], slices: new Map(), reducerStore: thunk ? "legacyThunk" : "legacy"};
563
+ }
564
+ const detail = args.length === 2 && !isFunction(args[1]) && read && "unsupported" in read && read.unsupported.startsWith("an enhancer `") ?
565
+ `${api} with a second argument that may be an enhancer` : `${api} with ${read && "unsupported" in read ? read.unsupported : "an enhancer"}`;
566
+ return {api, findings: [{reason: "LEGACY_STORE", detail}], slices: new Map()};
567
+ }
411
568
  if (!functions.configure.has(api)) return undefined;
412
569
  const slices = new Map<string, SliceFacts>();
413
570
  const options = objectProperties(call.arguments.elements[0]?.element);
@@ -416,16 +573,19 @@ export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit,
416
573
  for (const key of options.keys()) {
417
574
  if (key !== "reducer") findings.push({reason: BLOCKING_OPTIONS[key] ?? "UNKNOWN_OPTION", detail: key});
418
575
  }
576
+ // A store of its `reducer` alone can also move to zustand whole, driven by that reducer
577
+ const reducer = options.get("reducer");
578
+ const reducerStore = options.size !== 1 || !reducer ? undefined : reducer.kind === J.Kind.NewClass && !(reducer as J.NewClass).class ? "combined" : "reducer";
419
579
  const reducers = objectProperties(options.get("reducer"));
420
- if (!reducers) return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: ""}], slices};
580
+ if (!reducers) return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: ""}], slices, reducerStore};
421
581
  const local = localSlices(cu);
422
582
  for (const [key, value] of reducers) {
423
- const slice = resolveSliceReducer(value, cu, local, modules);
583
+ const slice = resolveSliceReducer(value, cu, local, modules, resolve);
424
584
  if (!slice) findings.push({reason: "NON_SLICE_REDUCER", detail: key});
425
585
  else if (slice.blocker) findings.push(slice.blocker);
426
586
  else slices.set(key, slice);
427
587
  }
428
- return {api, findings, slices};
588
+ return {api, findings, slices, reducerStore};
429
589
  }
430
590
 
431
591
  /** The variable or function a store is created in, such as `store` in `export const store = configureStore(...)`. */