@openrewrite/recipes-react 0.32.0 → 0.33.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 (150) hide show
  1. package/dist/index.d.ts +37 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +146 -2
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/shared.d.ts +2 -8
  6. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  7. package/dist/migration/cra-to-vite/shared.js +21 -53
  8. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  9. package/dist/nextjs-config/config-recipes.d.ts +90 -0
  10. package/dist/nextjs-config/config-recipes.d.ts.map +1 -0
  11. package/dist/nextjs-config/config-recipes.js +222 -0
  12. package/dist/nextjs-config/config-recipes.js.map +1 -0
  13. package/dist/nextjs-config/next-config.d.ts +25 -0
  14. package/dist/nextjs-config/next-config.d.ts.map +1 -0
  15. package/dist/nextjs-config/next-config.js +199 -0
  16. package/dist/nextjs-config/next-config.js.map +1 -0
  17. package/dist/nextjs-search/find-nextjs-projects-below.d.ts +37 -0
  18. package/dist/nextjs-search/find-nextjs-projects-below.d.ts.map +1 -0
  19. package/dist/nextjs-search/find-nextjs-projects-below.js +196 -0
  20. package/dist/nextjs-search/find-nextjs-projects-below.js.map +1 -0
  21. package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts +18 -0
  22. package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts.map +1 -0
  23. package/dist/nextjs-search/find-nextjs-upgrade-issues.js +269 -0
  24. package/dist/nextjs-search/find-nextjs-upgrade-issues.js.map +1 -0
  25. package/dist/nextjs-search/find-pages-router-candidates.d.ts +14 -0
  26. package/dist/nextjs-search/find-pages-router-candidates.d.ts.map +1 -0
  27. package/dist/nextjs-search/find-pages-router-candidates.js +136 -0
  28. package/dist/nextjs-search/find-pages-router-candidates.js.map +1 -0
  29. package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts +16 -0
  30. package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts.map +1 -0
  31. package/dist/nextjs-search/mark-pending-nextjs-upgrade.js +125 -0
  32. package/dist/nextjs-search/mark-pending-nextjs-upgrade.js.map +1 -0
  33. package/dist/nextjs13/new-link.d.ts +8 -0
  34. package/dist/nextjs13/new-link.d.ts.map +1 -0
  35. package/dist/nextjs13/new-link.js +82 -0
  36. package/dist/nextjs13/new-link.js.map +1 -0
  37. package/dist/nextjs13/next-image-to-legacy-image.d.ts +8 -0
  38. package/dist/nextjs13/next-image-to-legacy-image.d.ts.map +1 -0
  39. package/dist/nextjs13/next-image-to-legacy-image.js +103 -0
  40. package/dist/nextjs13/next-image-to-legacy-image.js.map +1 -0
  41. package/dist/nextjs13/next-modules.d.ts +18 -0
  42. package/dist/nextjs13/next-modules.d.ts.map +1 -0
  43. package/dist/nextjs13/next-modules.js +127 -0
  44. package/dist/nextjs13/next-modules.js.map +1 -0
  45. package/dist/nextjs14/metadata-to-viewport-export.d.ts +8 -0
  46. package/dist/nextjs14/metadata-to-viewport-export.d.ts.map +1 -0
  47. package/dist/nextjs14/metadata-to-viewport-export.js +223 -0
  48. package/dist/nextjs14/metadata-to-viewport-export.js.map +1 -0
  49. package/dist/nextjs14/next-og-import.d.ts +8 -0
  50. package/dist/nextjs14/next-og-import.d.ts.map +1 -0
  51. package/dist/nextjs14/next-og-import.js +29 -0
  52. package/dist/nextjs14/next-og-import.js.map +1 -0
  53. package/dist/nextjs15/add-vercel-functions.d.ts +17 -0
  54. package/dist/nextjs15/add-vercel-functions.d.ts.map +1 -0
  55. package/dist/nextjs15/add-vercel-functions.js +86 -0
  56. package/dist/nextjs15/add-vercel-functions.js.map +1 -0
  57. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts +11 -0
  58. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts.map +1 -0
  59. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js +62 -0
  60. package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js.map +1 -0
  61. package/dist/nextjs15/app-router.d.ts +26 -0
  62. package/dist/nextjs15/app-router.d.ts.map +1 -0
  63. package/dist/nextjs15/app-router.js +302 -0
  64. package/dist/nextjs15/app-router.js.map +1 -0
  65. package/dist/nextjs15/async-params.d.ts +8 -0
  66. package/dist/nextjs15/async-params.d.ts.map +1 -0
  67. package/dist/nextjs15/async-params.js +484 -0
  68. package/dist/nextjs15/async-params.js.map +1 -0
  69. package/dist/nextjs15/async-request-apis.d.ts +8 -0
  70. package/dist/nextjs15/async-request-apis.d.ts.map +1 -0
  71. package/dist/nextjs15/async-request-apis.js +204 -0
  72. package/dist/nextjs15/async-request-apis.js.map +1 -0
  73. package/dist/nextjs15/fetch-cache-defaults.d.ts +8 -0
  74. package/dist/nextjs15/fetch-cache-defaults.d.ts.map +1 -0
  75. package/dist/nextjs15/fetch-cache-defaults.js +160 -0
  76. package/dist/nextjs15/fetch-cache-defaults.js.map +1 -0
  77. package/dist/nextjs15/next-request-geo-ip.d.ts +10 -0
  78. package/dist/nextjs15/next-request-geo-ip.d.ts.map +1 -0
  79. package/dist/nextjs15/next-request-geo-ip.js +71 -0
  80. package/dist/nextjs15/next-request-geo-ip.js.map +1 -0
  81. package/dist/nextjs15/route-handler-cache-defaults.d.ts +8 -0
  82. package/dist/nextjs15/route-handler-cache-defaults.d.ts.map +1 -0
  83. package/dist/nextjs15/route-handler-cache-defaults.js +231 -0
  84. package/dist/nextjs15/route-handler-cache-defaults.js.map +1 -0
  85. package/dist/nextjs16/middleware-to-proxy.d.ts +16 -0
  86. package/dist/nextjs16/middleware-to-proxy.d.ts.map +1 -0
  87. package/dist/nextjs16/middleware-to-proxy.js +159 -0
  88. package/dist/nextjs16/middleware-to-proxy.js.map +1 -0
  89. package/dist/nextjs16/next-lint-to-eslint.d.ts +9 -0
  90. package/dist/nextjs16/next-lint-to-eslint.d.ts.map +1 -0
  91. package/dist/nextjs16/next-lint-to-eslint.js +60 -0
  92. package/dist/nextjs16/next-lint-to-eslint.js.map +1 -0
  93. package/dist/nextjs16/remove-experimental-ppr-config.d.ts +9 -0
  94. package/dist/nextjs16/remove-experimental-ppr-config.d.ts.map +1 -0
  95. package/dist/nextjs16/remove-experimental-ppr-config.js +17 -0
  96. package/dist/nextjs16/remove-experimental-ppr-config.js.map +1 -0
  97. package/dist/nextjs16/remove-experimental-ppr.d.ts +8 -0
  98. package/dist/nextjs16/remove-experimental-ppr.d.ts.map +1 -0
  99. package/dist/nextjs16/remove-experimental-ppr.js +67 -0
  100. package/dist/nextjs16/remove-experimental-ppr.js.map +1 -0
  101. package/dist/nextjs16/revalidate-tag-profile.d.ts +8 -0
  102. package/dist/nextjs16/revalidate-tag-profile.d.ts.map +1 -0
  103. package/dist/nextjs16/revalidate-tag-profile.js +46 -0
  104. package/dist/nextjs16/revalidate-tag-profile.js.map +1 -0
  105. package/dist/nextjs16/stable-cache-apis.d.ts +8 -0
  106. package/dist/nextjs16/stable-cache-apis.d.ts.map +1 -0
  107. package/dist/nextjs16/stable-cache-apis.js +29 -0
  108. package/dist/nextjs16/stable-cache-apis.js.map +1 -0
  109. package/dist/react19/replace-default-props.d.ts.map +1 -1
  110. package/dist/react19/replace-default-props.js +50 -13
  111. package/dist/react19/replace-default-props.js.map +1 -1
  112. package/dist/util/java-recipe-proxy.d.ts +1 -0
  113. package/dist/util/java-recipe-proxy.d.ts.map +1 -1
  114. package/dist/util/java-recipe-proxy.js +8 -5
  115. package/dist/util/java-recipe-proxy.js.map +1 -1
  116. package/dist/util/package-json.d.ts +11 -0
  117. package/dist/util/package-json.d.ts.map +1 -0
  118. package/dist/util/package-json.js +46 -0
  119. package/dist/util/package-json.js.map +1 -0
  120. package/package.json +2 -2
  121. package/src/index.ts +123 -0
  122. package/src/migration/cra-to-vite/shared.ts +3 -42
  123. package/src/nextjs-config/config-recipes.ts +219 -0
  124. package/src/nextjs-config/next-config.ts +190 -0
  125. package/src/nextjs-search/find-nextjs-projects-below.ts +216 -0
  126. package/src/nextjs-search/find-nextjs-upgrade-issues.ts +225 -0
  127. package/src/nextjs-search/find-pages-router-candidates.ts +110 -0
  128. package/src/nextjs-search/mark-pending-nextjs-upgrade.ts +131 -0
  129. package/src/nextjs13/new-link.ts +57 -0
  130. package/src/nextjs13/next-image-to-legacy-image.ts +71 -0
  131. package/src/nextjs13/next-modules.ts +93 -0
  132. package/src/nextjs14/metadata-to-viewport-export.ts +224 -0
  133. package/src/nextjs14/next-og-import.ts +19 -0
  134. package/src/nextjs15/add-vercel-functions.ts +78 -0
  135. package/src/nextjs15/app-dir-runtime-config-experimental-edge.ts +38 -0
  136. package/src/nextjs15/app-router.ts +316 -0
  137. package/src/nextjs15/async-params.ts +487 -0
  138. package/src/nextjs15/async-request-apis.ts +213 -0
  139. package/src/nextjs15/fetch-cache-defaults.ts +141 -0
  140. package/src/nextjs15/next-request-geo-ip.ts +49 -0
  141. package/src/nextjs15/route-handler-cache-defaults.ts +189 -0
  142. package/src/nextjs16/middleware-to-proxy.ts +146 -0
  143. package/src/nextjs16/next-lint-to-eslint.ts +43 -0
  144. package/src/nextjs16/remove-experimental-ppr-config.ts +15 -0
  145. package/src/nextjs16/remove-experimental-ppr.ts +39 -0
  146. package/src/nextjs16/revalidate-tag-profile.ts +28 -0
  147. package/src/nextjs16/stable-cache-apis.ts +20 -0
  148. package/src/react19/replace-default-props.ts +65 -27
  149. package/src/util/java-recipe-proxy.ts +9 -3
  150. package/src/util/package-json.ts +43 -0
