@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,146 @@
|
|
|
1
|
+
import {and, check, Cursor, ExecutionContext, foundSearchResult, not, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {hasSourcePath, isVendoredOrBundled, JavaScriptVisitor, JS, leftmostExpression, referencesOf} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {NextjsProjects, scanNextjsProjects} from "../nextjs-search/find-nextjs-projects-below";
|
|
5
|
+
import {dirName, nearestRoot} from "../util/package-json";
|
|
6
|
+
import {treesOfType} from "../util/java-recipe-proxy";
|
|
7
|
+
|
|
8
|
+
const MIDDLEWARE_NAME = /^middleware\.([cm]?[jt]s)$/;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The directory and extension of the file Next.js reads as middleware: `middleware.*` in the root of the nearest
|
|
12
|
+
* package above it that declares `next`, or in that package's `src` folder. A `middleware` file anywhere else is a
|
|
13
|
+
* helper, such as `lib/middleware.ts`, and so is one in a package without `next`.
|
|
14
|
+
*/
|
|
15
|
+
export function middlewareFile(path: string, projects: NextjsProjects): { dir: string, extension: string } | undefined {
|
|
16
|
+
const normalized = path.replace(/\\/g, '/');
|
|
17
|
+
const extension = MIDDLEWARE_NAME.exec(normalized.substring(normalized.lastIndexOf('/') + 1))?.[1];
|
|
18
|
+
if (extension === undefined) return undefined;
|
|
19
|
+
const owner = nearestRoot(new Set(projects.majors.keys()), normalized);
|
|
20
|
+
if (owner === undefined) return undefined;
|
|
21
|
+
const dir = dirName(normalized);
|
|
22
|
+
return dir === owner || dir === (owner === '' ? 'src' : `${owner}/src`) ? {dir, extension} : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const MARKER = "Next.js 16: `middleware` is exported in a form that cannot be renamed safely, rename the file to `proxy.ts` and the export to `proxy` by hand";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Next.js 16 renamed Middleware to Proxy to make its network boundary clearer. The file is renamed only where Next.js
|
|
29
|
+
* reads it: at the root or in `src` of a package that declares `next`. References to the function and
|
|
30
|
+
* its export clause follow the rename. A file whose export is CommonJS or a re-export from another module is marked
|
|
31
|
+
* instead, and a file whose `config` sets `runtime` is left alone, because Proxy does not accept that option.
|
|
32
|
+
*
|
|
33
|
+
* @see https://nextjs.org/docs/app/api-reference/file-conventions/proxy#migration-to-proxy
|
|
34
|
+
*/
|
|
35
|
+
export class MiddlewareToProxy extends ScanningRecipe<NextjsProjects> {
|
|
36
|
+
readonly name = "io.moderne.nextjs.16.middleware-to-proxy";
|
|
37
|
+
readonly displayName: string = "Rename `middleware` to `proxy`";
|
|
38
|
+
readonly description: string = "Next.js 16 renamed `middleware.ts` to `proxy.ts` and its exported `middleware` function to `proxy`. " +
|
|
39
|
+
"Marks a file whose export cannot be renamed safely, and leaves a file alone whose `config` sets `runtime`, which `proxy` does not support.";
|
|
40
|
+
|
|
41
|
+
initialValue(): NextjsProjects {
|
|
42
|
+
return new NextjsProjects();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async scanner(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
46
|
+
return scanNextjsProjects(acc);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
|
|
50
|
+
// host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
|
|
51
|
+
override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
52
|
+
return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async editorWithData(acc: NextjsProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
56
|
+
return check(and(hasSourcePath("**/middleware.{js,cjs,mjs,ts,cts,mts}"), not(isVendoredOrBundled())), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
57
|
+
/** Ids of the identifiers that declare or read the top-level `middleware` binding. */
|
|
58
|
+
private references = new Set<string>();
|
|
59
|
+
|
|
60
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
61
|
+
const path = cu.sourcePath.replace(/\\/g, '/');
|
|
62
|
+
const file = middlewareFile(path, acc);
|
|
63
|
+
if (!file || configSetsRuntime(cu) || exportsRuntime(cu)) return cu;
|
|
64
|
+
if (hasUnrenamableExport(cu)) return markFirstStatement(cu);
|
|
65
|
+
const references = referencesOf(new Cursor(cu, this.cursor), 'middleware');
|
|
66
|
+
if (references.some(r => r.cursor.parent?.value?.kind === JS.Kind.PropertyAssignment && !(r.cursor.parent.value as JS.PropertyAssignment).initializer)) {
|
|
67
|
+
return markFirstStatement(cu);
|
|
68
|
+
}
|
|
69
|
+
this.references = new Set(references.map(r => r.identifier.id));
|
|
70
|
+
const visited = await super.visitJsCompilationUnit(renameExportAlias(cu), ctx) as JS.CompilationUnit;
|
|
71
|
+
return {...visited, sourcePath: `${file.dir ? file.dir + '/' : ''}proxy.${file.extension}`} as JS.CompilationUnit;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
|
|
75
|
+
const i = await super.visitIdentifier(identifier, ctx) as J.Identifier;
|
|
76
|
+
return this.references.has(i.id) && i.simpleName === 'middleware' ? {...i, simpleName: 'proxy'} as J.Identifier : i;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function markFirstStatement(cu: JS.CompilationUnit): JS.CompilationUnit {
|
|
83
|
+
const first = cu.statements[0];
|
|
84
|
+
const marked = first && foundSearchResult(first.element as any, MARKER);
|
|
85
|
+
return marked && marked !== first.element ? {...cu, statements: [{...first, element: marked}, ...cu.statements.slice(1)]} as JS.CompilationUnit : cu;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const statementOf = (s: { element: any }): any => s.element.kind === JS.Kind.ExpressionStatement ? s.element.expression : s.element;
|
|
89
|
+
|
|
90
|
+
/** CommonJS exports (`exports.x =`, `module.exports =`), and a re-export of `middleware` from another module. */
|
|
91
|
+
function hasUnrenamableExport(cu: JS.CompilationUnit): boolean {
|
|
92
|
+
return cu.statements.some(s => {
|
|
93
|
+
const st = statementOf(s);
|
|
94
|
+
if (st.kind === J.Kind.Assignment) {
|
|
95
|
+
const root = leftmostExpression(st.variable);
|
|
96
|
+
return isIdentifier(root) && ['exports', 'module'].includes(root.simpleName);
|
|
97
|
+
}
|
|
98
|
+
if (st.kind !== JS.Kind.ExportDeclaration || !st.moduleSpecifier) return false;
|
|
99
|
+
return exportSpecifiers(st).some((spec: any) => (spec.kind === JS.Kind.Alias ? spec.alias : spec).simpleName === 'middleware');
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function exportSpecifiers(exportDeclaration: any): any[] {
|
|
104
|
+
return (exportDeclaration.exportClause?.elements?.elements ?? []).map((e: any) => e.element.specifier);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** `export { handler as middleware }` becomes `export { handler as proxy }`. */
|
|
108
|
+
function renameExportAlias(cu: JS.CompilationUnit): JS.CompilationUnit {
|
|
109
|
+
return {
|
|
110
|
+
...cu, statements: cu.statements.map(s => {
|
|
111
|
+
const st = s.element as any;
|
|
112
|
+
if (st.kind !== JS.Kind.ExportDeclaration || st.moduleSpecifier || st.exportClause?.kind !== JS.Kind.NamedExports) return s;
|
|
113
|
+
const elements = st.exportClause.elements.elements.map((e: any) => {
|
|
114
|
+
const spec = e.element.specifier;
|
|
115
|
+
return spec.kind === JS.Kind.Alias && spec.alias.simpleName === 'middleware'
|
|
116
|
+
? {...e, element: {...e.element, specifier: {...spec, alias: {...spec.alias, simpleName: 'proxy'}}}} : e;
|
|
117
|
+
});
|
|
118
|
+
return {...s, element: {...st, exportClause: {...st.exportClause, elements: {...st.exportClause.elements, elements}}}};
|
|
119
|
+
})
|
|
120
|
+
} as JS.CompilationUnit;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The initializer of the top-level `const` that `export const name = ...` declares. */
|
|
124
|
+
function exportedInitializer(cu: JS.CompilationUnit, name: string): any {
|
|
125
|
+
for (const s of cu.statements) {
|
|
126
|
+
const st = statementOf(s);
|
|
127
|
+
if (st.kind !== J.Kind.VariableDeclarations) continue;
|
|
128
|
+
const v = st.variables.find((v: any) => v.element.name.simpleName === name);
|
|
129
|
+
if (v) return v.element.initializer?.element;
|
|
130
|
+
}
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Proxy does not accept a `runtime` in its `config` (https://nextjs.org/docs/app/api-reference/file-conventions/proxy#runtime). */
|
|
135
|
+
function configSetsRuntime(cu: JS.CompilationUnit): boolean {
|
|
136
|
+
const config = exportedInitializer(cu, 'config');
|
|
137
|
+
return config?.kind === J.Kind.NewClass && (config.body?.statements ?? []).some((s: any) =>
|
|
138
|
+
s.element.kind === JS.Kind.PropertyAssignment && s.element.name.element.simpleName === 'runtime');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function exportsRuntime(cu: JS.CompilationUnit): boolean {
|
|
142
|
+
return cu.statements.some(s => {
|
|
143
|
+
const decl = statementOf(s);
|
|
144
|
+
return decl?.kind === J.Kind.VariableDeclarations && decl.variables?.some((v: any) => v.element.name.simpleName === 'runtime');
|
|
145
|
+
});
|
|
146
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {check, ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {hasSourcePath} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {getMemberKeyName, Json, jsonLiteral, JsonVisitor, membersOf, setAt} from "@openrewrite/rewrite/json";
|
|
4
|
+
import {hasDependency, isPackageJson, memberObject, rootObject, stringValue} from "../util/package-json";
|
|
5
|
+
|
|
6
|
+
/** Arguments of `next lint` that `eslint` takes as they are. */
|
|
7
|
+
const PORTABLE = /^(--fix|--quiet|--max-warnings(=|\s+)\S+|--cache|--no-cache|--report-unused-disable-directives)$/;
|
|
8
|
+
|
|
9
|
+
/** Rewrites `next lint ...` to `eslint . ...`, or undefined when an argument has no ESLint equivalent. */
|
|
10
|
+
export function lintCommand(command: string): string | undefined {
|
|
11
|
+
const m = /^(.*?)\bnext lint\b(.*)$/.exec(command);
|
|
12
|
+
if (!m) return undefined;
|
|
13
|
+
const args = m[2].trim().split(/\s+(?=--)/).filter(a => a.length > 0);
|
|
14
|
+
if (/[&|;]/.test(m[2]) || !args.every(a => PORTABLE.test(a))) return undefined;
|
|
15
|
+
return `${m[1]}eslint .${args.length > 0 ? ' ' + args.join(' ') : ''}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-16#next-lint-command
|
|
20
|
+
*/
|
|
21
|
+
export class NextLintToEslint extends Recipe {
|
|
22
|
+
readonly name = "io.moderne.nextjs.16.next-lint-to-eslint";
|
|
23
|
+
readonly displayName = "Replace `next lint` with the ESLint CLI";
|
|
24
|
+
readonly description = "Next.js 16 removed `next lint`. Rewrites `next lint` in package.json scripts to `eslint .` for projects that declare `eslint`, keeping portable arguments such as `--fix`. Scripts with arguments that ESLint does not know are left alone.";
|
|
25
|
+
|
|
26
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
27
|
+
return check(hasSourcePath("**/package.json"), new class extends JsonVisitor<ExecutionContext> {
|
|
28
|
+
protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
|
|
29
|
+
const pkg = isPackageJson(doc.sourcePath) ? rootObject(doc) : undefined;
|
|
30
|
+
const scripts = pkg && hasDependency(pkg, 'eslint') ? memberObject(pkg, 'scripts') : undefined;
|
|
31
|
+
if (!scripts) return doc;
|
|
32
|
+
let updated = doc;
|
|
33
|
+
for (const m of membersOf(scripts)) {
|
|
34
|
+
const name = getMemberKeyName(m);
|
|
35
|
+
const command = stringValue(m.value);
|
|
36
|
+
const next = command === undefined ? undefined : lintCommand(command);
|
|
37
|
+
if (name !== undefined && next !== undefined) updated = setAt(updated, ['scripts', name], jsonLiteral(next));
|
|
38
|
+
}
|
|
39
|
+
return updated;
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {J} from "@openrewrite/rewrite/java";
|
|
2
|
+
import {NextConfigRecipe, removeNested} from "../nextjs-config/next-config";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-16#partial-prerendering-ppr
|
|
6
|
+
*/
|
|
7
|
+
export class RemoveExperimentalPprConfig extends NextConfigRecipe {
|
|
8
|
+
readonly name = "io.moderne.nextjs.16.remove-experimental-ppr-config";
|
|
9
|
+
readonly displayName = "Remove `experimental.ppr`";
|
|
10
|
+
readonly description = "Next.js 16 removed `experimental.ppr`. Removes the option, and `experimental` when it ends up empty. Adopting Cache Components with `cacheComponents` is left to the application.";
|
|
11
|
+
|
|
12
|
+
protected edit(root: J.NewClass): J.NewClass {
|
|
13
|
+
return removeNested(root, 'experimental', 'ppr');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
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 {APP_DIR_FILE} from "../nextjs15/app-dir-runtime-config-experimental-edge";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/codemods#remove-experimental_ppr-route-segment-config-from-app-router-pages-and-layouts
|
|
8
|
+
*/
|
|
9
|
+
export class RemoveExperimentalPpr extends Recipe {
|
|
10
|
+
readonly name = "io.moderne.nextjs.16.remove-experimental-ppr";
|
|
11
|
+
readonly displayName = "Remove the `experimental_ppr` route segment config";
|
|
12
|
+
readonly description = "Next.js 16 removed Partial Prerendering in favor of Cache Components. Removes `export const experimental_ppr = true` and `= false` from files below an `app` folder.";
|
|
13
|
+
|
|
14
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
15
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
16
|
+
private active = false;
|
|
17
|
+
|
|
18
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
19
|
+
this.active = APP_DIR_FILE.test(cu.sourcePath.replace(/\\/g, '/'));
|
|
20
|
+
if (!this.active) return cu;
|
|
21
|
+
const visited = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
|
|
22
|
+
const first = cu.statements[0];
|
|
23
|
+
// The statement after a removed first one keeps its line break: give it the removed one's prefix.
|
|
24
|
+
if (!first || visited.statements.length === 0 || visited.statements[0].element.id === first.element.id) return visited;
|
|
25
|
+
const [head, ...rest] = visited.statements;
|
|
26
|
+
return {...visited, statements: [{...head, element: {...head.element, prefix: first.element.prefix}}, ...rest]} as JS.CompilationUnit;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
override async visitVariableDeclarations(decls: J.VariableDeclarations, ctx: ExecutionContext): Promise<J | undefined> {
|
|
30
|
+
const only = decls.variables.length === 1 ? decls.variables[0].element : undefined;
|
|
31
|
+
const init = only?.initializer?.element as J.Literal | undefined;
|
|
32
|
+
if (only && isIdentifier(only.name) && only.name.simpleName === 'experimental_ppr'
|
|
33
|
+
&& decls.modifiers.some(m => m.keyword === 'export')
|
|
34
|
+
&& init?.kind === J.Kind.Literal && typeof init.value === 'boolean') return undefined;
|
|
35
|
+
return super.visitVariableDeclarations(decls, ctx);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {and, check, ExecutionContext, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS, MethodMatcher, Template, usesMethod} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {J} from "@openrewrite/rewrite/java";
|
|
4
|
+
|
|
5
|
+
const REVALIDATE_TAG_PATTERN = "next/cache revalidateTag(..)";
|
|
6
|
+
const REVALIDATE_TAG = new MethodMatcher(REVALIDATE_TAG_PATTERN);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-16#revalidatetag
|
|
10
|
+
*/
|
|
11
|
+
export class RevalidateTagProfile extends Recipe {
|
|
12
|
+
readonly name = "io.moderne.nextjs.16.revalidate-tag-profile";
|
|
13
|
+
readonly displayName = "Add a cache life profile to `revalidateTag`";
|
|
14
|
+
readonly description = "Next.js 16 deprecated `revalidateTag(tag)` with a single argument. Adds `{ expire: 0 }` as the second argument, which keeps the immediate expiration `revalidateTag(tag)` had in Next.js 15: the next request waits for fresh data. Switch a call to the `'max'` profile (stale-while-revalidate) or to `updateTag` in a Server Action where that fits better.";
|
|
15
|
+
|
|
16
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
17
|
+
return check(and(usesMethod(REVALIDATE_TAG_PATTERN), not(isVendoredOrBundled())), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
18
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
19
|
+
const m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
|
|
20
|
+
const args = m.arguments.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
|
|
21
|
+
// A spread may hold the profile as well, and appending one to it could give the call three arguments
|
|
22
|
+
if (m.select || !REVALIDATE_TAG.matches(m.methodType) || args.length !== 1 || args[0].kind === JS.Kind.Spread) return m;
|
|
23
|
+
const result = await Template.builder().code(`${m.name.simpleName}(`).param(args[0]).code(", { expire: 0 })").build().apply(m, this.cursor);
|
|
24
|
+
return result ? {...result, prefix: m.prefix} as J : m;
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {Recipe} from "@openrewrite/rewrite";
|
|
2
|
+
import {ChangeImport} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* This recipe can be replaced by two inline `change-import` entries 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/version-16
|
|
10
|
+
*/
|
|
11
|
+
export class StableCacheApis extends Recipe {
|
|
12
|
+
readonly name = "io.moderne.nextjs.16.stable-cache-apis";
|
|
13
|
+
readonly displayName: string = "Use stable `cacheLife` and `cacheTag`";
|
|
14
|
+
readonly description: string = "Next.js 16 stabilized the Cache Components APIs, so `unstable_cacheLife` and `unstable_cacheTag` from `next/cache` become `cacheLife` and `cacheTag` in imports and usages.";
|
|
15
|
+
|
|
16
|
+
async recipeList(): Promise<Recipe[]> {
|
|
17
|
+
return ["cacheLife", "cacheTag"].map(member =>
|
|
18
|
+
new ChangeImport({oldModule: "next/cache", oldMember: `unstable_${member}`, newModule: "next/cache", newMember: member}));
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -1,21 +1,11 @@
|
|
|
1
|
-
import {check, Cursor, emptyMarkers, ExecutionContext, mapAsync, not, Recipe, TreeVisitor, updateIfChanged} from "@openrewrite/rewrite";
|
|
2
|
-
import {bindingNames, isVendoredOrBundled, JavaScriptVisitor, JS, namesReferencedWithin, referencesOf} from "@openrewrite/rewrite/javascript";
|
|
3
|
-
import {Expression, isIdentifier, isTextComment, J, singleSpace,
|
|
1
|
+
import {check, Cursor, emptyMarkers, ExecutionContext, mapAsync, not, randomId, Recipe, TreeVisitor, updateIfChanged} from "@openrewrite/rewrite";
|
|
2
|
+
import {bindingNames, deconflict, isVendoredOrBundled, JavaScriptVisitor, JS, namesReferencedWithin, namesUsedIn, referencesOf, Template} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Expression, isIdentifier, isTextComment, J, singleSpace, TextComment, Type} from "@openrewrite/rewrite/java";
|
|
4
4
|
|
|
5
5
|
const DEFAULT_PROPS = 'defaultProps';
|
|
6
6
|
export const TODO = " TODO: `defaultProps` is ignored on function components in React 19; move these defaults into the parameters, see https://react.dev/blog/2024/04/25/react-19-upgrade-guide#removed-proptypes-and-defaultprops";
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
|
-
* Converts `Component.defaultProps` to ES6 default parameter values.
|
|
10
|
-
*
|
|
11
|
-
* In React 19, `defaultProps` for function components is removed.
|
|
12
|
-
* This recipe moves default values into the parameter destructuring of a function or arrow
|
|
13
|
-
* function component declared in the same scope. The assignment is deleted only when every
|
|
14
|
-
* entry was moved; otherwise the remaining entries stay, marked with a TODO. Class components
|
|
15
|
-
* keep their `defaultProps`. So does an entry whose value uses a name the props pattern also
|
|
16
|
-
* binds: a parameter default would read the prop instead of the import or constant. A component
|
|
17
|
-
* whose `defaultProps` is read elsewhere in the file keeps it too, as the read would find nothing.
|
|
18
|
-
*
|
|
19
9
|
* Before:
|
|
20
10
|
* ```tsx
|
|
21
11
|
* function Greeting({name}) {
|
|
@@ -36,7 +26,7 @@ export const TODO = " TODO: `defaultProps` is ignored on function components in
|
|
|
36
26
|
export class ReplaceDefaultProps extends Recipe {
|
|
37
27
|
readonly name = "org.openrewrite.react.19.replace-default-props";
|
|
38
28
|
readonly displayName: string = "Replace `defaultProps` with default parameter values";
|
|
39
|
-
readonly description: string = "Converts `Component.defaultProps = {...}` to ES6 default parameter values in function components declared in the same scope.
|
|
29
|
+
readonly description: string = "Converts `Component.defaultProps = {...}` to ES6 default parameter values in function components declared in the same scope. A value that uses a name a destructured prop also binds is hoisted into a module-level const, so the default can't read the prop instead. Entries that can't be moved stay in `defaultProps`, marked with a TODO, as does a component whose `defaultProps` is read elsewhere in the file, and class components are left alone. `defaultProps` for function components is removed in React 19.";
|
|
40
30
|
|
|
41
31
|
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
42
32
|
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
@@ -57,8 +47,9 @@ export class ReplaceDefaultProps extends Recipe {
|
|
|
57
47
|
}
|
|
58
48
|
}
|
|
59
49
|
|
|
50
|
+
let taken: Set<string> | undefined;
|
|
60
51
|
const replaced = new Map<J, J>();
|
|
61
|
-
const
|
|
52
|
+
const mapped = await mapAsync<Statement, Statement | Statement[]>(cu.statements, async stmt => {
|
|
62
53
|
const assignment = asDefaultPropsAssignment(stmt.element);
|
|
63
54
|
const declaration = assignment && declarations.get(assignment.componentName);
|
|
64
55
|
if (!assignment || !declaration || !isFunctionComponent(replaced.get(declaration) ?? declaration)) {
|
|
@@ -72,22 +63,36 @@ export class ReplaceDefaultProps extends Recipe {
|
|
|
72
63
|
let component = replaced.get(declaration) ?? declaration;
|
|
73
64
|
const entries = assignment.object.body!.statements;
|
|
74
65
|
const remaining: typeof entries = [];
|
|
66
|
+
const hoisted: Hoisted[] = [];
|
|
67
|
+
const hoist: Hoist = (prop, value) => {
|
|
68
|
+
const names = taken ??= new Set(namesUsedIn(cu));
|
|
69
|
+
const name = deconflict(lowerFirst(assignment.componentName) + upperFirst(prop), name => names.has(name));
|
|
70
|
+
names.add(name);
|
|
71
|
+
hoisted.push({name, value});
|
|
72
|
+
return identifier(name);
|
|
73
|
+
};
|
|
75
74
|
for (const entry of entries) {
|
|
76
75
|
const prop = entry.element as J;
|
|
77
|
-
const moved = prop.kind === JS.Kind.PropertyAssignment ? moveDefault(component, prop as JS.PropertyAssignment) : undefined;
|
|
76
|
+
const moved = prop.kind === JS.Kind.PropertyAssignment ? moveDefault(component, prop as JS.PropertyAssignment, hoist) : undefined;
|
|
78
77
|
if (moved) {
|
|
79
78
|
component = moved;
|
|
80
79
|
} else {
|
|
81
80
|
remaining.push(entry);
|
|
82
81
|
}
|
|
83
82
|
}
|
|
84
|
-
replaced.set(declaration, component);
|
|
85
83
|
|
|
84
|
+
// The consts stand where the assignment was, ahead of whatever stays of it
|
|
85
|
+
const consts = hoisted.length > 0 ? await declareConsts(hoisted, stmt, new Cursor(stmt.element, this.cursor)) : [];
|
|
86
|
+
if (!consts) {
|
|
87
|
+
return stmt;
|
|
88
|
+
}
|
|
89
|
+
replaced.set(declaration, component);
|
|
90
|
+
const afterConsts = (kept?: Statement) => consts.length === 0 ? kept : kept ? [...consts, kept] : consts;
|
|
86
91
|
if (remaining.length === 0) {
|
|
87
|
-
return
|
|
92
|
+
return afterConsts();
|
|
88
93
|
}
|
|
89
94
|
if (remaining.length === entries.length && hasTodo(assignment.assignment)) {
|
|
90
|
-
return stmt;
|
|
95
|
+
return afterConsts(stmt);
|
|
91
96
|
}
|
|
92
97
|
// The new last entry ends the list the way the old one did, trailing comma included
|
|
93
98
|
const last = entries[entries.length - 1];
|
|
@@ -99,13 +104,15 @@ export class ReplaceDefaultProps extends Recipe {
|
|
|
99
104
|
element: {...assignment.object, body: {...assignment.object.body!, statements: remaining}} as J.NewClass
|
|
100
105
|
}
|
|
101
106
|
};
|
|
102
|
-
|
|
107
|
+
const onNewLine = consts.length > 0 ? {...kept, prefix: {...kept.prefix, whitespace: lastLine(kept.prefix.whitespace)}} : kept;
|
|
108
|
+
return afterConsts({...stmt, element: withTodo(onNewLine)});
|
|
103
109
|
});
|
|
110
|
+
const statements = mapped === cu.statements ? cu.statements : mapped.flat();
|
|
104
111
|
|
|
105
112
|
return updateIfChanged(cu, {
|
|
106
113
|
statements: await mapAsync(statements, async stmt => {
|
|
107
114
|
const to = replaced.get(stmt.element);
|
|
108
|
-
return to && to !== stmt.element ? {...stmt, element: to as Statement} : stmt;
|
|
115
|
+
return to && to !== stmt.element ? {...stmt, element: to as Statement["element"]} : stmt;
|
|
109
116
|
})
|
|
110
117
|
});
|
|
111
118
|
}
|
|
@@ -195,10 +202,10 @@ function isFunctionComponent(declaration: J): boolean {
|
|
|
195
202
|
}
|
|
196
203
|
|
|
197
204
|
/** The component with the default of `prop` moved into its destructured props, or undefined when it can't be. */
|
|
198
|
-
function moveDefault(component: J, prop: JS.PropertyAssignment): J | undefined {
|
|
205
|
+
function moveDefault(component: J, prop: JS.PropertyAssignment, hoist: Hoist): J | undefined {
|
|
199
206
|
const key = prop.name.element;
|
|
200
207
|
if (!isIdentifier(key) || !prop.initializer) return undefined;
|
|
201
|
-
return updateProps(component, pattern => withDefault(pattern, key.simpleName, prop.initializer
|
|
208
|
+
return updateProps(component, pattern => withDefault(pattern, key.simpleName, prop.initializer!, hoist));
|
|
202
209
|
}
|
|
203
210
|
|
|
204
211
|
function updateProps(component: J, update: (pattern: JS.ObjectBindingPattern) => JS.ObjectBindingPattern | undefined): J | undefined {
|
|
@@ -229,8 +236,11 @@ function updateParam<T>(param: T, update: (pattern: JS.ObjectBindingPattern) =>
|
|
|
229
236
|
return updated && {...declarations, variables: [{...variable, element: {...variable.element, name: updated}}, ...declarations.variables.slice(1)]} as unknown as T;
|
|
230
237
|
}
|
|
231
238
|
|
|
232
|
-
/**
|
|
233
|
-
|
|
239
|
+
/**
|
|
240
|
+
* The pattern with `prop` defaulting to `value`, replacing a default it has: `defaultProps` wins at runtime.
|
|
241
|
+
* A value that reads a name the pattern binds goes to `hoist`, which returns what to default to instead.
|
|
242
|
+
*/
|
|
243
|
+
function withDefault(pattern: JS.ObjectBindingPattern, prop: string, value: Expression, hoist: Hoist): JS.ObjectBindingPattern | undefined {
|
|
234
244
|
const index = pattern.bindings.elements.findIndex(padded => {
|
|
235
245
|
const binding = padded.element as JS.BindingElement;
|
|
236
246
|
const name = binding.propertyName?.element ?? binding.name;
|
|
@@ -239,7 +249,9 @@ function withDefault(pattern: JS.ObjectBindingPattern, prop: string, value: Expr
|
|
|
239
249
|
if (index < 0) return undefined;
|
|
240
250
|
// The value moves from module scope into the parameter scope, where the bindings of the pattern shadow it
|
|
241
251
|
const read = namesReferencedWithin(value);
|
|
242
|
-
if (read.size > 0 && bindingNames(pattern).some(({name}) => read.has(name)))
|
|
252
|
+
if (read.size > 0 && bindingNames(pattern).some(({name}) => read.has(name))) {
|
|
253
|
+
value = hoist(prop, value);
|
|
254
|
+
}
|
|
243
255
|
const padded = pattern.bindings.elements[index];
|
|
244
256
|
const binding = padded.element as JS.BindingElement;
|
|
245
257
|
const initializer = binding.initializer;
|
|
@@ -257,13 +269,39 @@ function withDefault(pattern: JS.ObjectBindingPattern, prop: string, value: Expr
|
|
|
257
269
|
return {...pattern, bindings: {...pattern.bindings, elements}};
|
|
258
270
|
}
|
|
259
271
|
|
|
272
|
+
type Hoisted = { name: string, value: Expression };
|
|
273
|
+
type Hoist = (prop: string, value: Expression) => Expression;
|
|
274
|
+
type Statement = JS.CompilationUnit["statements"][number];
|
|
275
|
+
|
|
276
|
+
const lowerFirst = (text: string) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
277
|
+
const upperFirst = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
278
|
+
const lastLine = (whitespace: string) => /\r?\n[ \t]*$/.exec(whitespace)?.[0] ?? '\n';
|
|
279
|
+
|
|
280
|
+
function identifier(name: string): J.Identifier {
|
|
281
|
+
return {kind: J.Kind.Identifier, id: randomId(), prefix: singleSpace, markers: emptyMarkers, annotations: [], simpleName: name, type: Type.Primitive.None};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** A `const name = value;` statement per hoisted value, the first one in the place of `at`; undefined when one can't be built. */
|
|
285
|
+
async function declareConsts(hoisted: Hoisted[], at: Statement, cursor: Cursor): Promise<Statement[] | undefined> {
|
|
286
|
+
const statements: Statement[] = [];
|
|
287
|
+
const prefix = (at.element as J).prefix;
|
|
288
|
+
for (const {name, value} of hoisted) {
|
|
289
|
+
const declaration = await Template.builder().code(`const ${name} = `).param({...value, prefix: {...value.prefix, whitespace: ""}} as Expression).code(";").build()
|
|
290
|
+
.apply(at.element as J, cursor);
|
|
291
|
+
if (!declaration) return undefined;
|
|
292
|
+
const whitespace = statements.length === 0 ? prefix.whitespace : lastLine(prefix.whitespace);
|
|
293
|
+
statements.push({...at, element: {...declaration, prefix: {...prefix, whitespace, comments: []}} as J});
|
|
294
|
+
}
|
|
295
|
+
return statements;
|
|
296
|
+
}
|
|
297
|
+
|
|
260
298
|
function hasTodo(assignment: J.Assignment): boolean {
|
|
261
299
|
return assignment.prefix.comments.some(c => isTextComment(c) && c.text === TODO);
|
|
262
300
|
}
|
|
263
301
|
|
|
264
302
|
function withTodo(assignment: J.Assignment): J.Assignment {
|
|
265
303
|
if (hasTodo(assignment)) return assignment;
|
|
266
|
-
const lineStart =
|
|
304
|
+
const lineStart = lastLine(assignment.prefix.whitespace);
|
|
267
305
|
const todo: TextComment = {kind: J.Kind.TextComment, multiline: false, text: TODO, suffix: lineStart, markers: emptyMarkers};
|
|
268
306
|
return {...assignment, prefix: {...assignment.prefix, comments: [todo, ...assignment.prefix.comments]}};
|
|
269
307
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {check, Cursor, ExecutionContext, or, RecipeRef, ScanningRecipe, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
1
|
+
import {and, check, Cursor, ExecutionContext, or, RecipeRef, ScanningRecipe, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {hasSourcePath} from "@openrewrite/rewrite/javascript";
|
|
2
3
|
import {DelegatingRecipe} from "@openrewrite/rewrite/rpc";
|
|
3
4
|
|
|
4
5
|
/** The host's own tree-type gate, the one it derives for a JsonVisitor or JavaScriptVisitor. */
|
|
@@ -6,12 +7,17 @@ export const treesOfType = (type: string) => new RecipeRef("org.openrewrite.rpc.
|
|
|
6
7
|
|
|
7
8
|
// The files the dependency delegates normally send to Java.
|
|
8
9
|
const NODE_MANIFESTS = /(^|\/)(package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|pnpm-workspace\.yaml|bun\.lock)$/;
|
|
9
|
-
const NODE_MANIFEST_TREES = ["org.openrewrite.json.tree.Json", "org.openrewrite.yaml.tree.Yaml"
|
|
10
|
+
const NODE_MANIFEST_TREES = ["org.openrewrite.json.tree.Json", "org.openrewrite.yaml.tree.Yaml"];
|
|
11
|
+
// `yarn.lock` and `bun.lock` have no structured parser and come over the wire as `PlainText`, the same kind as every
|
|
12
|
+
// other unparsed file (README, LICENSE, `.env`, CSV, ...). Asking the host for every `PlainText` tree would send all
|
|
13
|
+
// of those too, so the type check is narrowed by path to just the two lock files it actually parses.
|
|
14
|
+
const PLAINTEXT_MANIFESTS = "**/{yarn.lock,bun.lock}";
|
|
10
15
|
|
|
11
16
|
// Native lock transactions also need package-manager policy, patches and hooks they must refuse.
|
|
12
17
|
const NODE_INPUTS = /(^|\/)(\.npmrc|\.yarnrc(?:\.yml)?|bunfig\.toml|\.?pnpmfile\.cjs)$|\.patch$/;
|
|
13
18
|
|
|
14
|
-
const manifestTrees = () => or(...NODE_MANIFEST_TREES.map(treesOfType)
|
|
19
|
+
export const manifestTrees = () => or(...NODE_MANIFEST_TREES.map(treesOfType),
|
|
20
|
+
and(treesOfType("org.openrewrite.text.PlainText"), hasSourcePath(PLAINTEXT_MANIFESTS)));
|
|
15
21
|
|
|
16
22
|
/** The host's gate for the manifests a dependency step reads and the JavaScript sources that decide where it adds. */
|
|
17
23
|
export const manifestAndJavaScriptTrees = () => or(...[...NODE_MANIFEST_TREES, "org.openrewrite.javascript.tree.JS"].map(treesOfType));
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {findMember, isLiteral, isObject, Json, valueAt} from "@openrewrite/rewrite/json";
|
|
2
|
+
|
|
3
|
+
export const DEPENDENCY_SECTIONS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
|
|
4
|
+
|
|
5
|
+
/** The directory of a path with no trailing slash; `''` for a root-level file. */
|
|
6
|
+
export function dirName(path: string): string {
|
|
7
|
+
const i = path.lastIndexOf("/");
|
|
8
|
+
return i < 0 ? "" : path.substring(0, i);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function baseName(path: string): string {
|
|
12
|
+
return path.substring(path.lastIndexOf("/") + 1);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The nearest of `roots` that is a directory above `path`, found by climbing its ancestors. */
|
|
16
|
+
export function nearestRoot(roots: ReadonlySet<string>, path: string): string | undefined {
|
|
17
|
+
for (let dir = dirName(path); ; dir = dirName(dir)) {
|
|
18
|
+
if (roots.has(dir)) return dir;
|
|
19
|
+
if (dir === "") return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isPackageJson(sourcePath: string): boolean {
|
|
24
|
+
return baseName(sourcePath) === "package.json" && !sourcePath.split("/").includes("node_modules");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function rootObject(doc: Json.Document): Json.Object | undefined {
|
|
28
|
+
return isObject(doc.value) ? doc.value : undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function memberObject(obj: Json.Object, name: string): Json.Object | undefined {
|
|
32
|
+
const value = findMember(obj, name)?.value;
|
|
33
|
+
return value && isObject(value) ? value : undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The string a JSON value holds, or `undefined` when it is not a string literal. */
|
|
37
|
+
export function stringValue(value: Json | undefined): string | undefined {
|
|
38
|
+
return value && isLiteral(value) && typeof value.value === "string" ? value.value : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function hasDependency(pkg: Json.Object, name: string): boolean {
|
|
42
|
+
return DEPENDENCY_SECTIONS.some(section => valueAt(pkg, [section, name]) !== undefined);
|
|
43
|
+
}
|