File size: 14,455 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 |
import type { API, ASTPath, CallExpression, Collection } from 'jscodeshift'
import {
determineClientDirective,
isFunctionType,
isMatchedFunctionExported,
turnFunctionReturnTypeToAsync,
insertReactUseImport,
isFunctionScope,
findClosetParentFunctionScope,
wrapParentheseIfNeeded,
insertCommentOnce,
NEXTJS_ENTRY_FILES,
NEXT_CODEMOD_ERROR_PREFIX,
containsReactHooksCallExpressions,
isParentUseCallExpression,
isReactHookName,
} from './utils'
import { createParserFromPath } from '../../../lib/parser'
const DYNAMIC_IMPORT_WARN_COMMENT = ` @next-codemod-error The APIs under 'next/headers' are async now, need to be manually awaited. `
function findDynamicImportsAndComment(root: Collection<any>, j: API['j']) {
let modified = false
// find all the dynamic imports of `next/headers`,
// and add a comment to the import expression to inform this needs to be manually handled
// find all the dynamic imports of `next/cookies`,
// Notice, import() is not handled as ImportExpression in current jscodeshift version,
// we need to use CallExpression to capture the dynamic imports.
const importPaths = root.find(j.CallExpression, {
callee: {
type: 'Import',
},
arguments: [{ value: 'next/headers' }],
})
importPaths.forEach((path) => {
const inserted = insertCommentOnce(
path.node,
j,
DYNAMIC_IMPORT_WARN_COMMENT
)
modified ||= inserted
})
return modified
}
export function transformDynamicAPI(
source: string,
_api: API,
filePath: string
) {
const isEntryFile = NEXTJS_ENTRY_FILES.test(filePath)
const j = createParserFromPath(filePath)
const root = j(source)
let modified = false
// Check if 'use' from 'react' needs to be imported
let needsReactUseImport = false
const insertedTypes = new Set<string>()
function isImportedInModule(
path: ASTPath<CallExpression>,
functionName: string
) {
const closestDef = j(path)
.closestScope()
.findVariableDeclarators(functionName)
return closestDef.size() === 0
}
function processAsyncApiCalls(
asyncRequestApiName: string,
originRequestApiName: string
) {
// Process each call to cookies() or headers()
root
.find(j.CallExpression, {
callee: {
type: 'Identifier',
name: asyncRequestApiName,
},
})
.forEach((path) => {
const isImportedTopLevel = isImportedInModule(path, asyncRequestApiName)
if (!isImportedTopLevel) {
return
}
let parentFunctionPath = findClosetParentFunctionScope(path, j)
// We found the parent scope is not a function
let parentFunctionNode
if (parentFunctionPath) {
if (isFunctionScope(parentFunctionPath, j)) {
parentFunctionNode = parentFunctionPath.node
} else {
const scopeNode = parentFunctionPath.node
if (
scopeNode.type === 'ReturnStatement' &&
isFunctionType(scopeNode.argument.type)
) {
parentFunctionNode = scopeNode.argument
}
}
}
const isAsyncFunction = parentFunctionNode?.async || false
const isCallAwaited = path.parentPath?.node?.type === 'AwaitExpression'
const hasChainAccess =
path.parentPath.value.type === 'MemberExpression' &&
path.parentPath.value.object === path.node
const closetScope = j(path).closestScope()
// For cookies/headers API, only transform server and shared components
if (isAsyncFunction) {
if (!isCallAwaited) {
// Add 'await' in front of cookies() call
const expr = j.awaitExpression(
// add parentheses to wrap the function call
j.callExpression(j.identifier(asyncRequestApiName), [])
)
j(path).replaceWith(wrapParentheseIfNeeded(hasChainAccess, j, expr))
modified = true
}
} else {
// Determine if the function is an export
const closetScopePath = closetScope.get()
const isEntryFileExport =
isEntryFile && isMatchedFunctionExported(closetScopePath, j)
const closestFunctionNode = closetScope.size()
? closetScopePath.node
: null
// If it's exporting a function directly, exportFunctionNode is same as exportNode
// e.g. export default function MyComponent() {}
// If it's exporting a variable declaration, exportFunctionNode is the function declaration
// e.g. export const MyComponent = function() {}
let exportFunctionNode
if (isEntryFileExport) {
if (
closestFunctionNode &&
isFunctionType(closestFunctionNode.type)
) {
exportFunctionNode = closestFunctionNode
}
} else {
// Is normal async function
exportFunctionNode = closestFunctionNode
}
let canConvertToAsync = false
// check if current path is under the default export function
if (isEntryFileExport) {
// if default export function is not async, convert it to async, and await the api call
if (!isCallAwaited && isFunctionType(exportFunctionNode.type)) {
const hasReactHooksUsage = containsReactHooksCallExpressions(
closetScopePath,
j
)
// If the scoped function is async function
if (exportFunctionNode.async === false && !hasReactHooksUsage) {
canConvertToAsync = true
exportFunctionNode.async = true
}
if (canConvertToAsync) {
const expr = j.awaitExpression(
j.callExpression(j.identifier(asyncRequestApiName), [])
)
j(path).replaceWith(
wrapParentheseIfNeeded(hasChainAccess, j, expr)
)
turnFunctionReturnTypeToAsync(closetScopePath.node, j)
modified = true
} else {
// If it's still sync function that cannot be converted to async, wrap the api call with 'use()' if needed
if (!isParentUseCallExpression(path, j)) {
j(path).replaceWith(
j.callExpression(j.identifier('use'), [
j.callExpression(j.identifier(asyncRequestApiName), []),
])
)
needsReactUseImport = true
modified = true
}
}
}
} else {
// if parent is function and it's a hook, which starts with 'use', wrap the api call with 'use()'
const parentFunction = findClosetParentFunctionScope(path, j)
if (parentFunction) {
const parentFunctionName =
parentFunction.get().node.id?.name || ''
const isParentFunctionHook = isReactHookName(parentFunctionName)
if (isParentFunctionHook && !isParentUseCallExpression(path, j)) {
j(path).replaceWith(
j.callExpression(j.identifier('use'), [
j.callExpression(j.identifier(asyncRequestApiName), []),
])
)
needsReactUseImport = true
} else {
const casted = castTypesOrAddComment(
j,
path,
originRequestApiName,
root,
filePath,
insertedTypes,
` ${NEXT_CODEMOD_ERROR_PREFIX} Manually await this call and refactor the function to be async `
)
modified ||= casted
}
} else {
const casted = castTypesOrAddComment(
j,
path,
originRequestApiName,
root,
filePath,
insertedTypes,
` ${NEXT_CODEMOD_ERROR_PREFIX} please manually await this call, codemod cannot transform due to undetermined async scope `
)
modified ||= casted
}
}
}
})
// Handle type usage of async API, e.g. `type Cookie = ReturnType<typeof cookies>`
// convert it to `type Cookie = Awaited<ReturnType<typeof cookies>>`
root
.find(j.TSTypeReference, {
typeName: {
type: 'Identifier',
name: 'ReturnType',
},
})
.forEach((path) => {
const typeParam = path.node.typeParameters?.params[0]
// Check if the ReturnType is for 'cookies'
if (
typeParam &&
j.TSTypeQuery.check(typeParam) &&
j.Identifier.check(typeParam.exprName) &&
typeParam.exprName.name === asyncRequestApiName
) {
// Replace ReturnType<typeof cookies> with Awaited<ReturnType<typeof cookies>>
const awaitedTypeReference = j.tsTypeReference(
j.identifier('Awaited'),
j.tsTypeParameterInstantiation([
j.tsTypeReference(
j.identifier('ReturnType'),
j.tsTypeParameterInstantiation([typeParam])
),
])
)
j(path).replaceWith(awaitedTypeReference)
modified = true
}
})
}
const isClientComponent = determineClientDirective(root, j)
// Only transform the valid calls in server or shared components
if (isClientComponent) return null
// Import declaration case, e.g. import { cookies } from 'next/headers'
const importedNextAsyncRequestApisMapping = findImportMappingFromNextHeaders(
root,
j
)
for (const originName in importedNextAsyncRequestApisMapping) {
const aliasName = importedNextAsyncRequestApisMapping[originName]
processAsyncApiCalls(aliasName, originName)
}
// Add import { use } from 'react' if needed and not already imported
if (needsReactUseImport) {
insertReactUseImport(root, j)
}
const commented = findDynamicImportsAndComment(root, j)
modified ||= commented
return modified ? root.toSource() : null
}
// cast to unknown first, then the specific type
const API_CAST_TYPE_MAP = {
cookies: 'UnsafeUnwrappedCookies',
headers: 'UnsafeUnwrappedHeaders',
draftMode: 'UnsafeUnwrappedDraftMode',
}
function castTypesOrAddComment(
j: API['jscodeshift'],
path: ASTPath<CallExpression>,
originRequestApiName: string,
root: Collection<any>,
filePath: string,
insertedTypes: Set<string>,
customMessage: string
) {
let modified = false
const isTsFile = filePath.endsWith('.ts') || filePath.endsWith('.tsx')
if (isTsFile) {
// if the path of call expression is already being awaited, no need to cast
if (path.parentPath?.node?.type === 'AwaitExpression') return false
/* Do type cast for headers, cookies, draftMode
import {
type UnsafeUnwrappedHeaders,
type UnsafeUnwrappedCookies,
type UnsafeUnwrappedDraftMode
} from 'next/headers'
cookies() as unknown as UnsafeUnwrappedCookies
headers() as unknown as UnsafeUnwrappedHeaders
draftMode() as unknown as UnsafeUnwrappedDraftMode
e.g. `<path>` is cookies(), convert it to `(<path> as unknown as UnsafeUnwrappedCookies)`
*/
const targetType = API_CAST_TYPE_MAP[originRequestApiName]
const newCastExpression = j.tsAsExpression(
j.tsAsExpression(path.node, j.tsUnknownKeyword()),
j.tsTypeReference(j.identifier(targetType))
)
// Replace the original expression with the new cast expression,
// also wrap () around the new cast expression.
const parent = path.parent.value
const wrappedExpression = j.parenthesizedExpression(newCastExpression)
path.replace(wrappedExpression)
// If the wrapped expression `(<expression>)` is the beginning of an expression statement,
// add a void operator to separate the statement, to avoid syntax error that being treated as part of previous statement.
// example:
// input:
// <expression>
// <expression>
// output:
// (<expression> as ...)
// void (<expression> as ...)
if (
j.ExpressionStatement.check(parent) &&
parent.expression === path.node
) {
// append a semicolon to the start of the expression statement
parent.expression = j.unaryExpression('void', parent.expression)
}
modified = true
// If cast types are not imported, add them to the import list
const importDeclaration = root.find(j.ImportDeclaration, {
source: { value: 'next/headers' },
})
if (importDeclaration.size() > 0) {
const hasImportedType =
importDeclaration
.find(j.TSTypeAliasDeclaration, {
id: { name: targetType },
})
.size() > 0 ||
importDeclaration
.find(j.ImportSpecifier, {
imported: { name: targetType },
})
.size() > 0
if (!hasImportedType && !insertedTypes.has(targetType)) {
importDeclaration
.get()
.node.specifiers.push(
j.importSpecifier(j.identifier(`type ${targetType}`))
)
insertedTypes.add(targetType)
}
}
} else {
// Otherwise for JS file, leave a message to the user to manually handle the transformation
const inserted = insertCommentOnce(path.node, j, customMessage)
modified ||= inserted
}
return modified
}
function findImportMappingFromNextHeaders(root: Collection<any>, j: API['j']) {
const mappings = {}
// Find the import declaration from 'next/headers'
root
.find(j.ImportDeclaration, { source: { value: 'next/headers' } })
.forEach((importPath) => {
const importDeclaration = importPath.node
// Iterate over the specifiers and build the mappings
importDeclaration.specifiers.forEach((specifier) => {
if (j.ImportSpecifier.check(specifier)) {
const importedName = specifier.imported.name // Original name (e.g., cookies)
const localName = specifier.local.name // Local name (e.g., myCookies or same as importedName)
// Add to the mappings
mappings[importedName] = localName
}
})
})
return mappings
}
|