@@ -0,0 +1,216 @@
1
+ import {check, ExecutionContext, foundSearchResult, Option, RecipeRef, ScanningRecipe, Tree, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isObject, Json, membersOf, valueAt} from "@openrewrite/rewrite/json";
3
+ import {findNodeResolutionResult} from "@openrewrite/rewrite/javascript";
4
+ import {minVersion, satisfies, valid, validRange} from "semver";
5
+ import {dirName, isPackageJson, nearestRoot, stringValue} from "../util/package-json";
6
+
7
+ /** The Next.js version of every package that declares `next`, by package directory (`''` is the repository root). */
8
+ export class NextjsProjects {
9
+ /** Major of `next` per package directory; `undefined` when the version is not a version (`catalog:`, `latest`). */
10
+ readonly majors = new Map<string, number | undefined>();
11
+ /** Package directories whose `next` version is a `catalog:`, git or workspace reference, which the dependency upgrade cannot edit. */
12
+ readonly unresolvable = new Set<string>();
13
+ /** Package directories whose scripts run `next build` or `next dev` with `--webpack`, so that they keep building with webpack on Next.js 16. */
14
+ readonly webpackScripts = new Set<string>();
15
+
16
+ /** Whether the nearest package that declares `next` builds with webpack through a `--webpack` flag in its scripts. */
17
+ usesWebpackFlag(sourcePath: string): boolean {
18
+ const owner = nearestRoot(new Set(this.majors.keys()), sourcePath);
19
+ return owner !== undefined && this.webpackScripts.has(owner);
20
+ }
21
+
22
+ /** Major the lock file resolved, per package directory whose lock disagrees with the declared range (`^16.0.0` declared, 15.5.9 locked). */
23
+ readonly lockMajors = new Map<string, number>();
24
+
25
+ /** Whether the nearest package that declares `next` takes its version from a catalog, git or workspace reference. */
26
+ isUnresolvable(sourcePath: string): boolean {
27
+ const owner = nearestRoot(new Set(this.majors.keys()), sourcePath);
28
+ return owner !== undefined && this.unresolvable.has(owner);
29
+ }
30
+
31
+ /**
32
+ * As {@link majorOf}, but where the lock file resolved a version the declared range does not allow, the lock's
33
+ * major: what is installed, not what package.json asks for.
34
+ */
35
+ resolvedMajorOf(sourcePath: string): number | undefined | null {
36
+ const owner = nearestRoot(new Set(this.majors.keys()), sourcePath);
37
+ return owner === undefined ? null : this.lockMajors.get(owner) ?? this.majors.get(owner);
38
+ }
39
+
40
+ /** The major of the nearest package at or above the file that declares `next`; `null` when there is none. */
41
+ majorOf(sourcePath: string): number | undefined | null {
42
+ const owner = nearestRoot(new Set(this.majors.keys()), sourcePath);
43
+ return owner === undefined ? null : this.majors.get(owner);
44
+ }
45
+ }
46
+
47
+ /** Files the Next.js recipes edit. Everything else stays on the host: marking an image or lock file would only cost an RPC round trip. */
48
+ const SOURCE_FILES = "**/*.{js,jsx,ts,tsx,mjs,mts,cjs,cts,json}";
49
+
50
+ const DEPENDENCY_SECTIONS = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
51
+
52
+ const CATALOG = 'catalog';
53
+
54
+ /**
55
+ * Specifiers `UpgradeDependencyVersions` cannot replace with a semver range: a git or GitHub/GitLab/Bitbucket
56
+ * shorthand reference, a workspace, local (`file:`/`link:`) or tarball URL reference. Unlike `catalog:`, these can
57
+ * still resolve to a readable version in the lock file, but the dependency upgrade has no range to put there instead,
58
+ * so they are treated the same as a catalog entry: left alone.
59
+ */
60
+ const UNRESOLVABLE_REFERENCE = /^(git[+:]|github:|gitlab:|bitbucket:|workspace:|file:|link:|https?:\/\/)/i;
61
+
62
+ /** The major of the `next` a package.json declares, preferring the version the lock file resolved. */
63
+ function nextMajor(doc: Json.Document): { major: number | undefined | null | typeof CATALOG, lockMajor?: number } {
64
+ const major = declaredOrLockedMajor(doc);
65
+ if (typeof major !== 'number') return {major};
66
+ const lockMajor = lockedMajorOutsideRange(doc);
67
+ return lockMajor !== undefined && lockMajor !== major ? {major, lockMajor} : {major};
68
+ }
69
+
70
+ /** The major of the version the lock file resolved, when the declared range does not allow that version. */
71
+ function lockedMajorOutsideRange(doc: Json.Document): number | undefined {
72
+ const declared = DEPENDENCY_SECTIONS.map(s => stringValue(valueAt(doc, [s, 'next']))).find(v => v !== undefined);
73
+ const resolution = findNodeResolutionResult(doc);
74
+ const resolved = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? []]
75
+ .find(dep => dep.name === 'next')?.resolved;
76
+ const version = resolved?.name === 'next' ? resolved.version : undefined;
77
+ return declared && version && valid(version) && validRange(declared) && !satisfies(version, declared, {includePrerelease: true})
78
+ ? Number(version.split('.')[0]) : undefined;
79
+ }
80
+
81
+ function declaredOrLockedMajor(doc: Json.Document): number | undefined | null | typeof CATALOG {
82
+ const declared = DEPENDENCY_SECTIONS.map(s => stringValue(valueAt(doc, [s, 'next']))).find(v => v !== undefined);
83
+ if (declared === undefined) return null;
84
+ // The version lives in a catalog, or comes from a git/workspace reference, the dependency upgrade does not edit.
85
+ if (declared.startsWith('catalog:') || UNRESOLVABLE_REFERENCE.test(declared)) return CATALOG;
86
+ const resolution = findNodeResolutionResult(doc);
87
+ const resolved = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? []]
88
+ .find(dep => dep.name === 'next')?.resolved;
89
+ const version = resolved?.name === 'next' ? resolved.version : undefined;
90
+ if (version && valid(version) && (!validRange(declared) || satisfies(version, declared, {includePrerelease: true}))) {
91
+ return Number(version.split('.')[0]);
92
+ }
93
+ try {
94
+ return validRange(declared) ? minVersion(declared)?.major : undefined;
95
+ } catch {
96
+ return undefined;
97
+ }
98
+ }
99
+
100
+ const WEBPACK_FLAG_SCRIPT = /\bnext\s+(?:build|dev)\b[^&|;]*\s--webpack\b/;
101
+
102
+ /** Whether a script of the package.json runs `next build` or `next dev` with `--webpack`. */
103
+ function usesWebpackFlag(doc: Json.Document): boolean {
104
+ const scripts = valueAt(doc, ['scripts']);
105
+ return scripts !== undefined && isObject(scripts) && membersOf(scripts).some(m => WEBPACK_FLAG_SCRIPT.test(stringValue(m.value) ?? ''));
106
+ }
107
+
108
+ /** Scans the `package.json` files for the Next.js major of each package. */
109
+ export function scanNextjsProjects(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
110
+ return check(new RecipeRef("org.openrewrite.FindSourceFiles", {filePattern: "**/package.json"}), new class extends TreeVisitor<Tree, ExecutionContext> {
111
+ override async visit<R extends Tree>(tree: Tree): Promise<R | undefined> {
112
+ const path = (tree as { sourcePath?: string }).sourcePath?.replace(/\\/g, "/");
113
+ if (path !== undefined && tree.kind === Json.Kind.Document && isPackageJson(path)) {
114
+ const {major, lockMajor} = nextMajor(tree as Json.Document);
115
+ if (major === null) return tree as R;
116
+ const dir = dirName(path);
117
+ acc.majors.set(dir, major === CATALOG ? undefined : major);
118
+ if (lockMajor !== undefined) acc.lockMajors.set(dir, lockMajor);
119
+ if (usesWebpackFlag(tree as Json.Document)) acc.webpackScripts.add(dir);
120
+ if (major === CATALOG) acc.unresolvable.add(dir);
121
+ }
122
+ return tree as R;
123
+ }
124
+ });
125
+ }
126
+
127
+ /** Marks the source files of the packages whose Next.js major satisfies the test. A major that cannot be read is `undefined`. */
128
+ function markProjects(acc: NextjsProjects, test: (major: number | undefined, unresolvable: boolean) => boolean, resolved = false): Promise<TreeVisitor<any, ExecutionContext>> {
129
+ return check(new RecipeRef("org.openrewrite.FindSourceFiles", {filePattern: SOURCE_FILES}), new class extends TreeVisitor<Tree, ExecutionContext> {
130
+ override async visit<R extends Tree>(tree: Tree): Promise<R | undefined> {
131
+ const path = (tree as { sourcePath?: string }).sourcePath?.replace(/\\/g, "/");
132
+ if (path === undefined || tree.kind === undefined) return tree as R;
133
+ const major = resolved ? acc.resolvedMajorOf(path) : acc.majorOf(path);
134
+ return major !== null && test(major, acc.isUnresolvable(path)) ? foundSearchResult(tree) as R : tree as R;
135
+ }
136
+ });
137
+ }
138
+
139
+ /**
140
+ * A file belongs to the nearest `package.json` above it that declares `next`, so a monorepo with several
141
+ * Next.js majors is judged package by package. A package whose `next` version is a `catalog:`, git or workspace
142
+ * reference is left alone, because the dependency upgrade cannot edit it and a code change would run on an unchanged
143
+ * Next.js. A version that cannot be read otherwise (`latest`) is treated as older, because the recipe was asked for explicitly: such a project is
144
+ * migrated even when it is already on the target major, so check its `next` version first. Files outside any package that
145
+ * declares `next` are not marked, so shared libraries of a monorepo that sit in a package without `next` are left alone.
146
+ *
147
+ * @see https://nextjs.org/docs/app/guides/upgrading
148
+ */
149
+ export class FindNextjsProjectsBelow extends ScanningRecipe<NextjsProjects> {
150
+ readonly name = "io.moderne.nextjs.search.find-projects-below-nextjs-major";
151
+ readonly displayName = "Find files of projects on a Next.js version older than a major";
152
+ readonly description = "Marks every file in a package whose `next` dependency is older than the given major. Use it as a precondition so that an upgrade recipe leaves projects already on that major, or later, unchanged.";
153
+
154
+ @Option({
155
+ displayName: "Major version",
156
+ description: "Files of projects whose `next` major is lower than this one are marked.",
157
+ example: "16"
158
+ })
159
+ belowMajor!: number;
160
+
161
+ constructor(options: { belowMajor: number }) {
162
+ super(options);
163
+ }
164
+
165
+ initialValue(): NextjsProjects {
166
+ return new NextjsProjects();
167
+ }
168
+
169
+ async scanner(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
170
+ return scanNextjsProjects(acc);
171
+ }
172
+
173
+ async editorWithData(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
174
+ const below = Number(this.belowMajor);
175
+ return markProjects(acc, (major, unresolvable) => !unresolvable && (major === undefined || major < below));
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Marks every file of a project whose `next` is the given major or later, judged by the version the lock file
181
+ * resolved: a declared range such as `^16.0.0` that the lock file resolves to 15.5.9 does not count. Used as a precondition after a dependency upgrade, it makes a recipe run only where the upgrade landed:
182
+ * the scan of the next cycle sees the edited `package.json`, and a project whose upgrade was rejected stays unmarked.
183
+ *
184
+ * A `next` version that cannot be read (`latest`, a `catalog:` entry, or a git/workspace reference) is not marked, since nothing shows that the upgrade landed.
185
+ *
186
+ * @see https://nextjs.org/docs/app/guides/upgrading
187
+ */
188
+ export class FindNextjsProjectsAtLeast extends ScanningRecipe<NextjsProjects> {
189
+ readonly name = "io.moderne.nextjs.search.find-projects-at-least-nextjs-major";
190
+ readonly displayName = "Find files of projects on a Next.js version of a major or later";
191
+ readonly description = "Marks every file in a package whose `next` dependency, as resolved by the lock file, is at the given major or later. Use it as a precondition for changes that only work on that Next.js version, so that they wait for a dependency upgrade that is still being rejected.";
192
+
193
+ @Option({
194
+ displayName: "Major version",
195
+ description: "Files of projects whose `next` major is this one or higher are marked.",
196
+ example: "16"
197
+ })
198
+ atLeastMajor!: number;
199
+
200
+ constructor(options: { atLeastMajor: number }) {
201
+ super(options);
202
+ }
203
+
204
+ initialValue(): NextjsProjects {
205
+ return new NextjsProjects();
206
+ }
207
+
208
+ async scanner(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
209
+ return scanNextjsProjects(acc);
210
+ }
211
+
212
+ async editorWithData(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
213
+ const atLeast = Number(this.atLeastMajor);
214
+ return markProjects(acc, major => major !== undefined && major >= atLeast, true);
215
+ }
216
+ }
@@ -0,0 +1,225 @@
1
+ import {check, Column, DataTable, ExecutionContext, foundSearchResult, not, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {importedModule, importedNames} from "../nextjs13/next-modules";
5
+ import {isObject, NEXT_CONFIG_FILE, propName} from "../nextjs-config/next-config";
6
+ import {NextjsProjects, scanNextjsProjects} from "./find-nextjs-projects-below";
7
+ import {treesOfType} from "../util/java-recipe-proxy";
8
+
9
+ type Obj = J.NewClass;
10
+
11
+ /** The name of an object member written as a property (`webpack: ...`) or as a method shorthand (`webpack() {}`). */
12
+ function memberName(node: J): string | undefined {
13
+ return node.kind === J.Kind.MethodDeclaration ? (node as J.MethodDeclaration).name.simpleName : propName(node);
14
+ }
15
+
16
+ function hasMember(obj: Obj, name: string): boolean {
17
+ return obj.body!.statements.some(s => memberName(s.element) === name);
18
+ }
19
+
20
+ /** Marks the named member of a config object, however it is written, with a search result; a no-op mark leaves the object as it was, so a second cycle makes no further change. */
21
+ function markMember(obj: Obj, name: string, mark: (node: J) => J): Obj {
22
+ const statements = obj.body!.statements.map(s => {
23
+ if (memberName(s.element) !== name) return s;
24
+ const marked = mark(s.element);
25
+ return marked === s.element ? s : {...s, element: marked};
26
+ });
27
+ return statements.some((s, i) => s !== obj.body!.statements[i]) ? {...obj, body: {...obj.body!, statements}} as Obj : obj;
28
+ }
29
+
30
+ /** `next.config.*` plugins known to add their own `webpack` option, keyed by the module `require`d or imported. */
31
+ const WEBPACK_PLUGINS: Record<string, string> = {
32
+ 'next-pwa': "`next-pwa` adds its own `webpack` config to generate the service worker, and has no documented Turbopack equivalent. The service worker it generates will not run when Next.js 16 builds with Turbopack unless a `turbopack` option is also added.",
33
+ };
34
+
35
+ const TURBOPACK_ADVICE = "Next.js 16 builds with Turbopack by default and refuses to start when a `webpack` config has no matching `turbopack` option. Use the documented Turbopack equivalent when there is one (see nextjs.org/docs/app/api-reference/config/next-config-js/turbopack), for example `turbopack: { rules: { '*.svg': { loaders: ['@svgr/webpack'], as: '*.js' } } }` for `@svgr/webpack`; otherwise add an empty `turbopack: {}` so the build can start, knowing the webpack customization itself will not run under Turbopack.";
36
+
37
+ class UpgradeIssueRow {
38
+ @Column({displayName: "File path", description: "The file with the issue"})
39
+ filePath!: string;
40
+
41
+ @Column({displayName: "Issue", description: "What needs attention"})
42
+ issue!: string;
43
+
44
+ @Column({displayName: "Next.js version", description: "The Next.js major that made the change"})
45
+ version!: number;
46
+
47
+ @Column({displayName: "Advice", description: "What to do about it"})
48
+ advice!: string;
49
+ }
50
+
51
+ /** The Next.js packages, and the issues without a search result of their own that earlier cycles already reported. */
52
+ class IssuesAccumulator extends NextjsProjects {
53
+ readonly reported = new Set<string>();
54
+
55
+ /** True the first time a file reports the issue, so that later cycles do not add the same row again. */
56
+ firstReport(path: string, issue: string): boolean {
57
+ const key = `${path}\n${issue}`;
58
+ if (this.reported.has(key)) return false;
59
+ this.reported.add(key);
60
+ return true;
61
+ }
62
+ }
63
+
64
+ /** Imported modules that need attention, by module. */
65
+ const MODULES: Record<string, [number, string, string]> = {
66
+ 'next/legacy/image': [13, 'import of `next/legacy/image`', 'Deprecated in Next.js 16. Move to `next/image`, which has no `layout` or `objectFit` props: use `fill`, `sizes` and `style`.'],
67
+ 'next/future/image': [13, 'import of `next/future/image`', 'Removed in Next.js 13. Import `next/image` instead.'],
68
+ '@next/font/google': [13, 'import of `@next/font/google`', 'Removed in Next.js 14. Import `next/font/google` instead.'],
69
+ '@next/font/local': [13, 'import of `@next/font/local`', 'Removed in Next.js 14. Import `next/font/local` instead.'],
70
+ 'next/amp': [13, 'import of `next/amp`', 'AMP support was removed in Next.js 16.'],
71
+ };
72
+
73
+ /** Imported members of `next/cache` or `react-dom` that need attention. */
74
+ const MEMBERS: Record<string, [number, string, string]> = {
75
+ 'next/cache#unstable_noStore': [15, '`unstable_noStore`', 'Deprecated in Next.js 15. Use `await connection()` from `next/server`.'],
76
+ 'next/cache#unstable_cache': [16, '`unstable_cache`', 'Cache Components replaces it with `use cache` and `cacheLife`, in Next.js 16. It still works, so move when the app adopts Cache Components.'],
77
+ 'next/headers#UnsafeUnwrappedCookies': [16, '`UnsafeUnwrappedCookies` from `next/headers`', 'The temporary synchronous access cast of Next.js 15 is gone in Next.js 16. Await the call: make the server component async, or read the value in a parent and pass it down.'],
78
+ 'next/headers#UnsafeUnwrappedHeaders': [16, '`UnsafeUnwrappedHeaders` from `next/headers`', 'The temporary synchronous access cast of Next.js 15 is gone in Next.js 16. Await the call: make the server component async, or read the value in a parent and pass it down.'],
79
+ 'next/headers#UnsafeUnwrappedDraftMode': [16, '`UnsafeUnwrappedDraftMode` from `next/headers`', 'The temporary synchronous access cast of Next.js 15 is gone in Next.js 16. Await the call: make the server component async, or read the value in a parent and pass it down.'],
80
+ 'react-dom#useFormState': [15, '`useFormState` from `react-dom`', 'Renamed to `useActionState` from `react` for React 19.'],
81
+ };
82
+
83
+ /** Next config options that need attention, by dotted path. */
84
+ const CONFIG: Record<string, [number, string, string]> = {
85
+ 'experimental.ppr': [16, '`experimental.ppr`', 'Removed in Next.js 16. Adopt Cache Components with `cacheComponents: true` and Suspense boundaries.'],
86
+ 'eslint': [16, '`eslint` option', '`next build` no longer runs ESLint in Next.js 16, so the option is removed. Run ESLint in CI.'],
87
+ 'serverRuntimeConfig': [16, '`serverRuntimeConfig`', 'Removed in Next.js 16. Read environment variables instead.'],
88
+ 'publicRuntimeConfig': [16, '`publicRuntimeConfig`', 'Removed in Next.js 16. Use `NEXT_PUBLIC_` environment variables.'],
89
+ 'i18n': [13, '`i18n` option', 'Only matters when routes move to the App Router, which has no built-in `i18n` routing. Use middleware or proxy routing and a library such as `next-intl` then.'],
90
+ 'experimental.runtime': [13, '`experimental.runtime`', 'Set `runtime` on the route segment instead.'],
91
+ 'images.domains': [14, '`images.domains`', 'Deprecated in Next.js 14 and 16. Use `images.remotePatterns` (see the images-domains-to-remote-patterns recipe).'],
92
+ };
93
+
94
+ /**
95
+ * @see https://nextjs.org/docs/app/guides/upgrading/version-16
96
+ */
97
+ export class FindNextjsUpgradeIssues extends ScanningRecipe<IssuesAccumulator> {
98
+ readonly name = "io.moderne.nextjs.search.find-nextjs-upgrade-issues";
99
+ readonly displayName = "Find code that needs attention in a Next.js upgrade";
100
+ readonly description = "Finds deprecated and removed Next.js APIs and `next.config.*` options that the upgrade recipes do not change, such as `next/legacy/image`, `unstable_cache`, `legacyBehavior`, `experimental.ppr` and the `runtime` of `proxy`. Reports the Next.js major that changed each one and what to do. Does not change code.";
101
+
102
+ private dataTable = new DataTable<UpgradeIssueRow>(
103
+ "io.moderne.nextjs.table.NextjsUpgradeIssues",
104
+ "Next.js upgrade issues",
105
+ "Code and configuration that needs a manual change for a Next.js upgrade.",
106
+ UpgradeIssueRow
107
+ );
108
+
109
+ initialValue(): IssuesAccumulator {
110
+ return new IssuesAccumulator();
111
+ }
112
+
113
+ async scanner(acc: IssuesAccumulator): Promise<TreeVisitor<any, ExecutionContext>> {
114
+ return scanNextjsProjects(acc);
115
+ }
116
+
117
+ // HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
118
+ // host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
119
+ override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
120
+ return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
121
+ }
122
+
123
+ async editorWithData(acc: IssuesAccumulator): Promise<TreeVisitor<any, ExecutionContext>> {
124
+ const dataTable = this.dataTable;
125
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
126
+ private path = '';
127
+ private isConfig = false;
128
+ private keys: string[] = [];
129
+ private objDepth = 0;
130
+ private turbopackSeen = false;
131
+ private webpackPlugin: string | undefined;
132
+ /** A package whose scripts pass `--webpack` keeps building with webpack on Next.js 16, so its webpack config is not an issue. */
133
+ private optedIntoWebpack = false;
134
+
135
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
136
+ this.path = cu.sourcePath.replace(/\\/g, '/');
137
+ this.isConfig = NEXT_CONFIG_FILE.test(this.path);
138
+ this.keys = [];
139
+ this.objDepth = 0;
140
+ this.turbopackSeen = false;
141
+ this.webpackPlugin = undefined;
142
+ this.optedIntoWebpack = acc.usesWebpackFlag(this.path);
143
+ const visited = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
144
+ if (this.isConfig && this.webpackPlugin && !this.turbopackSeen && !this.optedIntoWebpack && acc.firstReport(this.path, this.webpackPlugin)) {
145
+ dataTable.insertRow(ctx, {
146
+ filePath: this.path, version: 16,
147
+ issue: `\`${this.webpackPlugin}\` plugin adds a \`webpack\` config`,
148
+ advice: WEBPACK_PLUGINS[this.webpackPlugin]
149
+ });
150
+ }
151
+ return visited;
152
+ }
153
+
154
+ override async visitNewClass(newClass: J.NewClass, ctx: ExecutionContext): Promise<J | undefined> {
155
+ if (!this.isConfig) return super.visitNewClass(newClass, ctx);
156
+ const root = this.objDepth === 0;
157
+ this.objDepth++;
158
+ const visited = await super.visitNewClass(newClass, ctx) as Obj;
159
+ this.objDepth--;
160
+ if (!root || !isObject(visited)) return visited;
161
+ if (hasMember(visited, 'turbopack')) this.turbopackSeen = true;
162
+ if (hasMember(visited, 'webpack') && !hasMember(visited, 'turbopack') && !this.optedIntoWebpack) {
163
+ const issue = '`webpack` config with no `turbopack` option';
164
+ const marked = markMember(visited, 'webpack', node => foundSearchResult(node, `Next.js 16: ${issue}`));
165
+ if (marked !== visited) dataTable.insertRow(ctx, {filePath: this.path, issue, version: 16, advice: TURBOPACK_ADVICE});
166
+ return marked;
167
+ }
168
+ return visited;
169
+ }
170
+
171
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
172
+ const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
173
+ if (!this.isConfig || visited.select || visited.name.simpleName !== 'require') return visited;
174
+ const arg = visited.arguments.elements[0]?.element as any;
175
+ const name = arg?.kind === J.Kind.Literal && typeof arg.value === 'string' ? arg.value : undefined;
176
+ if (name && WEBPACK_PLUGINS[name]) this.webpackPlugin = name;
177
+ return visited;
178
+ }
179
+
180
+ private report<T extends J>(tree: T, ctx: ExecutionContext, [version, issue, advice]: [number, string, string]): T {
181
+ const marked = foundSearchResult(tree, `Next.js ${version}: ${issue}`) as T;
182
+ // A node that already carries the marker was reported by an earlier cycle
183
+ if (marked !== tree) dataTable.insertRow(ctx, {filePath: this.path, issue, version, advice});
184
+ return marked;
185
+ }
186
+
187
+ protected override async visitImportDeclaration(jsImport: JS.Import, ctx: ExecutionContext): Promise<J | undefined> {
188
+ const imp = await super.visitImportDeclaration(jsImport, ctx) as JS.Import;
189
+ const module = importedModule(imp);
190
+ if (!module) return imp;
191
+ if (this.isConfig && WEBPACK_PLUGINS[module]) this.webpackPlugin = module;
192
+ if (MODULES[module]) return this.report(imp, ctx, MODULES[module]);
193
+ if (module.startsWith('next/dist/')) return this.report(imp, ctx, [15, `import of the internal module \`${module}\``, 'Internal modules are not part of the public API and can fail to resolve in newer Next.js or with Turbopack. Use the documented export, for example `next/headers`; in a client file read the data on the server and pass it down.']);
194
+ const hit = importedNames(imp).map(n => MEMBERS[`${module}#${n}`]).find(m => m);
195
+ return hit ? this.report(imp, ctx, hit) : imp;
196
+ }
197
+
198
+ override async visitVariable(variable: J.VariableDeclarations.NamedVariable, ctx: ExecutionContext): Promise<J | undefined> {
199
+ const v = await super.visitVariable(variable, ctx) as J.VariableDeclarations.NamedVariable;
200
+ const init = v.initializer?.element as any;
201
+ if (isIdentifier(v.name) && v.name.simpleName === 'runtime' && init?.kind === J.Kind.Literal) {
202
+ if (init.value === 'experimental-edge') return this.report(v, ctx, [15, '`runtime = \'experimental-edge\'`', 'Deprecated in Next.js 15. Use `runtime = \'edge\'`.']);
203
+ if (init.value === 'edge' && /(^|\/)(proxy|middleware)\.[cm]?[jt]s$/.test(this.path)) return this.report(v, ctx, [16, '`runtime = \'edge\'` in a proxy file', '`proxy` runs on the Node.js runtime only. Keep `middleware.ts` for the edge runtime or remove the `runtime` export.']);
204
+ }
205
+ return v;
206
+ }
207
+
208
+ protected override async visitJsxAttribute(attribute: any, ctx: ExecutionContext): Promise<J | undefined> {
209
+ const a = await super.visitJsxAttribute(attribute, ctx) as any;
210
+ return isIdentifier(a.key) && a.key.simpleName === 'legacyBehavior'
211
+ ? this.report(a, ctx, [16, '`legacyBehavior` on `Link`', 'Deprecated in Next.js 16. Remove the `<a>` child (see the new-link recipe).']) : a;
212
+ }
213
+
214
+ protected override async visitPropertyAssignment(prop: JS.PropertyAssignment, ctx: ExecutionContext): Promise<J | undefined> {
215
+ const name = this.isConfig ? propName(prop) : undefined;
216
+ if (name === undefined) return super.visitPropertyAssignment(prop, ctx);
217
+ this.keys.push(name);
218
+ const visited = await super.visitPropertyAssignment(prop, ctx) as JS.PropertyAssignment;
219
+ const key = this.keys.join('.');
220
+ this.keys.pop();
221
+ return CONFIG[key] ? this.report(visited, ctx, CONFIG[key]) : visited;
222
+ }
223
+ });
224
+ }
225
+ }
@@ -0,0 +1,110 @@
1
+ import {check, Column, DataTable, ExecutionContext, foundSearchResult, not, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {importedModule} from "../nextjs13/next-modules";
5
+ import {NextjsProjects, scanNextjsProjects} from "./find-nextjs-projects-below";
6
+ import {nearestRoot} from "../util/package-json";
7
+ import {treesOfType} from "../util/java-recipe-proxy";
8
+
9
+ class PagesRouterRow {
10
+ @Column({displayName: "File path", description: "The Pages Router file"})
11
+ filePath!: string;
12
+
13
+ @Column({displayName: "Kind", description: "`page`, `api route`, `_app`, `_document`, `_error`, `404` or `500`"})
14
+ kind!: string;
15
+
16
+ @Column({displayName: "Data fetching", description: "The data fetching functions the file uses, comma separated"})
17
+ dataFetching!: string;
18
+
19
+ @Column({displayName: "Router features", description: "Pages Router only modules the file imports, such as `next/router`, `next/head` or `next/document`"})
20
+ routerFeatures!: string;
21
+
22
+ @Column({displayName: "Effort", description: "`low` for a static page, `medium` for a page with data fetching, `high` for a custom `_app`, `_document` or `getInitialProps`"})
23
+ effort!: string;
24
+ }
25
+
26
+ const DATA_FETCHING = ['getServerSideProps', 'getStaticProps', 'getStaticPaths', 'getInitialProps'];
27
+ const ROUTER_MODULES = new Set(['next/router', 'next/head', 'next/document', 'next/amp', 'next/legacy/image']);
28
+ const PAGES_FILE = /^(?:src\/)?pages\/(.+)\.[cm]?[jt]sx?$/;
29
+
30
+ /** The path below the nearest package that declares `next`; a `pages` folder only counts there, not in `src/components/pages` or in a package without `next`. */
31
+ function pathInPackage(path: string, projects: NextjsProjects): string | undefined {
32
+ const owner = nearestRoot(new Set(projects.majors.keys()), path);
33
+ return owner === undefined ? undefined : owner === '' ? path : path.substring(owner.length + 1);
34
+ }
35
+
36
+ /** The Pages Router file kind for a path under `pages/`. */
37
+ export function pagesKind(relative: string): string | undefined {
38
+ if (/^api\//.test(relative)) return 'api route';
39
+ if (/^(_app|_document|_error|404|500)$/.test(relative)) return relative;
40
+ if (/\.(test|spec)$/.test(relative) || /(^|\/)(__tests__|__mocks__)\//.test(relative)) return undefined;
41
+ return 'page';
42
+ }
43
+
44
+ /**
45
+ * @see https://nextjs.org/docs/app/guides/migrating/app-router-migration
46
+ */
47
+ export class FindPagesRouterCandidates extends ScanningRecipe<NextjsProjects> {
48
+ readonly name = "io.moderne.nextjs.search.find-pages-router-candidates";
49
+ readonly displayName = "Find Pages Router files to migrate to the App Router";
50
+ readonly description = "Lists the files under `pages/` with their kind, data fetching functions and Pages Router only imports, and how much effort a move to the App Router takes. Does not change code.";
51
+
52
+ private dataTable = new DataTable<PagesRouterRow>(
53
+ "io.moderne.nextjs.table.PagesRouterCandidates",
54
+ "Pages Router files",
55
+ "Pages Router files with the features that decide how much work their move to the App Router is.",
56
+ PagesRouterRow
57
+ );
58
+
59
+ initialValue(): NextjsProjects {
60
+ return new NextjsProjects();
61
+ }
62
+
63
+ async scanner(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
64
+ return scanNextjsProjects(acc);
65
+ }
66
+
67
+ // HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
68
+ // host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
69
+ override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
70
+ return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
71
+ }
72
+
73
+ async editorWithData(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
74
+ const dataTable = this.dataTable;
75
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
76
+ protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
77
+ const inPackage = pathInPackage(cu.sourcePath.replace(/\\/g, '/'), acc);
78
+ const match = inPackage === undefined ? null : PAGES_FILE.exec(inPackage);
79
+ const kind = match ? pagesKind(match[1]) : undefined;
80
+ if (!kind) return cu;
81
+
82
+ const fetching = new Set<string>();
83
+ const modules = new Set<string>();
84
+ const scan = new class extends JavaScriptVisitor<ExecutionContext> {
85
+ override async visitIdentifier(identifier: J.Identifier, c: ExecutionContext): Promise<J | undefined> {
86
+ if (DATA_FETCHING.includes(identifier.simpleName)) fetching.add(identifier.simpleName);
87
+ return super.visitIdentifier(identifier, c);
88
+ }
89
+
90
+ protected override async visitImportDeclaration(jsImport: JS.Import, c: ExecutionContext): Promise<J | undefined> {
91
+ const module = importedModule(jsImport);
92
+ if (module && ROUTER_MODULES.has(module)) modules.add(module);
93
+ return super.visitImportDeclaration(jsImport, c);
94
+ }
95
+ }();
96
+ await scan.visit(cu, ctx);
97
+
98
+ const effort = kind === '_app' || kind === '_document' || fetching.has('getInitialProps') ? 'high'
99
+ : fetching.size > 0 || modules.has('next/router') ? 'medium' : 'low';
100
+ dataTable.insertRow(ctx, {
101
+ filePath: cu.sourcePath, kind, dataFetching: [...fetching].join(', '),
102
+ routerFeatures: [...modules].join(', '), effort
103
+ });
104
+ const first = cu.statements[0];
105
+ const marked = first && foundSearchResult(first.element as any, `Pages Router ${kind}, effort ${effort}`);
106
+ return marked && marked !== first.element ? {...cu, statements: [{...first, element: marked}, ...cu.statements.slice(1)]} as JS.CompilationUnit : cu;
107
+ }
108
+ });
109
+ }
110
+ }