@openrewrite/recipes-react 0.31.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,487 @@
|
|
|
1
|
+
import {check, Cursor, emptyMarkers, ExecutionContext, foundSearchResult, not, printer, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {
|
|
3
|
+
isVendoredOrBundled,
|
|
4
|
+
JavaScriptVisitor,
|
|
5
|
+
JS,
|
|
6
|
+
maybeBind,
|
|
7
|
+
MethodMatcher,
|
|
8
|
+
namesUsedWithin,
|
|
9
|
+
Template,
|
|
10
|
+
walk
|
|
11
|
+
} from "@openrewrite/rewrite/javascript";
|
|
12
|
+
import {emptySpace, isIdentifier, J, space} from "@openrewrite/rewrite/java";
|
|
13
|
+
import {create} from "mutative";
|
|
14
|
+
import {
|
|
15
|
+
appRouterFile,
|
|
16
|
+
callsHooks,
|
|
17
|
+
exportedName,
|
|
18
|
+
FunctionLike,
|
|
19
|
+
HTTP_METHODS,
|
|
20
|
+
identifier,
|
|
21
|
+
isAsync,
|
|
22
|
+
isClientFile,
|
|
23
|
+
isFunctionLike,
|
|
24
|
+
isParamsFile,
|
|
25
|
+
makeAsync,
|
|
26
|
+
METADATA_FUNCTIONS,
|
|
27
|
+
promiseOf,
|
|
28
|
+
SELF_TERMINATED
|
|
29
|
+
} from "./app-router";
|
|
30
|
+
|
|
31
|
+
const PROPS = 'props';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Covers the default export of `page`, `layout`, `default` and the metadata image files, a page's or
|
|
35
|
+
* layout's `generateMetadata` and `generateViewport`, and the segment data a route handler takes as
|
|
36
|
+
* its second argument. Following the upgrade guide, a destructured `params` or `searchParams` is
|
|
37
|
+
* read from the props instead, awaited — or unwrapped with `use` in a client component — and the
|
|
38
|
+
* function becomes async where it was not. Their declared types become promises, in the parameter's
|
|
39
|
+
* own type or in the interface or type alias the file declares for it, and an indexed read of such
|
|
40
|
+
* a type elsewhere in the file, as `generateStaticParams` makes, reads the resolved value instead.
|
|
41
|
+
*
|
|
42
|
+
* Before:
|
|
43
|
+
* ```tsx
|
|
44
|
+
* export default async function Page({ params }: { params: { slug: string } }) {
|
|
45
|
+
* return <h1>{params.slug}</h1>
|
|
46
|
+
* }
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* After:
|
|
50
|
+
* ```tsx
|
|
51
|
+
* export default async function Page(props: { params: Promise<{ slug: string }> }) {
|
|
52
|
+
* const params = await props.params
|
|
53
|
+
* return <h1>{params.slug}</h1>
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* @see https://nextjs.org/docs/app/guides/upgrading/version-15#params--searchparams
|
|
58
|
+
*/
|
|
59
|
+
export class AsyncParams extends Recipe {
|
|
60
|
+
readonly name = "io.moderne.nextjs.15.async-params";
|
|
61
|
+
readonly displayName: string = "Await `params` and `searchParams`";
|
|
62
|
+
readonly description: string = "Next.js 15 passes `params` and `searchParams` to App Router pages, layouts, route handlers and metadata functions as promises. " +
|
|
63
|
+
"Reads a destructured `params` or `searchParams` from the props and awaits it, or unwraps it with `use` in a client component, " +
|
|
64
|
+
"and declares their types as promises. Meant for projects on Next.js 15 and React 19; run it through `UpgradeToNextjs15` when upgrading.";
|
|
65
|
+
|
|
66
|
+
async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
67
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
68
|
+
private cu!: JS.CompilationUnit;
|
|
69
|
+
/** Local interfaces and type aliases whose members become promises, with the members that do. */
|
|
70
|
+
private typesToWrap = new Map<string, Set<string>>();
|
|
71
|
+
/** The entries whose parameter is typed by one of the file's own types. */
|
|
72
|
+
private entriesOfTypes = new Set<string>();
|
|
73
|
+
|
|
74
|
+
protected override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
75
|
+
if (!isParamsFile(cu.sourcePath)) return cu;
|
|
76
|
+
this.cu = cu;
|
|
77
|
+
this.typesToWrap = new Map();
|
|
78
|
+
this.entriesOfTypes = new Set();
|
|
79
|
+
const c = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
|
|
80
|
+
if (this.typesToWrap.size === 0) return c;
|
|
81
|
+
// Declaring `params` a promise in a type that another function takes would break that function's types.
|
|
82
|
+
const shared = typesOfOtherFunctions(c, [...this.typesToWrap.keys()], this.entriesOfTypes);
|
|
83
|
+
shared.forEach(name => this.typesToWrap.delete(name));
|
|
84
|
+
return wrapDeclaredTypes(c, this.typesToWrap, shared);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
override async visitMethodDeclaration(method: J.MethodDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
|
|
88
|
+
const m = await super.visitMethodDeclaration(method, ctx) as J.MethodDeclaration;
|
|
89
|
+
return this.migrate(m);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
protected override async visitArrowFunction(arrow: JS.ArrowFunction, ctx: ExecutionContext): Promise<J | undefined> {
|
|
93
|
+
const a = await super.visitArrowFunction(arrow, ctx) as JS.ArrowFunction;
|
|
94
|
+
return this.migrate(a);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private async migrate<F extends FunctionLike>(fn: F): Promise<F> {
|
|
98
|
+
const entry = this.entry();
|
|
99
|
+
if (!entry) return fn;
|
|
100
|
+
const parameters = parametersOf(fn);
|
|
101
|
+
const parameter = parameters[entry.index]?.element;
|
|
102
|
+
if (parameter?.kind !== J.Kind.VariableDeclarations) return fn;
|
|
103
|
+
const declarations = parameter as J.VariableDeclarations;
|
|
104
|
+
if (declarations.variables.length !== 1) return fn;
|
|
105
|
+
const pattern = declarations.variables[0].element.name;
|
|
106
|
+
if (pattern.kind !== JS.Kind.ObjectBindingPattern) return fn;
|
|
107
|
+
|
|
108
|
+
const typeTree = (declarations.typeExpression as JS.TypeInfo | undefined)?.typeIdentifier;
|
|
109
|
+
const literal = typeTree?.kind === JS.Kind.TypeLiteral ? typeTree as JS.TypeLiteral : undefined;
|
|
110
|
+
const named = typeTree && isIdentifier(typeTree) ? localTypeLiteral(this.cu, typeTree.simpleName) : undefined;
|
|
111
|
+
const declaredType = literal ?? named;
|
|
112
|
+
if (declaredType && entry.members.some(member => isPromiseMember(declaredType, member, this.cu))) return fn;
|
|
113
|
+
|
|
114
|
+
const bindings = (pattern as JS.ObjectBindingPattern).bindings.elements.map(e => e.element);
|
|
115
|
+
// A binding the body never reads, as `params: _`, needs nothing awaited.
|
|
116
|
+
const read = namesUsedWithin(fn.kind === J.Kind.MethodDeclaration ? (fn as J.MethodDeclaration).body : (fn as JS.ArrowFunction).lambda.body);
|
|
117
|
+
const awaited = bindings.filter(b => entry.members.includes(bindingKey(b) ?? '') &&
|
|
118
|
+
(bindingLocal(b) === undefined || read.has(bindingLocal(b)!.simpleName)));
|
|
119
|
+
const typeMembers = declaredType ? entry.members.filter(member => memberOf(declaredType, member)) : [];
|
|
120
|
+
if (awaited.length === 0 && typeMembers.length === 0) return fn;
|
|
121
|
+
|
|
122
|
+
if (awaited.some(b => (b as JS.BindingElement).initializer)) return fn;
|
|
123
|
+
// `...rest` is read from the props, so would hold the promises that the declared names no longer take out.
|
|
124
|
+
if (bindings.some(isRest)) return fn;
|
|
125
|
+
if (awaited.some(b => isUnwrapped(fn, bindingLocal(b)))) return fn;
|
|
126
|
+
if (namesUsedWithin(fn).has(PROPS)) return fn;
|
|
127
|
+
|
|
128
|
+
let result: F = fn;
|
|
129
|
+
if (awaited.length) {
|
|
130
|
+
// A client component, or a server one calling hooks, cannot be async, so unwraps with `use`
|
|
131
|
+
// as the upgrade guide's synchronous page and layout do.
|
|
132
|
+
const useHook = !isAsync(fn) && (isClientFile(this.cu) || callsHooks(fn));
|
|
133
|
+
const use = useHook ? maybeBind(this, {module: 'react', member: 'use', onlyIfReferenced: false}) : undefined;
|
|
134
|
+
if (useHook && !use) return fn;
|
|
135
|
+
const statements: string[] = [];
|
|
136
|
+
for (const b of awaited) {
|
|
137
|
+
const target = await this.source(b.kind === JS.Kind.BindingElement && (b as JS.BindingElement).propertyName ? (b as JS.BindingElement).name : bindingLocal(b)!);
|
|
138
|
+
const read = `${PROPS}.${bindingKey(b)}`;
|
|
139
|
+
statements.push(`const ${target} = ${use ? `${use}(${read})` : `await ${read}`}`);
|
|
140
|
+
}
|
|
141
|
+
const rest = bindings.filter(b => !awaited.includes(b));
|
|
142
|
+
if (rest.length) {
|
|
143
|
+
const names = await Promise.all(rest.map(b => this.source(b)));
|
|
144
|
+
statements.push(`const { ${names.join(', ')} } = ${PROPS}`);
|
|
145
|
+
}
|
|
146
|
+
result = await this.prependStatements(result, statements);
|
|
147
|
+
result = replaceParameter(result, entry.index, identifier(PROPS, pattern.prefix));
|
|
148
|
+
if (!useHook) result = makeAsync(result);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (literal) {
|
|
152
|
+
result = replaceParameterType(result, entry.index, wrapMembers(literal, typeMembers));
|
|
153
|
+
} else if (named && typeTree && isIdentifier(typeTree)) {
|
|
154
|
+
this.entriesOfTypes.add(fn.id);
|
|
155
|
+
const members = this.typesToWrap.get(typeTree.simpleName) ?? new Set<string>();
|
|
156
|
+
typeMembers.forEach(m => members.add(m));
|
|
157
|
+
this.typesToWrap.set(typeTree.simpleName, members);
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Which parameter Next.js passes request data in, and which of its members, or undefined for any other function. */
|
|
163
|
+
private entry(): {index: number, members: string[]} | undefined {
|
|
164
|
+
const name = exportedName(this.cursor, this.cu);
|
|
165
|
+
if (!name) return undefined;
|
|
166
|
+
const file = appRouterFile(this.cu.sourcePath);
|
|
167
|
+
if (file === 'route') {
|
|
168
|
+
return HTTP_METHODS.has(name) ? {index: 1, members: ['params']} : undefined;
|
|
169
|
+
}
|
|
170
|
+
const members = file === 'page' ? ['params', 'searchParams'] : ['params'];
|
|
171
|
+
if (name === 'default') return {index: 0, members};
|
|
172
|
+
if (METADATA_FUNCTIONS.has(name) && (file === 'page' || file === 'layout')) return {index: 0, members};
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private async source(tree: J): Promise<string> {
|
|
177
|
+
return (await printer(this.cursor).print(tree)).trim();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Puts `statements` first in the function's body, giving an expression body a block to hold them. */
|
|
181
|
+
private async prependStatements<F extends FunctionLike>(fn: F, statements: string[]): Promise<F> {
|
|
182
|
+
if (fn.kind === JS.Kind.ArrowFunction && (fn as JS.ArrowFunction).lambda.body.kind !== J.Kind.Block) {
|
|
183
|
+
const arrow = fn as JS.ArrowFunction;
|
|
184
|
+
const expression = arrow.lambda.body as J;
|
|
185
|
+
const indent = indentOf(this.cursor);
|
|
186
|
+
// An arrow's block is only read as a block where the code says it is an arrow.
|
|
187
|
+
const blockArrow = await Template.builder()
|
|
188
|
+
.code(`async () => {\n${statements.map(s => `${indent} ${s};\n`).join('')}${indent} return `)
|
|
189
|
+
.param(expression)
|
|
190
|
+
.code(`;\n${indent}}`)
|
|
191
|
+
.build()
|
|
192
|
+
.apply(arrow, this.cursor) as JS.ArrowFunction;
|
|
193
|
+
return create(arrow, draft => {
|
|
194
|
+
draft.lambda.body = {...blockArrow.lambda.body, prefix: expression.prefix} as any;
|
|
195
|
+
}) as F;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const body = bodyOf(fn)!;
|
|
199
|
+
const first = body.statements[0];
|
|
200
|
+
const terminator = terminatedLike(body, this.cu);
|
|
201
|
+
const bodyCursor = new Cursor(body, this.cursor);
|
|
202
|
+
const generated: J.RightPadded<J>[] = [];
|
|
203
|
+
// A first statement on the line of the brace is no start of a line: the new ones then share it, each ended by a semicolon.
|
|
204
|
+
const sameLine = first !== undefined && !hasLineBreak(first.element.prefix);
|
|
205
|
+
for (const text of statements) {
|
|
206
|
+
const anchor = first?.element ?? body;
|
|
207
|
+
const statement = await Template.builder().code(text).build().apply(anchor as J, new Cursor(anchor, bodyCursor));
|
|
208
|
+
generated.push({
|
|
209
|
+
kind: J.Kind.RightPadded,
|
|
210
|
+
element: {...statement!, prefix: sameLine ? space(' ') : lineStartOf(first?.element.prefix)} as J,
|
|
211
|
+
after: terminator?.after ?? emptySpace,
|
|
212
|
+
markers: sameLine ? {...emptyMarkers, markers: [{kind: J.Markers.Semicolon, id: randomId()}]} : terminator?.markers ?? emptyMarkers,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const newBody = create(body, draft => {
|
|
216
|
+
draft.statements.unshift(...generated as any);
|
|
217
|
+
});
|
|
218
|
+
if (fn.kind === J.Kind.MethodDeclaration) {
|
|
219
|
+
return {...fn, body: newBody} as F;
|
|
220
|
+
}
|
|
221
|
+
return create(fn as JS.ArrowFunction, draft => {
|
|
222
|
+
draft.lambda.body = newBody as any;
|
|
223
|
+
}) as F;
|
|
224
|
+
}
|
|
225
|
+
}());
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function indentOf(cursor: Cursor): string {
|
|
230
|
+
for (let c: Cursor | undefined = cursor; c; c = c.parent) {
|
|
231
|
+
const prefix = (c.value as J | undefined)?.prefix?.whitespace;
|
|
232
|
+
if (prefix && prefix.includes('\n')) return prefix.substring(prefix.lastIndexOf('\n') + 1);
|
|
233
|
+
}
|
|
234
|
+
return '';
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The padding of a statement that shows whether this code ends statements with a semicolon: the
|
|
239
|
+
* first one in the body that could, looking into its nested blocks, or else the file's, or
|
|
240
|
+
* undefined where nothing shows it.
|
|
241
|
+
*/
|
|
242
|
+
function terminatedLike(body: J.Block, cu: JS.CompilationUnit): J.RightPadded<J> | undefined {
|
|
243
|
+
const telling = (statements: J.RightPadded<J>[]) => statements.find(s => !SELF_TERMINATED.has(s.element.kind));
|
|
244
|
+
let found = telling(body.statements);
|
|
245
|
+
if (!found) {
|
|
246
|
+
walk(body, node => {
|
|
247
|
+
if ((node as J).kind === J.Kind.Block) found = telling((node as J.Block).statements);
|
|
248
|
+
return found === undefined;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
return found ?? telling(cu.statements as J.RightPadded<J>[]);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function hasLineBreak(prefix: J.Space): boolean {
|
|
255
|
+
return /\n/.test(prefix.whitespace) || prefix.comments.some(c => /\n/.test(c.suffix));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** The line break and indentation a statement starts on, leaving out any comment written above it. */
|
|
259
|
+
function lineStartOf(prefix: J.Space | undefined): J.Space {
|
|
260
|
+
if (!prefix) return space('\n');
|
|
261
|
+
const last = prefix.comments.length ? prefix.comments[prefix.comments.length - 1].suffix : prefix.whitespace;
|
|
262
|
+
const at = last.lastIndexOf('\n');
|
|
263
|
+
return space(at >= 0 ? last.substring(at) : '\n');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function parametersOf(fn: FunctionLike): J.RightPadded<J>[] {
|
|
267
|
+
return fn.kind === J.Kind.MethodDeclaration
|
|
268
|
+
? (fn as J.MethodDeclaration).parameters.elements
|
|
269
|
+
: (fn as JS.ArrowFunction).lambda.parameters.parameters;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function bodyOf(fn: FunctionLike): J.Block | undefined {
|
|
273
|
+
if (fn.kind === J.Kind.MethodDeclaration) return (fn as J.MethodDeclaration).body;
|
|
274
|
+
const body = (fn as JS.ArrowFunction).lambda.body;
|
|
275
|
+
return body.kind === J.Kind.Block ? body as J.Block : undefined;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function replaceParameter<F extends FunctionLike>(fn: F, index: number, replacement: J.Identifier): F {
|
|
279
|
+
return mapParameter(fn, index, declarations => create(declarations, draft => {
|
|
280
|
+
draft.variables[0].element.name = replacement as any;
|
|
281
|
+
}));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function replaceParameterType<F extends FunctionLike>(fn: F, index: number, type: JS.TypeLiteral): F {
|
|
285
|
+
return mapParameter(fn, index, declarations => create(declarations, draft => {
|
|
286
|
+
(draft.typeExpression as any).typeIdentifier = type;
|
|
287
|
+
}));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function mapParameter<F extends FunctionLike>(fn: F, index: number, map: (d: J.VariableDeclarations) => J.VariableDeclarations): F {
|
|
291
|
+
if (fn.kind === J.Kind.MethodDeclaration) {
|
|
292
|
+
return create(fn as J.MethodDeclaration, draft => {
|
|
293
|
+
const p = draft.parameters.elements[index];
|
|
294
|
+
p.element = map(p.element as any) as any;
|
|
295
|
+
}) as F;
|
|
296
|
+
}
|
|
297
|
+
return create(fn as JS.ArrowFunction, draft => {
|
|
298
|
+
const p = draft.lambda.parameters.parameters[index];
|
|
299
|
+
p.element = map(p.element as any) as any;
|
|
300
|
+
}) as F;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function isRest(binding: J): boolean {
|
|
304
|
+
return binding.kind === JS.Kind.Spread ||
|
|
305
|
+
(binding.kind === JS.Kind.BindingElement && (binding as JS.BindingElement).name.kind === JS.Kind.Spread);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The names of `types` that a function other than the `entries` takes in a parameter. */
|
|
309
|
+
function typesOfOtherFunctions(cu: JS.CompilationUnit, types: string[], entries: Set<string>): Set<string> {
|
|
310
|
+
const shared = new Set<string>();
|
|
311
|
+
walk(cu, node => {
|
|
312
|
+
const n = node as J;
|
|
313
|
+
if (isFunctionLike(n) && !entries.has(n.id)) {
|
|
314
|
+
for (const parameter of parametersOf(n)) {
|
|
315
|
+
walk(parameter.element, inner => {
|
|
316
|
+
const t = inner as J;
|
|
317
|
+
if (isIdentifier(t) && types.includes(t.simpleName)) shared.add(t.simpleName);
|
|
318
|
+
return true;
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return true;
|
|
323
|
+
});
|
|
324
|
+
return shared;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The property a binding reads: `params` in `{ params }` and in `{ params: { slug } }`. */
|
|
328
|
+
function bindingKey(binding: J): string | undefined {
|
|
329
|
+
if (binding.kind !== JS.Kind.BindingElement) return undefined;
|
|
330
|
+
const b = binding as JS.BindingElement;
|
|
331
|
+
const key = b.propertyName?.element ?? b.name;
|
|
332
|
+
return isIdentifier(key) ? key.simpleName : undefined;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The local name a binding introduces, when it introduces a single one. */
|
|
336
|
+
function bindingLocal(binding: J): J.Identifier | undefined {
|
|
337
|
+
if (binding.kind !== JS.Kind.BindingElement) return undefined;
|
|
338
|
+
const name = (binding as JS.BindingElement).name;
|
|
339
|
+
return isIdentifier(name) ? name : undefined;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const REACT_USE = new MethodMatcher('react use(..)');
|
|
343
|
+
|
|
344
|
+
/** Whether `fn` already awaits `name` or unwraps it with `use`, as code written for Next.js 15 does. */
|
|
345
|
+
function isUnwrapped(fn: FunctionLike, name: J.Identifier | undefined): boolean {
|
|
346
|
+
if (!name) return false;
|
|
347
|
+
let found = false;
|
|
348
|
+
walk(fn, node => {
|
|
349
|
+
if (found) return false;
|
|
350
|
+
const n = node as J;
|
|
351
|
+
if (n.kind === JS.Kind.Await && isIdentifier((n as JS.Await).expression) &&
|
|
352
|
+
((n as JS.Await).expression as J.Identifier).simpleName === name.simpleName) {
|
|
353
|
+
found = true;
|
|
354
|
+
} else if (n.kind === J.Kind.MethodInvocation) {
|
|
355
|
+
const m = n as J.MethodInvocation;
|
|
356
|
+
const arg = m.arguments.elements[0]?.element;
|
|
357
|
+
if (REACT_USE.matches(m.methodType) && isIdentifier(arg) && arg.simpleName === name.simpleName) found = true;
|
|
358
|
+
}
|
|
359
|
+
return !found;
|
|
360
|
+
});
|
|
361
|
+
return found;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The object type a top-level `interface Name {}` or `type Name = {}` in the file declares. */
|
|
365
|
+
function localTypeLiteral(cu: JS.CompilationUnit, name: string): J.Block | JS.TypeLiteral | undefined {
|
|
366
|
+
for (const s of cu.statements) {
|
|
367
|
+
let statement = s.element as J;
|
|
368
|
+
if (statement.kind === JS.Kind.ExportDeclaration) {
|
|
369
|
+
statement = (statement as JS.ExportDeclaration).exportClause as J ?? statement;
|
|
370
|
+
}
|
|
371
|
+
if (statement.kind === J.Kind.ClassDeclaration) {
|
|
372
|
+
const c = statement as J.ClassDeclaration;
|
|
373
|
+
if (c.name.simpleName === name) return c.body;
|
|
374
|
+
} else if (statement.kind === JS.Kind.TypeDeclaration) {
|
|
375
|
+
const t = statement as JS.TypeDeclaration;
|
|
376
|
+
if (t.name.element.simpleName === name && t.initializer.element.kind === JS.Kind.TypeLiteral) {
|
|
377
|
+
return t.initializer.element as JS.TypeLiteral;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return undefined;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function membersBlock(type: J.Block | JS.TypeLiteral): J.Block {
|
|
385
|
+
return type.kind === JS.Kind.TypeLiteral ? (type as JS.TypeLiteral).members : type as J.Block;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function memberOf(type: J.Block | JS.TypeLiteral, name: string): J.VariableDeclarations | undefined {
|
|
389
|
+
for (const s of membersBlock(type).statements) {
|
|
390
|
+
const member = s.element as J;
|
|
391
|
+
if (member.kind !== J.Kind.VariableDeclarations) continue;
|
|
392
|
+
const declarations = member as J.VariableDeclarations;
|
|
393
|
+
const variable = declarations.variables[0]?.element.name;
|
|
394
|
+
if (variable && isIdentifier(variable) && variable.simpleName === name) return declarations;
|
|
395
|
+
}
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function isPromiseMember(type: J.Block | JS.TypeLiteral, name: string, cu: JS.CompilationUnit): boolean {
|
|
400
|
+
const member = memberOf(type, name);
|
|
401
|
+
const memberType = (member?.typeExpression as JS.TypeInfo | undefined)?.typeIdentifier;
|
|
402
|
+
return memberType !== undefined && isPromiseType(memberType, cu);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function isPromiseType(type: J, cu: JS.CompilationUnit): boolean {
|
|
406
|
+
if (type.kind === J.Kind.ParameterizedType) {
|
|
407
|
+
const clazz = (type as J.ParameterizedType).class;
|
|
408
|
+
return isIdentifier(clazz) && clazz.simpleName === 'Promise';
|
|
409
|
+
}
|
|
410
|
+
if (isIdentifier(type)) {
|
|
411
|
+
// `type Params = Promise<{ slug: string }>`
|
|
412
|
+
for (const s of cu.statements) {
|
|
413
|
+
const statement = s.element as J;
|
|
414
|
+
if (statement.kind === JS.Kind.TypeDeclaration && (statement as JS.TypeDeclaration).name.element.simpleName === type.simpleName) {
|
|
415
|
+
return isPromiseType((statement as JS.TypeDeclaration).initializer.element, cu);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Declares each of `members` as a promise of the type it declared. */
|
|
423
|
+
function wrapMembers<T extends J.Block | JS.TypeLiteral>(type: T, members: string[]): T {
|
|
424
|
+
if (members.length === 0) return type;
|
|
425
|
+
const wrapBlock = (block: J.Block) => create(block, draft => {
|
|
426
|
+
for (const s of draft.statements) {
|
|
427
|
+
const member = s.element as any;
|
|
428
|
+
if (member.kind !== J.Kind.VariableDeclarations) continue;
|
|
429
|
+
const name = member.variables[0]?.element.name;
|
|
430
|
+
if (!name || !isIdentifier(name) || !members.includes(name.simpleName)) continue;
|
|
431
|
+
const typeInfo = member.typeExpression;
|
|
432
|
+
if (typeInfo?.typeIdentifier) typeInfo.typeIdentifier = promiseOf(typeInfo.typeIdentifier);
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
if (type.kind === JS.Kind.TypeLiteral) {
|
|
436
|
+
return {...type, members: wrapBlock((type as JS.TypeLiteral).members)} as T;
|
|
437
|
+
}
|
|
438
|
+
return wrapBlock(type as J.Block) as T;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Wraps the members of the file's own types that entries take, and resolves indexed reads of them. */
|
|
442
|
+
async function wrapDeclaredTypes(cu: JS.CompilationUnit, types: Map<string, Set<string>>, shared: Set<string>): Promise<JS.CompilationUnit> {
|
|
443
|
+
const mark = <T extends J>(tree: T, name: string): T => foundSearchResult(tree,
|
|
444
|
+
`Another function in this file also takes \`${name}\`, so its \`params\` is not declared as a promise; do that and await it where it is read.`);
|
|
445
|
+
const visitor = new class extends JavaScriptVisitor<void> {
|
|
446
|
+
override async visitClassDeclaration(c: J.ClassDeclaration, p: void): Promise<J | undefined> {
|
|
447
|
+
const visited = await super.visitClassDeclaration(c, p) as J.ClassDeclaration;
|
|
448
|
+
if (shared.has(visited.name.simpleName)) return mark(visited, visited.name.simpleName);
|
|
449
|
+
const members = types.get(visited.name.simpleName);
|
|
450
|
+
return members ? {...visited, body: wrapMembers(visited.body, [...members])} as J.ClassDeclaration : visited;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
protected override async visitTypeDeclaration(t: JS.TypeDeclaration, p: void): Promise<J | undefined> {
|
|
454
|
+
const visited = await super.visitTypeDeclaration(t, p) as JS.TypeDeclaration;
|
|
455
|
+
if (shared.has(visited.name.element.simpleName)) return mark(visited, visited.name.element.simpleName);
|
|
456
|
+
const members = types.get(visited.name.element.simpleName);
|
|
457
|
+
if (!members || visited.initializer.element.kind !== JS.Kind.TypeLiteral) return visited;
|
|
458
|
+
return create(visited, draft => {
|
|
459
|
+
draft.initializer.element = wrapMembers(visited.initializer.element as JS.TypeLiteral, [...members]) as any;
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
protected override async visitIndexedAccessType(i: JS.IndexedAccessType, p: void): Promise<J | undefined> {
|
|
464
|
+
const visited = await super.visitIndexedAccessType(i, p) as JS.IndexedAccessType;
|
|
465
|
+
const objectType = visited.objectType;
|
|
466
|
+
if (!isIdentifier(objectType) || !types.has(objectType.simpleName)) return visited;
|
|
467
|
+
const parent = this.cursor.parentTree()?.value as J | undefined;
|
|
468
|
+
if (parent?.kind === J.Kind.ParameterizedType && isIdentifier((parent as J.ParameterizedType).class) &&
|
|
469
|
+
((parent as J.ParameterizedType).class as J.Identifier).simpleName === 'Awaited') {
|
|
470
|
+
return visited;
|
|
471
|
+
}
|
|
472
|
+
const key = indexKey(visited);
|
|
473
|
+
return key && types.get(objectType.simpleName)!.has(key) ? promiseOf(visited, 'Awaited') : visited;
|
|
474
|
+
}
|
|
475
|
+
}();
|
|
476
|
+
return await visitor.visit(cu, undefined) as JS.CompilationUnit;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function indexKey(i: JS.IndexedAccessType): string | undefined {
|
|
480
|
+
let found: string | undefined;
|
|
481
|
+
walk(i.indexType, node => {
|
|
482
|
+
const n = node as J;
|
|
483
|
+
if (n.kind === J.Kind.Literal && typeof (n as J.Literal).value === 'string') found = (n as J.Literal).value as string;
|
|
484
|
+
return found === undefined;
|
|
485
|
+
});
|
|
486
|
+
return found;
|
|
487
|
+
}
|