@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.
- package/dist/index.d.ts +37 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +146 -2
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts +2 -8
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/shared.js +21 -53
- package/dist/migration/cra-to-vite/shared.js.map +1 -1
- package/dist/nextjs-config/config-recipes.d.ts +90 -0
- package/dist/nextjs-config/config-recipes.d.ts.map +1 -0
- package/dist/nextjs-config/config-recipes.js +222 -0
- package/dist/nextjs-config/config-recipes.js.map +1 -0
- package/dist/nextjs-config/next-config.d.ts +25 -0
- package/dist/nextjs-config/next-config.d.ts.map +1 -0
- package/dist/nextjs-config/next-config.js +199 -0
- package/dist/nextjs-config/next-config.js.map +1 -0
- package/dist/nextjs-search/find-nextjs-projects-below.d.ts +37 -0
- package/dist/nextjs-search/find-nextjs-projects-below.d.ts.map +1 -0
- package/dist/nextjs-search/find-nextjs-projects-below.js +196 -0
- package/dist/nextjs-search/find-nextjs-projects-below.js.map +1 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts +18 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.d.ts.map +1 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.js +269 -0
- package/dist/nextjs-search/find-nextjs-upgrade-issues.js.map +1 -0
- package/dist/nextjs-search/find-pages-router-candidates.d.ts +14 -0
- package/dist/nextjs-search/find-pages-router-candidates.d.ts.map +1 -0
- package/dist/nextjs-search/find-pages-router-candidates.js +136 -0
- package/dist/nextjs-search/find-pages-router-candidates.js.map +1 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts +16 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.d.ts.map +1 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.js +125 -0
- package/dist/nextjs-search/mark-pending-nextjs-upgrade.js.map +1 -0
- package/dist/nextjs13/new-link.d.ts +8 -0
- package/dist/nextjs13/new-link.d.ts.map +1 -0
- package/dist/nextjs13/new-link.js +82 -0
- package/dist/nextjs13/new-link.js.map +1 -0
- package/dist/nextjs13/next-image-to-legacy-image.d.ts +8 -0
- package/dist/nextjs13/next-image-to-legacy-image.d.ts.map +1 -0
- package/dist/nextjs13/next-image-to-legacy-image.js +103 -0
- package/dist/nextjs13/next-image-to-legacy-image.js.map +1 -0
- package/dist/nextjs13/next-modules.d.ts +18 -0
- package/dist/nextjs13/next-modules.d.ts.map +1 -0
- package/dist/nextjs13/next-modules.js +127 -0
- package/dist/nextjs13/next-modules.js.map +1 -0
- package/dist/nextjs14/metadata-to-viewport-export.d.ts +8 -0
- package/dist/nextjs14/metadata-to-viewport-export.d.ts.map +1 -0
- package/dist/nextjs14/metadata-to-viewport-export.js +223 -0
- package/dist/nextjs14/metadata-to-viewport-export.js.map +1 -0
- package/dist/nextjs14/next-og-import.d.ts +8 -0
- package/dist/nextjs14/next-og-import.d.ts.map +1 -0
- package/dist/nextjs14/next-og-import.js +29 -0
- package/dist/nextjs14/next-og-import.js.map +1 -0
- package/dist/nextjs15/add-vercel-functions.d.ts +17 -0
- package/dist/nextjs15/add-vercel-functions.d.ts.map +1 -0
- package/dist/nextjs15/add-vercel-functions.js +86 -0
- package/dist/nextjs15/add-vercel-functions.js.map +1 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts +11 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.d.ts.map +1 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js +62 -0
- package/dist/nextjs15/app-dir-runtime-config-experimental-edge.js.map +1 -0
- package/dist/nextjs15/app-router.d.ts +26 -0
- package/dist/nextjs15/app-router.d.ts.map +1 -0
- package/dist/nextjs15/app-router.js +302 -0
- package/dist/nextjs15/app-router.js.map +1 -0
- package/dist/nextjs15/async-params.d.ts +8 -0
- package/dist/nextjs15/async-params.d.ts.map +1 -0
- package/dist/nextjs15/async-params.js +484 -0
- package/dist/nextjs15/async-params.js.map +1 -0
- package/dist/nextjs15/async-request-apis.d.ts +8 -0
- package/dist/nextjs15/async-request-apis.d.ts.map +1 -0
- package/dist/nextjs15/async-request-apis.js +204 -0
- package/dist/nextjs15/async-request-apis.js.map +1 -0
- package/dist/nextjs15/fetch-cache-defaults.d.ts +8 -0
- package/dist/nextjs15/fetch-cache-defaults.d.ts.map +1 -0
- package/dist/nextjs15/fetch-cache-defaults.js +160 -0
- package/dist/nextjs15/fetch-cache-defaults.js.map +1 -0
- package/dist/nextjs15/next-request-geo-ip.d.ts +10 -0
- package/dist/nextjs15/next-request-geo-ip.d.ts.map +1 -0
- package/dist/nextjs15/next-request-geo-ip.js +71 -0
- package/dist/nextjs15/next-request-geo-ip.js.map +1 -0
- package/dist/nextjs15/route-handler-cache-defaults.d.ts +8 -0
- package/dist/nextjs15/route-handler-cache-defaults.d.ts.map +1 -0
- package/dist/nextjs15/route-handler-cache-defaults.js +231 -0
- package/dist/nextjs15/route-handler-cache-defaults.js.map +1 -0
- package/dist/nextjs16/middleware-to-proxy.d.ts +16 -0
- package/dist/nextjs16/middleware-to-proxy.d.ts.map +1 -0
- package/dist/nextjs16/middleware-to-proxy.js +159 -0
- package/dist/nextjs16/middleware-to-proxy.js.map +1 -0
- package/dist/nextjs16/next-lint-to-eslint.d.ts +9 -0
- package/dist/nextjs16/next-lint-to-eslint.d.ts.map +1 -0
- package/dist/nextjs16/next-lint-to-eslint.js +60 -0
- package/dist/nextjs16/next-lint-to-eslint.js.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr-config.d.ts +9 -0
- package/dist/nextjs16/remove-experimental-ppr-config.d.ts.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr-config.js +17 -0
- package/dist/nextjs16/remove-experimental-ppr-config.js.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr.d.ts +8 -0
- package/dist/nextjs16/remove-experimental-ppr.d.ts.map +1 -0
- package/dist/nextjs16/remove-experimental-ppr.js +67 -0
- package/dist/nextjs16/remove-experimental-ppr.js.map +1 -0
- package/dist/nextjs16/revalidate-tag-profile.d.ts +8 -0
- package/dist/nextjs16/revalidate-tag-profile.d.ts.map +1 -0
- package/dist/nextjs16/revalidate-tag-profile.js +46 -0
- package/dist/nextjs16/revalidate-tag-profile.js.map +1 -0
- package/dist/nextjs16/stable-cache-apis.d.ts +8 -0
- package/dist/nextjs16/stable-cache-apis.d.ts.map +1 -0
- package/dist/nextjs16/stable-cache-apis.js +29 -0
- package/dist/nextjs16/stable-cache-apis.js.map +1 -0
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +50 -13
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +1 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -1
- package/dist/util/java-recipe-proxy.js +8 -5
- package/dist/util/java-recipe-proxy.js.map +1 -1
- package/dist/util/package-json.d.ts +11 -0
- package/dist/util/package-json.d.ts.map +1 -0
- package/dist/util/package-json.js +46 -0
- package/dist/util/package-json.js.map +1 -0
- package/package.json +2 -2
- package/src/index.ts +123 -0
- package/src/migration/cra-to-vite/shared.ts +3 -42
- package/src/nextjs-config/config-recipes.ts +219 -0
- package/src/nextjs-config/next-config.ts +190 -0
- package/src/nextjs-search/find-nextjs-projects-below.ts +216 -0
- package/src/nextjs-search/find-nextjs-upgrade-issues.ts +225 -0
- package/src/nextjs-search/find-pages-router-candidates.ts +110 -0
- package/src/nextjs-search/mark-pending-nextjs-upgrade.ts +131 -0
- package/src/nextjs13/new-link.ts +57 -0
- package/src/nextjs13/next-image-to-legacy-image.ts +71 -0
- package/src/nextjs13/next-modules.ts +93 -0
- package/src/nextjs14/metadata-to-viewport-export.ts +224 -0
- package/src/nextjs14/next-og-import.ts +19 -0
- package/src/nextjs15/add-vercel-functions.ts +78 -0
- package/src/nextjs15/app-dir-runtime-config-experimental-edge.ts +38 -0
- package/src/nextjs15/app-router.ts +316 -0
- package/src/nextjs15/async-params.ts +487 -0
- package/src/nextjs15/async-request-apis.ts +213 -0
- package/src/nextjs15/fetch-cache-defaults.ts +141 -0
- package/src/nextjs15/next-request-geo-ip.ts +49 -0
- package/src/nextjs15/route-handler-cache-defaults.ts +189 -0
- package/src/nextjs16/middleware-to-proxy.ts +146 -0
- package/src/nextjs16/next-lint-to-eslint.ts +43 -0
- package/src/nextjs16/remove-experimental-ppr-config.ts +15 -0
- package/src/nextjs16/remove-experimental-ppr.ts +39 -0
- package/src/nextjs16/revalidate-tag-profile.ts +28 -0
- package/src/nextjs16/stable-cache-apis.ts +20 -0
- package/src/react19/replace-default-props.ts +65 -27
- package/src/util/java-recipe-proxy.ts +9 -3
- package/src/util/package-json.ts +43 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import {and, check, ExecutionContext, not, Option, randomId, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {hasSourcePath, isVendoredOrBundled, JavaScriptParser, JavaScriptVisitor, JS, walk} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Comment, isIdentifier, isTextComment, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {NextjsProjects, scanNextjsProjects} from "./find-nextjs-projects-below";
|
|
5
|
+
import {middlewareFile} from "../nextjs16/middleware-to-proxy";
|
|
6
|
+
import {NEXT_CONFIG_FILE} from "../nextjs-config/next-config";
|
|
7
|
+
import {treesOfType} from "../util/java-recipe-proxy";
|
|
8
|
+
import {importedModule} from "../nextjs13/next-modules";
|
|
9
|
+
|
|
10
|
+
/** Text every comment of this recipe starts with, so that a later run can find it again. */
|
|
11
|
+
const TAG = "TODO(nextjs-upgrade)";
|
|
12
|
+
|
|
13
|
+
/** The file Next.js reads as middleware, or as proxy once renamed. */
|
|
14
|
+
const isMiddlewareFile = (path: string, projects: NextjsProjects) =>
|
|
15
|
+
middlewareFile(path.replace(/proxy(\.[cm]?[jt]s)$/, "middleware$1"), projects) !== undefined;
|
|
16
|
+
|
|
17
|
+
/** Files of the Next.js 13 marker: the source files that `next/link` is imported in (a `.js` file can hold JSX too). */
|
|
18
|
+
const LINK_FILES = "**/*.{js,jsx,ts,tsx}";
|
|
19
|
+
const CONFIG_FILES = "**/{next.config,middleware,proxy}.{js,cjs,mjs,ts,cts,mts}";
|
|
20
|
+
|
|
21
|
+
const jsxName = (tag: any): string | undefined => isIdentifier(tag?.openName?.element) ? tag.openName.element.simpleName : undefined;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Whether the file has a `next/link` `Link` with a single `<a>` child that the Next.js 13 rewrite would remove:
|
|
25
|
+
* the Link rewrite skips a `legacyBehavior` link, so does this.
|
|
26
|
+
*/
|
|
27
|
+
function hasLinkWithAnchorChild(cu: JS.CompilationUnit): boolean {
|
|
28
|
+
const binding = cu.statements
|
|
29
|
+
.map(s => s.element as any)
|
|
30
|
+
.find(st => st.kind === JS.Kind.Import && importedModule(st) === 'next/link')?.importClause?.name?.element.simpleName as string | undefined;
|
|
31
|
+
if (!binding) return false;
|
|
32
|
+
let found = false;
|
|
33
|
+
walk(cu, node => {
|
|
34
|
+
const tag = node as any;
|
|
35
|
+
if (found || tag.kind !== JS.Kind.JsxTag || jsxName(tag) !== binding) return !found;
|
|
36
|
+
const hasLegacy = tag.attributes.some((a: any) => a.element.kind === JS.Kind.JsxAttribute && isIdentifier(a.element.key) && a.element.key.simpleName === 'legacyBehavior');
|
|
37
|
+
const content = (tag.children ?? []).filter((c: any) => !(c.kind === J.Kind.Literal && typeof c.value === 'string' && c.value.trim() === ''));
|
|
38
|
+
if (!hasLegacy && content.length === 1 && content[0].kind === JS.Kind.JsxTag && jsxName(content[0]) === 'a') found = true;
|
|
39
|
+
return !found;
|
|
40
|
+
});
|
|
41
|
+
return found;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Whether the comment is this recipe's for the given major: the markers of the majors 13, 15 and 16 share files and must not remove each other's. */
|
|
45
|
+
const isOurs = (c: Comment, major: number) => isTextComment(c) &&
|
|
46
|
+
c.text.includes(TAG) && c.text.includes(`the Next.js ${major} changes to this file`);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Several changes of a Next.js major only work on that version: the new config options and the `proxy` file name are
|
|
50
|
+
* ignored, without an error, by the version before. The recipes for them run only where `next` is already on the major,
|
|
51
|
+
* so a project whose dependency upgrade is rejected keeps the old names. This recipe says so in the files, instead of
|
|
52
|
+
* leaving the project quietly half migrated.
|
|
53
|
+
*
|
|
54
|
+
* It judges by the `next` version the lock file resolved: an edit of `package.json` does not change the lock file, so
|
|
55
|
+
* a project whose upgrade lands in this run still looks old, and the comment is added. The next run, after an install,
|
|
56
|
+
* sees the new version and removes it. A project that is on the major already has the comment removed.
|
|
57
|
+
* A version that cannot be read (`latest`) is left alone.
|
|
58
|
+
*
|
|
59
|
+
* The comment says both ways out, since a landed edit and a blocked one look alike until the dependencies are installed.
|
|
60
|
+
*
|
|
61
|
+
* For major 13 the comment goes only in files the `Link` rewrite of Next.js 13 would edit: a `.js`, `.jsx`, `.ts` or `.tsx` file that
|
|
62
|
+
* imports `next/link` and has a `Link` with a single `<a>` child and no `legacyBehavior`. The config and middleware
|
|
63
|
+
* files are not marked for 13. A declarative wrapper can filter on `**\/{package.json,*.js,*.jsx,*.ts,*.tsx}`.
|
|
64
|
+
*
|
|
65
|
+
* @see https://nextjs.org/docs/app/guides/upgrading
|
|
66
|
+
*/
|
|
67
|
+
export class MarkPendingNextjsUpgrade extends ScanningRecipe<NextjsProjects> {
|
|
68
|
+
readonly name = "io.moderne.nextjs.search.mark-pending-nextjs-upgrade";
|
|
69
|
+
readonly displayName = "Mark Next.js changes that wait for the dependency upgrade";
|
|
70
|
+
readonly description = "Adds a `TODO(nextjs-upgrade)` comment to `next.config.*` and `middleware.*` of a project whose `next` is older than the given major, because the dependency upgrade did not land and the changes of that major were not applied. For major 13 the comment goes in the `.js`, `.jsx`, `.ts` and `.tsx` files whose `next/link` `Link` still has an `<a>` child. Removes the comment where `next` has reached the major.";
|
|
71
|
+
|
|
72
|
+
@Option({
|
|
73
|
+
displayName: "Major version",
|
|
74
|
+
description: "The Next.js major the project is being upgraded to.",
|
|
75
|
+
example: "16"
|
|
76
|
+
})
|
|
77
|
+
major!: number;
|
|
78
|
+
|
|
79
|
+
constructor(options: { major: number }) {
|
|
80
|
+
super(options);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
initialValue(): NextjsProjects {
|
|
84
|
+
return new NextjsProjects();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async scanner(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
88
|
+
return scanNextjsProjects(acc);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
|
|
92
|
+
// host no edit gate and the host would send the editor every tree, including images and lock files whose markers
|
|
93
|
+
// this side cannot decode (openrewrite/rewrite#9734)
|
|
94
|
+
override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
95
|
+
return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async editorWithData(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
99
|
+
const target = Number(this.major);
|
|
100
|
+
// One text for both cases: in the cycle that edits package.json the scan has not seen the edit yet, and the lock
|
|
101
|
+
// file only catches up with an install, so the recipe cannot tell a landed edit from a blocked one.
|
|
102
|
+
const text = ` ${TAG}: the Next.js ${target} changes to this file were not applied, because the project still resolves Next.js ${target - 1} or older. ` +
|
|
103
|
+
`If the dependency upgrade landed, install the dependencies and run the Next.js ${target} recipe again; otherwise find what blocks it (often an npm peer dependency conflict on react or react-dom).`;
|
|
104
|
+
// The comments are parsed once; each file gets a copy with its own id
|
|
105
|
+
const parsed = new Map<string, Promise<any>>();
|
|
106
|
+
const commentWithFreshId = async (content: string) => {
|
|
107
|
+
if (!parsed.has(content)) parsed.set(content, new JavaScriptParser().parseOne({text: `//${content}
|
|
108
|
+
export {};
|
|
109
|
+
`, sourcePath: "todo.ts"}).then(cu => (cu as JS.CompilationUnit).prefix.comments[0]));
|
|
110
|
+
return {...await parsed.get(content), id: randomId()};
|
|
111
|
+
};
|
|
112
|
+
// The Next.js 13 change that needs the new version is the `Link` rewrite; from 15 on it is the config and proxy changes
|
|
113
|
+
const linkRewrite = target === 13;
|
|
114
|
+
return check(and(hasSourcePath(linkRewrite ? LINK_FILES : CONFIG_FILES), not(isVendoredOrBundled())), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
115
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
116
|
+
const path = cu.sourcePath.replace(/\\/g, "/");
|
|
117
|
+
if (!linkRewrite && !NEXT_CONFIG_FILE.test(path) && !isMiddlewareFile(path, acc)) return cu;
|
|
118
|
+
const major = acc.resolvedMajorOf(path);
|
|
119
|
+
if (major === null || major === undefined) return cu;
|
|
120
|
+
const comments = cu.prefix.comments;
|
|
121
|
+
const ours = comments.filter(c => isOurs(c, target));
|
|
122
|
+
if (major >= target) {
|
|
123
|
+
return ours.length ? {...cu, prefix: {...cu.prefix, comments: comments.filter(c => !ours.includes(c))}} as JS.CompilationUnit : cu;
|
|
124
|
+
}
|
|
125
|
+
if (ours.length) return cu;
|
|
126
|
+
if (linkRewrite && !hasLinkWithAnchorChild(cu)) return cu;
|
|
127
|
+
return {...cu, prefix: {...cu.prefix, comments: [await commentWithFreshId(text), ...comments]}} as JS.CompilationUnit;
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import {check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {importedModule} from "./next-modules";
|
|
5
|
+
|
|
6
|
+
function linkBinding(cu: JS.CompilationUnit): string | undefined {
|
|
7
|
+
for (const s of cu.statements) {
|
|
8
|
+
const st = s.element as any;
|
|
9
|
+
if (st.kind !== JS.Kind.Import || importedModule(st) !== 'next/link') continue;
|
|
10
|
+
const clause = (st as JS.Import).importClause;
|
|
11
|
+
if (clause?.name) return clause.name.element.simpleName;
|
|
12
|
+
// import { default as NextLink } from 'next/link'
|
|
13
|
+
for (const e of (clause?.namedBindings as any)?.elements?.elements ?? []) {
|
|
14
|
+
const spec = e.element?.specifier;
|
|
15
|
+
if (spec?.kind === JS.Kind.Alias && spec.propertyName?.element?.simpleName === 'default') return spec.alias?.simpleName;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const tagName = (tag: any): string | undefined => isIdentifier(tag?.openName?.element) ? tag.openName.element.simpleName : undefined;
|
|
22
|
+
const attributeNames = (tag: any): string[] => tag.attributes.map((a: any) => a.element.kind === JS.Kind.JsxAttribute && isIdentifier(a.element.key) ? a.element.key.simpleName : '...');
|
|
23
|
+
const isBlank = (child: any) => child.kind === J.Kind.Literal && typeof child.value === 'string' && child.value.trim() === '';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/codemods#new-link
|
|
27
|
+
*/
|
|
28
|
+
export class NewLink extends Recipe {
|
|
29
|
+
readonly name = "io.moderne.nextjs.13.new-link";
|
|
30
|
+
readonly displayName = "Remove the `<a>` child of `next/link`";
|
|
31
|
+
readonly description = "Next.js 13 made `Link` render its own `<a>`. Moves the attributes of a single `<a>` child to the `Link` and drops the child. Links with `legacyBehavior`, and children that cannot be merged, are left alone.";
|
|
32
|
+
|
|
33
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
34
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
35
|
+
private binding?: string;
|
|
36
|
+
|
|
37
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
38
|
+
this.binding = linkBinding(cu);
|
|
39
|
+
return this.binding ? super.visitJsCompilationUnit(cu, ctx) : cu;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
protected override async visitJsxTag(element: any, ctx: ExecutionContext): Promise<J | undefined> {
|
|
43
|
+
const link = await super.visitJsxTag(element, ctx) as any;
|
|
44
|
+
if (tagName(link) !== this.binding || !link.children) return link;
|
|
45
|
+
const content = link.children.filter((c: any) => !isBlank(c));
|
|
46
|
+
const child = content[0];
|
|
47
|
+
if (content.length !== 1 || child.kind !== JS.Kind.JsxTag || tagName(child) !== 'a' || !child.children) return link;
|
|
48
|
+
const linkAttrs = attributeNames(link);
|
|
49
|
+
const childAttrs = attributeNames(child);
|
|
50
|
+
if (linkAttrs.includes('legacyBehavior') || childAttrs.includes('href') || childAttrs.includes('...')
|
|
51
|
+
|| linkAttrs.includes('...') || childAttrs.some(n => linkAttrs.includes(n))) return link;
|
|
52
|
+
const kept = link.attributes.filter((a: any) => !(isIdentifier(a.element.key) && a.element.key.simpleName === 'passHref'));
|
|
53
|
+
return {...link, attributes: [...kept, ...child.attributes], children: child.children};
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import {check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS, withStringValue} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {importedModule} from "./next-modules";
|
|
5
|
+
|
|
6
|
+
/** Props of the Next.js 12 `next/image` that the new component of Next.js 13 does not have. */
|
|
7
|
+
const LEGACY_PROPS = new Set(['layout', 'objectFit', 'objectPosition', 'lazyBoundary', 'lazyRoot']);
|
|
8
|
+
|
|
9
|
+
/** The name `next/image` is bound to in the file. */
|
|
10
|
+
function imageBinding(cu: JS.CompilationUnit): string | undefined {
|
|
11
|
+
for (const s of cu.statements) {
|
|
12
|
+
const st = s.element as any;
|
|
13
|
+
if (st.kind !== JS.Kind.Import || importedModule(st) !== 'next/image') continue;
|
|
14
|
+
const clause = (st as JS.Import).importClause;
|
|
15
|
+
const name = clause?.name?.element;
|
|
16
|
+
// next/legacy/image has no getImageProps and the like, so an import that names values stays on next/image
|
|
17
|
+
const bindings = clause?.namedBindings as any;
|
|
18
|
+
const valueBinding = bindings && (bindings.kind !== JS.Kind.NamedImports || bindings.elements.elements.some((e: any) => !e.element.importType?.element));
|
|
19
|
+
if (name && !valueBinding) return name.simpleName;
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
class LegacyPropFinder extends JavaScriptVisitor<ExecutionContext> {
|
|
25
|
+
found = false;
|
|
26
|
+
constructor(private readonly binding: string) { super(); }
|
|
27
|
+
|
|
28
|
+
protected override async visitJsxTag(tag: any, ctx: ExecutionContext): Promise<J | undefined> {
|
|
29
|
+
const name = tag.openName?.element;
|
|
30
|
+
if (isIdentifier(name) && name.simpleName === this.binding) {
|
|
31
|
+
for (const a of tag.attributes) {
|
|
32
|
+
const key = a.element.key;
|
|
33
|
+
if (a.element.kind === JS.Kind.JsxAttribute && isIdentifier(key) && LEGACY_PROPS.has(key.simpleName)) this.found = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return super.visitJsxTag(tag, ctx);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/codemods#next-image-to-legacy-image
|
|
42
|
+
*/
|
|
43
|
+
export class NextImageToLegacyImage extends Recipe {
|
|
44
|
+
readonly name = "io.moderne.nextjs.13.next-image-to-legacy-image";
|
|
45
|
+
readonly displayName = "Use `next/legacy/image` for the old `next/image` props";
|
|
46
|
+
readonly description = "Imports `next/legacy/image` instead of `next/image` in files that pass `layout`, `objectFit`, `objectPosition`, `lazyBoundary` or `lazyRoot`, which the `next/image` of Next.js 13 does not have. Other files stay on `next/image`, the new component, whose markup and styles differ from Next.js 12 even without these props. An import that also names a value from `next/image` is left alone.";
|
|
47
|
+
|
|
48
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
49
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
50
|
+
private legacy = false;
|
|
51
|
+
|
|
52
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
53
|
+
const binding = imageBinding(cu);
|
|
54
|
+
this.legacy = false;
|
|
55
|
+
if (binding) {
|
|
56
|
+
const finder = new LegacyPropFinder(binding);
|
|
57
|
+
await finder.visit(cu, ctx);
|
|
58
|
+
this.legacy = finder.found;
|
|
59
|
+
}
|
|
60
|
+
return this.legacy ? super.visitJsCompilationUnit(cu, ctx) : cu;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
protected override async visitImportDeclaration(jsImport: JS.Import, ctx: ExecutionContext): Promise<J | undefined> {
|
|
64
|
+
const imp = await super.visitImportDeclaration(jsImport, ctx) as JS.Import;
|
|
65
|
+
if (!this.legacy || importedModule(imp) !== 'next/image') return imp;
|
|
66
|
+
const spec = imp.moduleSpecifier!;
|
|
67
|
+
return {...imp, moduleSpecifier: {...spec, element: withStringValue(spec.element as J.Literal, 'next/legacy/image')}} as JS.Import;
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS, withStringValue} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
|
|
5
|
+
/** The module an import declaration names, when it is a plain string literal. */
|
|
6
|
+
export function importedModule(imp: JS.Import): string | undefined {
|
|
7
|
+
const spec = imp.moduleSpecifier?.element as any;
|
|
8
|
+
return spec?.kind === J.Kind.Literal && typeof spec.value === 'string' ? spec.value : undefined;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** The `jest` functions whose first argument names a module. */
|
|
12
|
+
const JEST_MODULE_CALLS = new Set(['mock', 'doMock', 'unmock', 'dontMock', 'requireActual', 'requireMock', 'createMockFromModule', 'setMock']);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Rewrites the module a file loads, in `import` and `export ... from` declarations, `require(...)` and `import(...)`
|
|
16
|
+
* calls, and `jest.mock(...)` style calls with a string literal.
|
|
17
|
+
*/
|
|
18
|
+
export function moduleRewriter(rewrite: (module: string) => string | undefined): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
19
|
+
const rewritten = (literal: any): J.Literal | undefined => {
|
|
20
|
+
if (literal?.kind !== J.Kind.Literal || typeof literal.value !== 'string') return undefined;
|
|
21
|
+
const next = rewrite(literal.value);
|
|
22
|
+
return next === undefined || next === literal.value ? undefined : withStringValue(literal, next);
|
|
23
|
+
};
|
|
24
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
25
|
+
protected override async visitImportDeclaration(jsImport: JS.Import, ctx: ExecutionContext): Promise<J | undefined> {
|
|
26
|
+
const imp = await super.visitImportDeclaration(jsImport, ctx) as JS.Import;
|
|
27
|
+
const next = rewritten(imp.moduleSpecifier?.element);
|
|
28
|
+
return next ? {...imp, moduleSpecifier: {...imp.moduleSpecifier!, element: next}} as JS.Import : imp;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
protected override async visitExportDeclaration(exportDeclaration: JS.ExportDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
|
|
32
|
+
const exp = await super.visitExportDeclaration(exportDeclaration, ctx) as JS.ExportDeclaration;
|
|
33
|
+
const next = rewritten(exp.moduleSpecifier?.element);
|
|
34
|
+
return next ? {...exp, moduleSpecifier: {...exp.moduleSpecifier!, element: next}} as JS.ExportDeclaration : exp;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
protected override async visitFunctionCall(functionCall: JS.FunctionCall, ctx: ExecutionContext): Promise<J | undefined> {
|
|
38
|
+
const call = await super.visitFunctionCall(functionCall, ctx) as JS.FunctionCall;
|
|
39
|
+
const callee = call.function?.element as any;
|
|
40
|
+
const first = call.arguments.elements[0];
|
|
41
|
+
const next = isIdentifier(callee) && callee.simpleName === 'import' && first ? rewritten(first.element) : undefined;
|
|
42
|
+
if (!next) return call;
|
|
43
|
+
return {...call, arguments: {...call.arguments, elements: [{...first, element: next}, ...call.arguments.elements.slice(1)]}} as JS.FunctionCall;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
protected override async visitMethodInvocation(methodInvocation: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
47
|
+
const call = await super.visitMethodInvocation(methodInvocation, ctx) as J.MethodInvocation;
|
|
48
|
+
const select = call.select?.element as any;
|
|
49
|
+
const name = call.name.simpleName;
|
|
50
|
+
const loadsModule = select ? isIdentifier(select) && select.simpleName === 'jest' && JEST_MODULE_CALLS.has(name) : name === 'require';
|
|
51
|
+
const first = call.arguments.elements[0];
|
|
52
|
+
const next = loadsModule && first ? rewritten(first.element) : undefined;
|
|
53
|
+
if (!next) return call;
|
|
54
|
+
return {...call, arguments: {...call.arguments, elements: [{...first, element: next}, ...call.arguments.elements.slice(1)]}} as J.MethodInvocation;
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/codemods#built-in-next-font
|
|
61
|
+
*/
|
|
62
|
+
export class BuiltInNextFont extends Recipe {
|
|
63
|
+
readonly name = "io.moderne.nextjs.13.built-in-next-font";
|
|
64
|
+
readonly displayName = "Use the built-in `next/font`";
|
|
65
|
+
readonly description = "Next.js 13.2 built `@next/font` into `next` as `next/font`, and Next.js 14 removed the package. Rewrites `@next/font/google` and `@next/font/local` in `import` and `export ... from` declarations, `require()` and `import()` calls with a string literal, and `jest.mock()` style calls. Removing the `@next/font` dependency is a separate step.";
|
|
66
|
+
|
|
67
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
68
|
+
return moduleRewriter(m => /^@next\/font(\/(google|local))?$/.test(m) ? m.replace('@next/font', 'next/font') : undefined);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-13
|
|
74
|
+
*/
|
|
75
|
+
export class NextFutureImageToImage extends Recipe {
|
|
76
|
+
readonly name = "io.moderne.nextjs.13.next-future-image";
|
|
77
|
+
readonly displayName = "Import `next/image` instead of `next/future/image`";
|
|
78
|
+
readonly description = "The `next/future/image` component of Next.js 12 became `next/image` in Next.js 13, and `next/future/image` was removed. Rewrites it in `import` and `export ... from` declarations, `require()` and `import()` calls with a string literal, and `jest.mock()` style calls.";
|
|
79
|
+
|
|
80
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
81
|
+
return moduleRewriter(m => m === 'next/future/image' ? 'next/image' : undefined);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The names an import declaration imports by name, so `a as b` is `a`. */
|
|
86
|
+
export function importedNames(imp: JS.Import): string[] {
|
|
87
|
+
const bindings = imp.importClause?.namedBindings as any;
|
|
88
|
+
return (bindings?.elements?.elements ?? []).flatMap((e: any) => {
|
|
89
|
+
const spec = e.element?.specifier;
|
|
90
|
+
const name = spec?.kind === J.Kind.Identifier ? spec.simpleName : spec?.propertyName?.element?.simpleName;
|
|
91
|
+
return name ? [name] : [];
|
|
92
|
+
});
|
|
93
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import {check, ExecutionContext, not, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS, maybeBind, Template} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {J, space} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {appRouterFile, isAsync, isClientFile} from "../nextjs15/app-router";
|
|
5
|
+
import {findProp, isObject, objectValue, propName, removeProp} from "../nextjs-config/next-config";
|
|
6
|
+
|
|
7
|
+
type Obj = J.NewClass;
|
|
8
|
+
|
|
9
|
+
/** The `metadata` fields Next.js 14 moved to the `viewport` export. */
|
|
10
|
+
const VIEWPORT_FIELDS = new Set(['viewport', 'colorScheme', 'themeColor']);
|
|
11
|
+
|
|
12
|
+
const isExported = (modifiers: J.Modifier[] | undefined) => !!modifiers?.some(m => m.keyword === 'export');
|
|
13
|
+
|
|
14
|
+
function exportedConstName(statement: any): string | undefined {
|
|
15
|
+
if (statement?.kind !== J.Kind.VariableDeclarations || !isExported(statement.modifiers)) return undefined;
|
|
16
|
+
return statement.variables?.[0]?.element?.name?.simpleName;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The properties of an object literal, as plain elements. */
|
|
20
|
+
function propsOf(obj: Obj): any[] {
|
|
21
|
+
return obj.body!.statements.map(s => s.element);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function movedProps(obj: Obj): string[] {
|
|
25
|
+
return propsOf(obj).map(propName).filter((n): n is string => !!n && VIEWPORT_FIELDS.has(n));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A property's prefix split in the comments on the line of the previous property (`a: 1, // about a`), which belong to
|
|
30
|
+
* that property, and the rest, which belong to this one.
|
|
31
|
+
*/
|
|
32
|
+
function splitPrefix(prefix: J.Space): { trailing: J.Space['comments'], own: J.Space } {
|
|
33
|
+
let separator = prefix.whitespace;
|
|
34
|
+
let n = 0;
|
|
35
|
+
while (n < prefix.comments.length && !separator.includes('\n')) separator = prefix.comments[n++].suffix;
|
|
36
|
+
return {trailing: prefix.comments.slice(0, n), own: {...prefix, whitespace: separator, comments: prefix.comments.slice(n)}};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The object with the viewport properties taken out. The comments on the previous property's line stay behind. */
|
|
40
|
+
function withoutViewport(obj: Obj): Obj {
|
|
41
|
+
const stripped = {...obj, body: {...obj.body!, statements: obj.body!.statements.map(s => {
|
|
42
|
+
if (!VIEWPORT_FIELDS.has(propName(s.element) ?? '')) return s;
|
|
43
|
+
const prefix = s.element.prefix as J.Space;
|
|
44
|
+
return {...s, element: {...s.element, prefix: {...prefix, comments: splitPrefix(prefix).trailing}}};
|
|
45
|
+
})}} as Obj;
|
|
46
|
+
return movedProps(obj).reduce((o, name) => removeProp(o, name), stripped);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `metadata.viewport` has to be an object literal: its fields become fields of the `viewport` export, and a string cannot. */
|
|
50
|
+
function canFlatten(obj: Obj): boolean {
|
|
51
|
+
const viewport = findProp(obj, 'viewport');
|
|
52
|
+
return !viewport || !!objectValue(viewport);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The `viewport` export's object: `themeColor` and `colorScheme` as they are, and the fields of
|
|
57
|
+
* `metadata.viewport` (`width`, `initialScale`, ...) in the place of `viewport` itself.
|
|
58
|
+
*/
|
|
59
|
+
function onlyViewport(obj: Obj): Obj {
|
|
60
|
+
const all = obj.body!.statements;
|
|
61
|
+
const keep = all.flatMap((s, index) => {
|
|
62
|
+
if (!VIEWPORT_FIELDS.has(propName(s.element) ?? '')) return [];
|
|
63
|
+
// A comment on the previous property's line stays with that property, unless it moves too
|
|
64
|
+
const previousMoves = index > 0 && VIEWPORT_FIELDS.has(propName(all[index - 1].element) ?? '');
|
|
65
|
+
const prefix = previousMoves ? s.element.prefix as J.Space : splitPrefix(s.element.prefix as J.Space).own;
|
|
66
|
+
const inner = propName(s.element) === 'viewport' ? objectValue(s.element as any) : undefined;
|
|
67
|
+
if (!inner) return [{...s, element: {...s.element, prefix}}];
|
|
68
|
+
return inner.body!.statements.map((i, n) => {
|
|
69
|
+
const innerComments = (i.element.prefix as J.Space).comments;
|
|
70
|
+
return {...i, element: {...i.element, prefix: {...prefix, comments: n === 0 ? [...prefix.comments, ...innerComments] : innerComments}}};
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
return {...obj, body: {...obj.body!, statements: keep}} as Obj;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The types of `generateMetadata`'s signature that `generateViewport` takes in their place. */
|
|
77
|
+
const VIEWPORT_TYPES: Record<string, string> = {Metadata: 'Viewport', ResolvingMetadata: 'ResolvingViewport'};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A copy of a tree that also stays where it is, with ids of its own and the `Metadata` types renamed to their
|
|
81
|
+
* `Viewport` counterparts. `renamed` collects the types the copy now names.
|
|
82
|
+
*/
|
|
83
|
+
async function copyOf<T extends J>(tree: T, renamed = new Set<string>()): Promise<T> {
|
|
84
|
+
return await new class extends JavaScriptVisitor<undefined> {
|
|
85
|
+
protected override async preVisit(t: J): Promise<J | undefined> {
|
|
86
|
+
return {...t, id: randomId()} as J;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
override async visitIdentifier(identifier: J.Identifier, p: undefined): Promise<J | undefined> {
|
|
90
|
+
const i = await super.visitIdentifier(identifier, p) as J.Identifier;
|
|
91
|
+
const type = VIEWPORT_TYPES[i.simpleName];
|
|
92
|
+
if (!type) return i;
|
|
93
|
+
renamed.add(type);
|
|
94
|
+
return {...i, simpleName: type, type: undefined, fieldType: undefined} as J.Identifier;
|
|
95
|
+
}
|
|
96
|
+
}().visit(tree, undefined) as T;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** True when a `return` is anywhere in the tree. */
|
|
100
|
+
function hasReturn(node: any, seen = new Set<object>()): boolean {
|
|
101
|
+
if (!node || typeof node !== 'object' || seen.has(node)) return false;
|
|
102
|
+
seen.add(node);
|
|
103
|
+
if (node.kind === J.Kind.Return) return true;
|
|
104
|
+
return Object.entries(node).some(([key, value]) => key !== 'type' && hasReturn(value, seen));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Literals and literal objects and arrays: a value that reads nothing from the function around it. */
|
|
108
|
+
function isStatic(expr: any): boolean {
|
|
109
|
+
switch (expr?.kind) {
|
|
110
|
+
case J.Kind.Literal:
|
|
111
|
+
return true;
|
|
112
|
+
case J.Kind.Unary:
|
|
113
|
+
return isStatic(expr.expression);
|
|
114
|
+
case J.Kind.NewArray:
|
|
115
|
+
return (expr.initializer?.elements ?? []).every((e: any) => e.element.kind === J.Kind.Empty || isStatic(e.element));
|
|
116
|
+
case J.Kind.NewClass:
|
|
117
|
+
return isObject(expr) && propsOf(expr).every(p => p?.kind === JS.Kind.PropertyAssignment && isStatic(p.initializer));
|
|
118
|
+
default:
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Handled: `export const metadata = {...}` and `export function generateMetadata(...)` whose last statement is
|
|
125
|
+
* `return {...}`. When the viewport values of `generateMetadata` are literals, `generateViewport()` takes no
|
|
126
|
+
* parameters. When they read the parameters and the body is only that `return`, `generateViewport` repeats the
|
|
127
|
+
* signature. A function that does other work and reads it in the viewport values is left alone, since copying the work
|
|
128
|
+
* would run it twice. An empty `metadata` object is removed. Files that already export `viewport` or
|
|
129
|
+
* `generateViewport`, `'use client'` files, files that are not an App Router `page` or `layout`, arrow-function
|
|
130
|
+
* exports and `metadata` objects with spreads are left alone.
|
|
131
|
+
*
|
|
132
|
+
* @see https://nextjs.org/docs/app/api-reference/functions/generate-viewport
|
|
133
|
+
*/
|
|
134
|
+
export class MetadataToViewportExport extends Recipe {
|
|
135
|
+
readonly name = "io.moderne.nextjs.14.metadata-to-viewport-export";
|
|
136
|
+
readonly displayName = "Move `metadata` viewport fields to the `viewport` export";
|
|
137
|
+
readonly description = "Next.js 14 moved `viewport`, `colorScheme` and `themeColor` out of `metadata` and `generateMetadata` into the `viewport` and `generateViewport` exports. Handles `metadata` object literals and `generateMetadata` functions whose viewport values do not depend on the rest of the function body. A `metadata` or `generateMetadata` that held only these fields is removed.";
|
|
138
|
+
|
|
139
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
140
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
141
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
142
|
+
const file = appRouterFile(cu.sourcePath);
|
|
143
|
+
if ((file !== 'page' && file !== 'layout') || isClientFile(cu)) return cu;
|
|
144
|
+
const names = new Set(cu.statements.map(s => (s.element as any).name?.simpleName ?? exportedConstName(s.element)));
|
|
145
|
+
if (names.has('viewport') || names.has('generateViewport')) return cu;
|
|
146
|
+
|
|
147
|
+
const statements: J.RightPadded<any>[] = [];
|
|
148
|
+
let changed = false;
|
|
149
|
+
for (const s of cu.statements) {
|
|
150
|
+
const st = s.element as any;
|
|
151
|
+
const result = exportedConstName(st) === 'metadata' ? await this.fromConst(st, cu) :
|
|
152
|
+
st.kind === J.Kind.MethodDeclaration && st.name.simpleName === 'generateMetadata' && isExported(st.modifiers) ? await this.fromFunction(st, cu) : undefined;
|
|
153
|
+
if (!result) {
|
|
154
|
+
statements.push(s);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
changed = true;
|
|
158
|
+
if (result.original) statements.push({...s, element: result.original});
|
|
159
|
+
statements.push({...s, element: {...result.added, prefix: result.original ? space('\n\n') : st.prefix}});
|
|
160
|
+
}
|
|
161
|
+
if (!changed) return cu;
|
|
162
|
+
const edited = {...cu, statements} as JS.CompilationUnit;
|
|
163
|
+
return edited;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private async fromConst(declaration: J.VariableDeclarations, cu: JS.CompilationUnit) {
|
|
167
|
+
const variable = declaration.variables[0].element;
|
|
168
|
+
const obj = variable.initializer?.element as Obj | undefined;
|
|
169
|
+
if (!obj || !isObject(obj) || movedProps(obj).length === 0 || propsOf(obj).some(p => p?.kind !== JS.Kind.PropertyAssignment) || !canFlatten(obj)) return undefined;
|
|
170
|
+
const typed = !!declaration.typeExpression;
|
|
171
|
+
const added = await Template.builder()
|
|
172
|
+
.code(`export const viewport${typed ? ': Viewport' : ''} = `).param(await copyOf(onlyViewport(obj))).code(';')
|
|
173
|
+
.build().apply(declaration, this.cursor);
|
|
174
|
+
if (!added) return undefined;
|
|
175
|
+
if (typed) maybeBind(this, {module: 'next', member: 'Viewport', typeOnly: true, onlyIfReferenced: false});
|
|
176
|
+
const rest = withoutViewport(obj);
|
|
177
|
+
const original = rest.body!.statements.length === 0 ? undefined :
|
|
178
|
+
{...declaration, variables: [{...declaration.variables[0], element: {...variable, initializer: {...variable.initializer!, element: rest}}}, ...declaration.variables.slice(1)]} as J.VariableDeclarations;
|
|
179
|
+
return {original, added};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private async fromFunction(method: J.MethodDeclaration, cu: JS.CompilationUnit) {
|
|
183
|
+
const statements = method.body?.statements ?? [];
|
|
184
|
+
const last = statements[statements.length - 1]?.element as any;
|
|
185
|
+
const obj = last?.kind === J.Kind.Return ? last.expression as Obj : undefined;
|
|
186
|
+
// An earlier return means other branches return metadata without these fields, and generateViewport would add them to every one
|
|
187
|
+
if (statements.slice(0, -1).some(st => hasReturn(st.element))) return undefined;
|
|
188
|
+
if (!obj || !isObject(obj) || movedProps(obj).length === 0 || propsOf(obj).some(p => p?.kind !== JS.Kind.PropertyAssignment) || !canFlatten(obj)) return undefined;
|
|
189
|
+
const moved = onlyViewport(obj);
|
|
190
|
+
const stat = isStatic(moved);
|
|
191
|
+
if (!stat && statements.length !== 1) return undefined;
|
|
192
|
+
|
|
193
|
+
// Generic type parameters on a function Next.js calls itself have no use, and `generateViewport` would not know what to do with them
|
|
194
|
+
if (!stat && method.typeParameters) return undefined;
|
|
195
|
+
|
|
196
|
+
const renamed = new Set<string>();
|
|
197
|
+
const template = Template.builder();
|
|
198
|
+
if (stat) {
|
|
199
|
+
template.code(`export function generateViewport()${method.returnTypeExpression ? ': Viewport' : ''}`);
|
|
200
|
+
if (method.returnTypeExpression) renamed.add('Viewport');
|
|
201
|
+
} else {
|
|
202
|
+
template.code(`export ${isAsync(method) ? 'async ' : ''}function generateViewport()`);
|
|
203
|
+
}
|
|
204
|
+
const generated = await template.code(' {\n return ').param(await copyOf(moved)).code(';\n}').build().apply(method, this.cursor) as J.MethodDeclaration | undefined;
|
|
205
|
+
if (!generated) return undefined;
|
|
206
|
+
// A template has no place for a parameter list, so the copied signature goes in after
|
|
207
|
+
const added = stat ? generated : {
|
|
208
|
+
...generated,
|
|
209
|
+
parameters: {...method.parameters, elements: await Promise.all(method.parameters.elements.map(async p => ({...p, element: await copyOf(p.element, renamed)})))},
|
|
210
|
+
returnTypeExpression: method.returnTypeExpression && await copyOf(method.returnTypeExpression, renamed)
|
|
211
|
+
} as J.MethodDeclaration;
|
|
212
|
+
for (const type of renamed) maybeBind(this, {module: 'next', member: type, typeOnly: true, onlyIfReferenced: false});
|
|
213
|
+
const rest = withoutViewport(obj);
|
|
214
|
+
// Nothing but the viewport fields was in it: the function has no reason to stay
|
|
215
|
+
if (propsOf(rest).length === 0 && statements.length === 1) return {original: undefined, added};
|
|
216
|
+
const original = {
|
|
217
|
+
...method,
|
|
218
|
+
body: {...method.body!, statements: [...statements.slice(0, -1), {...statements[statements.length - 1], element: {...last, expression: rest}}]}
|
|
219
|
+
} as J.MethodDeclaration;
|
|
220
|
+
return {original, added};
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {Recipe} from "@openrewrite/rewrite";
|
|
2
|
+
import {ChangeImport} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* This recipe can be replaced by an inline `change-import` entry in `nextjs-migrate.yml` once
|
|
6
|
+
* {@link https://github.com/openrewrite/rewrite/issues/10113 openrewrite/rewrite#10113} is fixed. Until then, the
|
|
7
|
+
* platform can't load a TypeScript recipe configured with options from the jar's YAML.
|
|
8
|
+
*
|
|
9
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/codemods#next-og-import
|
|
10
|
+
*/
|
|
11
|
+
export class NextOgImport extends Recipe {
|
|
12
|
+
readonly name = "io.moderne.nextjs.14.next-og-import";
|
|
13
|
+
readonly displayName: string = "Import `ImageResponse` from `next/og`";
|
|
14
|
+
readonly description: string = "Next.js 14 deprecated the `ImageResponse` export of `next/server`. Imports it from `next/og` instead, keeping an alias, and leaves the other `next/server` imports in place.";
|
|
15
|
+
|
|
16
|
+
async recipeList(): Promise<Recipe[]> {
|
|
17
|
+
return [new ChangeImport({oldModule: "next/server", oldMember: "ImageResponse", newModule: "next/og"})];
|
|
18
|
+
}
|
|
19
|
+
}
|