Unverified Commit b0ba92cb authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Unify TODO markers for codemods and skip adoption-only codemods for upgrade (#98560)

### Why?

Async Request API codemods can leave temporary casts that still require
application-specific repairs. Those locations need explicit markers,
while optional feature adoption needs to be distinguishable from
required version migrations.

### How?

Add `@next-codemod-error` comments to temporary `UnsafeUnwrapped*`
casts, with instructions for completing the repair. Preserve documented
ignores and avoid duplicating casts or markers when the transform runs
again. Mark generated Cache Components opt-outs with
`@next-codemod-ignore`, a removal condition and a link to the adoption
guide.

Add `upgrade --skip-adoption` to skip the Cache Components `instant =
false` transform and partial-prefetch adoption cleanup. Required
migrations and normal dependency and bundler selection keep their
existing behavior. Both adoption transforms can still be run explicitly.
parent 39f5d797
......@@ -7,3 +7,14 @@ Codemods are transformations that run on your codebase programmatically. This al
## Documentation
Visit [nextjs.org/docs/advanced-features/codemods](https://nextjs.org/docs/app/guides/upgrading/codemods) to view the documentation for this package.
## Skip optional feature adoption
`upgrade --skip-adoption` skips codemods marked as feature adoption in the
registry while keeping version migrations and normal dependency selection.
Currently this excludes `cache-components-instant-false` and the
`remove-partial-prefetch` cleanup used after adopting partial prefetching.
Both transforms can still be run explicitly.
Combine it with `--yes` for an unattended version upgrade. Without
`--skip-adoption`, the existing upgrade selections are unchanged.
......@@ -70,6 +70,11 @@ program
'Skip every interactive prompt and accept its default. Also auto-enabled when stdin is not a TTY (e.g. running under an agent or in CI).',
false
)
.option(
'--skip-adoption',
'Skip optional feature-adoption codemods while applying version migrations.',
false
)
.action(async (revision, options) => {
try {
await runUpgrade(revision, options)
......
......@@ -113,7 +113,7 @@ function resolveSemanticRevision(
export async function runUpgrade(
revision: string | undefined,
options: { verbose: boolean; yes?: boolean }
options: { verbose: boolean; yes?: boolean; skipAdoption?: boolean }
): Promise<void> {
const { verbose } = options
const nonInteractive = options.yes === true || !process.stdin.isTTY
......@@ -272,7 +272,8 @@ export async function runUpgrade(
const codemods = await suggestCodemods(
installedNextVersion,
targetNextVersion,
nonInteractive
nonInteractive,
options.skipAdoption
)
const packageManager: PackageManager = getPkgManager(cwd)
......@@ -641,7 +642,8 @@ async function suggestTurbopack(
async function suggestCodemods(
initialNextVersion: string,
targetNextVersion: string,
nonInteractive: boolean
nonInteractive: boolean,
skipAdoption = false
): Promise<string[]> {
// example:
// codemod version: 15.0.0-canary.45
......@@ -670,7 +672,7 @@ async function suggestCodemods(
const relevantCodemods = TRANSFORMER_INQUIRER_CHOICES.slice(
initialVersionIndex,
targetVersionIndex
)
).filter((codemod) => !skipAdoption || !codemod.adoption)
if (relevantCodemods.length === 0) {
return []
......
import { yellow } from 'picocolors'
import isGitClean from 'is-git-clean'
export const NEXT_CODEMOD_ERROR_PREFIX = '@next-codemod-error'
export const NEXT_CODEMOD_IGNORE_ERROR_PREFIX = '@next-codemod-ignore'
export function checkGitStatus(force) {
let clean = false
let errorMessage = 'Unable to determine if git directory is clean'
......@@ -148,11 +151,13 @@ export const TRANSFORMER_INQUIRER_CHOICES = [
'Add `export const instant = false` to App Router pages and layouts to ease Cache Components adoption',
value: 'cache-components-instant-false',
version: '16.3.0',
adoption: true,
},
{
title:
"Remove `export const prefetch = 'partial'` Route Segment Config from App Router pages and layouts after enabling `partialPrefetching` globally",
value: 'remove-partial-prefetch',
version: '16.3.0',
adoption: true,
},
]
// @ts-nocheck
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking.
// Remove this opt-out after verifying the segment passes validation without it.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
......
// @ts-nocheck
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking.
// Remove this opt-out after verifying the segment passes validation without it.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
......
// @ts-nocheck
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking.
// Remove this opt-out after verifying the segment passes validation without it.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
......
......@@ -3,7 +3,8 @@
* A page with a leading JSDoc banner.
* The opt-out must be appended after this block, not inside it.
*/
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking.
// Remove this opt-out after verifying the segment passes validation without it.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
......
......@@ -8,7 +8,8 @@ import {
bar,
} from './lib'
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking.
// Remove this opt-out after verifying the segment passes validation without it.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
......
......@@ -2,7 +2,8 @@
import { Suspense } from 'react'
import { foo } from './bar'
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking.
// Remove this opt-out after verifying the segment passes validation without it.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
......
......@@ -2,7 +2,8 @@ import { use } from "react";
import { draftMode, type UnsafeUnwrappedDraftMode } from 'next/headers';
export function MyComponent2() {
(draftMode() as unknown as UnsafeUnwrappedDraftMode).enable()
(/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedDraftMode cast after repairing the migration. */
draftMode() as unknown as UnsafeUnwrappedDraftMode).enable()
}
export function useDraftModeEnabled() {
......
......@@ -2,5 +2,6 @@
import { draftMode, type UnsafeUnwrappedDraftMode } from 'next/headers'
export function MyComponent2() {
(draftMode() as unknown as UnsafeUnwrappedDraftMode).enable()
(/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedDraftMode cast after repairing the migration. */
draftMode() as unknown as UnsafeUnwrappedDraftMode).enable()
}
import { headers, type UnsafeUnwrappedHeaders } from 'next/headers';
export function MyComp() {
return (headers() as unknown as UnsafeUnwrappedHeaders);
return (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders);
}
export function MyComp2() {
return (headers() as unknown as UnsafeUnwrappedHeaders);
return (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders);
}
export function MyComp3() {
return (headers() as unknown as UnsafeUnwrappedHeaders);
return (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders);
}
import { headers, type UnsafeUnwrappedHeaders } from 'next/headers';
export function MyComp() {
void (headers() as unknown as UnsafeUnwrappedHeaders)
void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders)
}
export function generateContentfulMetadata() {
void (headers() as unknown as UnsafeUnwrappedHeaders)
void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders)
}
......@@ -8,6 +8,7 @@ export function myFun() {
export function myFun2() {
return function () {
void (headers() as unknown as UnsafeUnwrappedHeaders)
void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders)
};
}
import { cookies, type UnsafeUnwrappedCookies } from 'next/headers';
export function myFunc() {
const c = (cookies() as unknown as UnsafeUnwrappedCookies)
void (cookies() as unknown as UnsafeUnwrappedCookies)
const c = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */
cookies() as unknown as UnsafeUnwrappedCookies)
void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */
cookies() as unknown as UnsafeUnwrappedCookies)
}
......@@ -9,7 +9,8 @@ import {
} from 'next/headers';
export function MyDraftComponent() {
if ((draftMode() as unknown as UnsafeUnwrappedDraftMode).isEnabled) {
if ((/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedDraftMode cast after repairing the migration. */
draftMode() as unknown as UnsafeUnwrappedDraftMode).isEnabled) {
return null
}
......@@ -17,12 +18,14 @@ export function MyDraftComponent() {
}
export function MyCookiesComponent() {
const c = (cookies() as unknown as UnsafeUnwrappedCookies)
const c = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */
cookies() as unknown as UnsafeUnwrappedCookies)
return c.get('name')
}
export function MyHeadersComponent() {
const h = (headers() as unknown as UnsafeUnwrappedHeaders)
const h = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */
headers() as unknown as UnsafeUnwrappedHeaders)
return <p>{h.get('x-foo')}</p>
}
import { cookies, type UnsafeUnwrappedCookies } from 'next/headers';
export default function Foo(): string {
const name = (cookies() as unknown as UnsafeUnwrappedCookies).get('name')
const name = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */
cookies() as unknown as UnsafeUnwrappedCookies).get('name')
return name
}
......@@ -67,3 +67,31 @@ describe('next-async-request-api - dynamic-apis', () => {
})
}
})
describe('unfinished async migration markers', () => {
const transform = require('../next-async-request-api').default
const j = require('jscodeshift').withParser('tsx')
const apply = source => transform({ path: 'lib/viewer.ts', source }, { jscodeshift: j, j }, {})
it('marks contextual helper repair and does not duplicate it on a second pass', () => {
const source = "import { cookies } from 'next/headers'; export function readViewer() { return cookies().get('viewer')?.value }"
const once = apply(source)
expect(once).toContain('@next-codemod-error')
expect(once).toContain('UnsafeUnwrappedCookies')
const twice = apply(once) || once
expect((twice.match(/@next-codemod-error/g) || []).length).toBe(1)
expect((twice.match(/as unknown as UnsafeUnwrappedCookies/g) || []).length).toBe(1)
})
it('preserves an explicitly documented ignore on a repeated pass', () => {
const source = "import { cookies, type UnsafeUnwrappedCookies } from 'next/headers'; export function readViewer() { return (/* @next-codemod-ignore Verified exception in fixture. */ cookies() as unknown as UnsafeUnwrappedCookies).get('viewer')?.value }"
const output = apply(source) || source
expect(output).toContain('@next-codemod-ignore')
expect(output).not.toContain('@next-codemod-error')
})
it('uses the same marker for a dynamic import requiring contextual review', () => {
const output = apply("export async function readViewer() { const { cookies } = await import('next/headers'); return cookies().get('viewer') }")
expect(output).toContain('@next-codemod-error')
})
})
import type { API, FileInfo } from 'jscodeshift'
import { createParserFromPath } from '../lib/parser'
import { NEXT_CODEMOD_IGNORE_ERROR_PREFIX } from '../lib/utils'
/**
* Blanket-inserts `export const instant = false` into every App Router `page`,
......@@ -104,11 +105,16 @@ export default function transformer(file: FileInfo, _api: API) {
return file.source
}
// Build `export const instant = false`. The two `//` comments above it
// (TODO + See:) are attached as leading comments on the declaration so
// Build `export const instant = false`. The ignore reason, removal condition,
// and guide link are attached as leading comments on the declaration so
// recast prints them right above it.
const todoComment = j.commentLine(
' TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.',
const ignoreComment = j.commentLine(
` ${NEXT_CODEMOD_IGNORE_ERROR_PREFIX} Cache Components adoption: this segment temporarily allows blocking.`,
true,
false
)
const removalComment = j.commentLine(
' Remove this opt-out after verifying the segment passes validation without it.',
true,
false
)
......@@ -122,7 +128,7 @@ export default function transformer(file: FileInfo, _api: API) {
j.variableDeclarator(j.identifier('instant'), j.booleanLiteral(false)),
])
)
instantExport.comments = [todoComment, seeComment]
instantExport.comments = [ignoreComment, removalComment, seeComment]
// Insert after the last top-level import, or at the top of the module
// if there are no imports.
......@@ -138,14 +144,19 @@ export default function transformer(file: FileInfo, _api: API) {
// No imports. Inserting at index 0 would steal any file-level leading
// comments (e.g. `// @ts-nocheck`) from `body[0]` because recast
// attributes them to whatever is first. Move those leading comments
// off `body[0]` onto the new export *before* its TODO/See: lines, so
// off `body[0]` onto the new export *before* its adoption comments, so
// they print in their original position.
const first = body[0]
const allComments = (first.comments ?? []) as any[]
const firstLeading = allComments.filter((c) => c.leading === true)
if (firstLeading.length > 0) {
first.comments = allComments.filter((c) => c.leading !== true)
instantExport.comments = [...firstLeading, todoComment, seeComment]
instantExport.comments = [
...firstLeading,
ignoreComment,
removalComment,
seeComment,
]
}
body.unshift(instantExport)
} else {
......
......@@ -10,14 +10,14 @@ import {
wrapParentheseIfNeeded,
insertCommentOnce,
NEXTJS_ENTRY_FILES,
NEXT_CODEMOD_ERROR_PREFIX,
containsReactHooksCallExpressions,
isParentUseCallExpression,
isReactHookName,
} from './utils'
import { createParserFromPath } from '../../../lib/parser'
import { NEXT_CODEMOD_ERROR_PREFIX } from '../../../lib/utils'
const DYNAMIC_IMPORT_WARN_COMMENT = ` @next-codemod-error The APIs under 'next/headers' are async now, need to be manually awaited. `
const DYNAMIC_IMPORT_WARN_COMMENT = ` ${NEXT_CODEMOD_ERROR_PREFIX} The APIs under 'next/headers' are async now, need to be manually awaited. `
function findDynamicImportsAndComment(root: Collection<any>, j: API['j']) {
let modified = false
......@@ -331,6 +331,20 @@ function castTypesOrAddComment(
*/
const targetType = API_CAST_TYPE_MAP[originRequestApiName]
const repairComment = ` ${NEXT_CODEMOD_ERROR_PREFIX} Await this API and update its callers; remove the temporary ${targetType} cast after repairing the migration. `
const parentCast = path.parentPath?.node
const outerCast = path.parentPath?.parentPath?.node
if (
j.TSAsExpression.check(parentCast) &&
j.TSAsExpression.check(outerCast) &&
j.TSTypeReference.check(outerCast.typeAnnotation) &&
j.Identifier.check(outerCast.typeAnnotation.typeName) &&
outerCast.typeAnnotation.typeName.name === targetType
) {
// Re-parsing attaches the leading marker to the outer cast.
return insertCommentOnce(outerCast, j, repairComment)
}
insertCommentOnce(path.node, j, repairComment)
const newCastExpression = j.tsAsExpression(
j.tsAsExpression(path.node, j.tsUnknownKeyword()),
......
......@@ -20,7 +20,6 @@ import {
TARGET_ROUTE_EXPORTS,
getVariableDeclaratorId,
NEXTJS_ENTRY_FILES,
NEXT_CODEMOD_ERROR_PREFIX,
findFunctionBody,
containsReactHooksCallExpressions,
isParentUseCallExpression,
......@@ -28,6 +27,7 @@ import {
findClosetParentFunctionScope,
} from './utils'
import { createParserFromPath } from '../../../lib/parser'
import { NEXT_CODEMOD_ERROR_PREFIX } from '../../../lib/utils'
const PAGE_PROPS = 'props'
......
......@@ -17,8 +17,10 @@ export type FunctionScope =
| FunctionExpression
| ArrowFunctionExpression
export const NEXT_CODEMOD_ERROR_PREFIX = '@next-codemod-error'
const NEXT_CODEMOD_IGNORE_ERROR_PREFIX = '@next-codemod-ignore'
import {
NEXT_CODEMOD_ERROR_PREFIX,
NEXT_CODEMOD_IGNORE_ERROR_PREFIX,
} from '../../../lib/utils'
export const TARGET_ROUTE_EXPORTS = new Set([
'GET',
......
......@@ -3,7 +3,7 @@
import type { API, Collection, FileInfo, JSXElement } from 'jscodeshift'
import { createParserFromPath } from '../lib/parser'
import { NEXT_CODEMOD_ERROR_PREFIX } from './lib/async-request-api/utils'
import { NEXT_CODEMOD_ERROR_PREFIX } from '../lib/utils'
export default function transformer(file: FileInfo, _api: API) {
const j = createParserFromPath(file.path)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment