Unverified Commit a8af659c authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Avoid unused route handler imports in route type validator

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 44525146
...@@ -546,8 +546,10 @@ export function generateValidatorFile( ...@@ -546,8 +546,10 @@ export function generateValidatorFile(
routesManifest.filePathToRoute routesManifest.filePathToRoute
) )
const hasAppRouteHandlers = // Only import route handler types when a route handler is validated.
Object.keys(routesManifest.appRouteHandlerRoutes).length > 0 // Metadata routes and JavaScript route handlers are listed in the manifest
// but aren't validated, so they mustn't add imports that would be unused.
const hasAppRouteHandlerValidations = appRouteHandlerValidations !== ''
// Build type definitions based on what's actually used // Build type definitions based on what's actually used
let typeDefinitions = '' let typeDefinitions = ''
...@@ -664,7 +666,7 @@ export function generateValidatorFile( ...@@ -664,7 +666,7 @@ export function generateValidatorFile(
routeImports.push('ParamMap') routeImports.push('ParamMap')
} }
if (hasAppRouteHandlers) { if (hasAppRouteHandlerValidations) {
routeImports.push('AppRouteHandlerRoutes') routeImports.push('AppRouteHandlerRoutes')
} }
...@@ -673,7 +675,7 @@ export function generateValidatorFile( ...@@ -673,7 +675,7 @@ export function generateValidatorFile(
? `import type { ${routeImports.join(', ')} } from "./routes.js"` ? `import type { ${routeImports.join(', ')} } from "./routes.js"`
: '' : ''
const nextRequestImport = hasAppRouteHandlers const nextRequestImport = hasAppRouteHandlerValidations
? "import type { NextRequest } from 'next/server.js'\n" ? "import type { NextRequest } from 'next/server.js'\n"
: '' : ''
...@@ -793,8 +795,9 @@ export function generateValidatorFileStrict( ...@@ -793,8 +795,9 @@ export function generateValidatorFileStrict(
routesManifest.filePathToRoute routesManifest.filePathToRoute
) )
const hasAppRouteHandlers = // Only import route handler types when a route handler is validated.
Object.keys(routesManifest.appRouteHandlerRoutes).length > 0 // See generateValidatorFile.
const hasAppRouteHandlerValidations = appRouteHandlerValidations !== ''
// Build type definitions based on what's actually used // Build type definitions based on what's actually used
let typeDefinitions = '' let typeDefinitions = ''
...@@ -911,7 +914,7 @@ export function generateValidatorFileStrict( ...@@ -911,7 +914,7 @@ export function generateValidatorFileStrict(
routeImports.push('ParamMap') routeImports.push('ParamMap')
} }
if (hasAppRouteHandlers) { if (hasAppRouteHandlerValidations) {
routeImports.push('AppRouteHandlerRoutes') routeImports.push('AppRouteHandlerRoutes')
} }
...@@ -920,7 +923,7 @@ export function generateValidatorFileStrict( ...@@ -920,7 +923,7 @@ export function generateValidatorFileStrict(
? `import type { ${routeImports.join(', ')} } from "./routes.js"` ? `import type { ${routeImports.join(', ')} } from "./routes.js"`
: '' : ''
const nextRequestImport = hasAppRouteHandlers const nextRequestImport = hasAppRouteHandlerValidations
? "import type { NextRequest } from 'next/server.js'\n" ? "import type { NextRequest } from 'next/server.js'\n"
: '' : ''
......
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"noUnusedLocals": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import execa from 'execa'
import { nextTestSetup } from 'e2e-utils'
import { getDistDir, retry } from 'next-test-utils'
// Reads generated types and runs the local TypeScript compiler.
// @force-gate !deploy
describe('typed-routes-validator-metadata-only', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
skipStart: true,
})
async function generateTypes() {
if (isNextDev) {
await next.start()
await next.fetch('/')
} else {
await next.build()
}
}
async function expectTypes(expectValidator: (validator: string) => void) {
try {
// Dev route types are generated after the server starts.
await retry(async () => {
const validator = await next.readFile(
`${getDistDir()}/types/validator.ts`
)
expectValidator(validator)
const { exitCode, stdout, stderr } = await execa(
'pnpm',
['tsc', '--noEmit'],
{
cwd: next.testDir,
reject: false,
}
)
expect({ exitCode, stdout, stderr }).toEqual({
exitCode: 0,
stdout: '',
stderr: '',
})
})
} finally {
if (isNextDev) {
await next.stop()
}
}
}
function expectNoRouteHandlerImports(validator: string) {
expect(validator).toContain('const handler = {} as typeof import(')
expect(validator).not.toContain('AppRouteHandlerRoutes')
expect(validator).not.toContain('NextRequest')
}
it('should not import route handler types for metadata routes', async () => {
await generateTypes()
await expectTypes(expectNoRouteHandlerImports)
})
it('should not import route handler types for JavaScript route handlers', async () => {
await next.patchFile(
'app/api/legacy/route.js',
`export function GET() {
return Response.json({ ok: true })
}
`
)
try {
await generateTypes()
await expectTypes(expectNoRouteHandlerImports)
} finally {
await next.deleteFile('app/api/legacy/route.js')
}
})
it('should import route handler types for TypeScript route handlers', async () => {
await next.patchFile(
'app/api/typed/route.ts',
`import type { NextRequest } from 'next/server'
export function GET(request: NextRequest) {
return Response.json({ pathname: request.nextUrl.pathname })
}
`
)
try {
await generateTypes()
await expectTypes((validator) => {
expect(validator).toContain('AppRouteHandlerRoutes')
expect(validator).toContain(
"import type { NextRequest } from 'next/server.js'"
)
expect(validator).toContain('RouteHandlerConfig<"/api/typed">')
})
} finally {
await next.deleteFile('app/api/typed/route.ts')
}
})
})
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