Unverified Commit 212ced6f authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Revert "keep next-env.d.s unchanged between dev and build" (#90384)

parent 6aa3dbd2
...@@ -217,7 +217,6 @@ import { ...@@ -217,7 +217,6 @@ import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
writeValidatorFile, writeValidatorFile,
writeRouteTypesEntryFile,
} from '../server/lib/router-utils/route-types-utils' } from '../server/lib/router-utils/route-types-utils'
import { Lockfile } from './lockfile' import { Lockfile } from './lockfile'
import { import {
...@@ -1367,13 +1366,7 @@ export default async function build( ...@@ -1367,13 +1366,7 @@ export default async function build(
await nextBuildSpan await nextBuildSpan
.traceChild('generate-route-types') .traceChild('generate-route-types')
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
// Actual type files go to route-types.d.ts (not routes.d.ts) const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts')
// routes.d.ts is reserved for the entry file
const routeTypesFilePath = path.join(
distDir,
'types',
'route-types.d.ts'
)
const validatorFilePath = path.join(distDir, 'types', 'validator.ts') const validatorFilePath = path.join(distDir, 'types', 'validator.ts')
await mkdir(path.dirname(routeTypesFilePath), { recursive: true }) await mkdir(path.dirname(routeTypesFilePath), { recursive: true })
...@@ -1400,20 +1393,6 @@ export default async function build( ...@@ -1400,20 +1393,6 @@ export default async function build(
validatorFilePath, validatorFilePath,
Boolean(config.experimental.strictRouteTypes) Boolean(config.experimental.strictRouteTypes)
) )
// Write the entry file at {distDirRoot}/types/routes.d.ts
// This ensures next-env.d.ts has a consistent import path
const entryFilePath = path.join(
dir,
config.distDirRoot,
'types',
'routes.d.ts'
)
const actualTypesDir = path.join(distDir, 'types')
await writeRouteTypesEntryFile(entryFilePath, actualTypesDir, {
strictRouteTypes: Boolean(config.experimental.strictRouteTypes),
typedRoutes: Boolean(config.typedRoutes),
})
}) })
// Turbopack already handles conflicting app and page routes. // Turbopack already handles conflicting app and page routes.
......
...@@ -20,10 +20,10 @@ import { hrtimeDurationToString } from './duration-to-string' ...@@ -20,10 +20,10 @@ import { hrtimeDurationToString } from './duration-to-string'
function verifyTypeScriptSetup( function verifyTypeScriptSetup(
dir: string, dir: string,
distDir: string, distDir: string,
distDirRoot: string,
strictRouteTypes: boolean, strictRouteTypes: boolean,
typeCheckPreflight: boolean, typeCheckPreflight: boolean,
tsconfigPath: string | undefined, tsconfigPath: string | undefined,
typedRoutes: boolean,
disableStaticImages: boolean, disableStaticImages: boolean,
cacheDir: string | undefined, cacheDir: string | undefined,
enableWorkerThreads: boolean | undefined, enableWorkerThreads: boolean | undefined,
...@@ -51,10 +51,10 @@ function verifyTypeScriptSetup( ...@@ -51,10 +51,10 @@ function verifyTypeScriptSetup(
.verifyTypeScriptSetup({ .verifyTypeScriptSetup({
dir, dir,
distDir, distDir,
distDirRoot,
strictRouteTypes, strictRouteTypes,
typeCheckPreflight, typeCheckPreflight,
tsconfigPath, tsconfigPath,
typedRoutes,
disableStaticImages, disableStaticImages,
cacheDir, cacheDir,
hasAppDir, hasAppDir,
...@@ -119,10 +119,10 @@ export async function startTypeChecking({ ...@@ -119,10 +119,10 @@ export async function startTypeChecking({
verifyTypeScriptSetup( verifyTypeScriptSetup(
dir, dir,
config.distDir, config.distDir,
config.distDirRoot,
Boolean(config.experimental.strictRouteTypes), Boolean(config.experimental.strictRouteTypes),
!ignoreTypeScriptErrors, !ignoreTypeScriptErrors,
config.typescript.tsconfigPath, config.typescript.tsconfigPath,
Boolean(config.typedRoutes),
config.images.disableStaticImages, config.images.disableStaticImages,
cacheDir, cacheDir,
config.experimental.workerThreads, config.experimental.workerThreads,
......
...@@ -140,10 +140,10 @@ async function runPlaywright( ...@@ -140,10 +140,10 @@ async function runPlaywright(
const { version: typeScriptVersion } = await verifyTypeScriptSetup({ const { version: typeScriptVersion } = await verifyTypeScriptSetup({
dir: baseDir, dir: baseDir,
distDir: nextConfig.distDir, distDir: nextConfig.distDir,
distDirRoot: nextConfig.distDirRoot,
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes), strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages, disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir, hasAppDir: !!appDir,
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
......
...@@ -16,7 +16,6 @@ import { ...@@ -16,7 +16,6 @@ import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
writeValidatorFile, writeValidatorFile,
writeRouteTypesEntryFile,
} from '../server/lib/router-utils/route-types-utils' } from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils' import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { installBindings } from '../build/swc/install-bindings' import { installBindings } from '../build/swc/install-bindings'
...@@ -46,10 +45,10 @@ const nextTypegen = async ( ...@@ -46,10 +45,10 @@ const nextTypegen = async (
await verifyTypeScriptSetup({ await verifyTypeScriptSetup({
dir: baseDir, dir: baseDir,
distDir: nextConfig.distDir, distDir: nextConfig.distDir,
distDirRoot: nextConfig.distDirRoot,
strictRouteTypes, strictRouteTypes,
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages, disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir, hasAppDir: !!appDir,
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
...@@ -59,9 +58,7 @@ const nextTypegen = async ( ...@@ -59,9 +58,7 @@ const nextTypegen = async (
console.log('Generating route types...') console.log('Generating route types...')
// Actual type files go to route-types.d.ts (not routes.d.ts) const routeTypesFilePath = join(distDir, 'types', 'routes.d.ts')
// routes.d.ts is reserved for the entry file
const routeTypesFilePath = join(distDir, 'types', 'route-types.d.ts')
const validatorFilePath = join(distDir, 'types', 'validator.ts') const validatorFilePath = join(distDir, 'types', 'validator.ts')
await mkdir(join(distDir, 'types'), { recursive: true }) await mkdir(join(distDir, 'types'), { recursive: true })
...@@ -115,20 +112,6 @@ const nextTypegen = async ( ...@@ -115,20 +112,6 @@ const nextTypegen = async (
const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts') const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts')
writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath) writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath)
// Write the entry file at {distDirRoot}/types/routes.d.ts
// This ensures next-env.d.ts has a consistent import path
const entryFilePath = join(
baseDir,
nextConfig.distDirRoot,
'types',
'routes.d.ts'
)
const actualTypesDir = join(distDir, 'types')
await writeRouteTypesEntryFile(entryFilePath, actualTypesDir, {
strictRouteTypes,
typedRoutes: Boolean(nextConfig.typedRoutes),
})
console.log('✓ Types generated successfully') console.log('✓ Types generated successfully')
} }
......
...@@ -5,21 +5,20 @@ import { promises as fs } from 'fs' ...@@ -5,21 +5,20 @@ import { promises as fs } from 'fs'
export async function writeAppTypeDeclarations({ export async function writeAppTypeDeclarations({
baseDir, baseDir,
distDir, distDir,
distDirRoot,
imageImportsEnabled, imageImportsEnabled,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
strictRouteTypes,
typedRoutes,
}: { }: {
baseDir: string baseDir: string
distDir: string distDir: string
/** The root dist directory without /dev suffix, used for fixed type paths */
distDirRoot?: string
imageImportsEnabled: boolean imageImportsEnabled: boolean
hasPagesDir: boolean hasPagesDir: boolean
hasAppDir: boolean hasAppDir: boolean
strictRouteTypes: boolean
typedRoutes: boolean
}): Promise<void> { }): Promise<void> {
// Use distDirRoot for fixed paths in next-env.d.ts, fallback to distDir
const typesDistDir = distDirRoot ?? distDir
// Reference `next` types // Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts') const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
...@@ -62,16 +61,36 @@ export async function writeAppTypeDeclarations({ ...@@ -62,16 +61,36 @@ export async function writeAppTypeDeclarations({
) )
} }
// Use fixed path for the entry type file (always at .next/types/routes.d.ts)
// This entry file re-exports from actual type files which may be at different paths
const routeTypesPath = path.posix.join( const routeTypesPath = path.posix.join(
typesDistDir.replaceAll(path.win32.sep, path.posix.sep), distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/routes.d.ts' 'types/routes.d.ts'
) )
// Use ESM import instead of triple-slash reference for better ESLint compatibility // Use ESM import instead of triple-slash reference for better ESLint compatibility
lines.push(`import "./${routeTypesPath}";`) lines.push(`import "./${routeTypesPath}";`)
if (strictRouteTypes) {
const cacheLifePath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/cache-life.d.ts'
)
lines.push(`import "./${cacheLifePath}";`)
const routeValidatorPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/validator.ts'
)
lines.push(`import "./${routeValidatorPath}";`)
if (typedRoutes === true) {
const linkTypesPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/link.d.ts'
)
lines.push(`import "./${linkTypesPath}";`)
}
}
// Push the notice in. // Push the notice in.
lines.push( lines.push(
'', '',
......
...@@ -56,11 +56,11 @@ function hasNativeTypeScriptPreview(dir: string): boolean { ...@@ -56,11 +56,11 @@ function hasNativeTypeScriptPreview(dir: string): boolean {
export async function verifyTypeScriptSetup({ export async function verifyTypeScriptSetup({
dir, dir,
distDir, distDir,
distDirRoot,
cacheDir, cacheDir,
strictRouteTypes, strictRouteTypes,
tsconfigPath, tsconfigPath,
typeCheckPreflight, typeCheckPreflight,
typedRoutes,
disableStaticImages, disableStaticImages,
hasAppDir, hasAppDir,
hasPagesDir, hasPagesDir,
...@@ -70,12 +70,11 @@ export async function verifyTypeScriptSetup({ ...@@ -70,12 +70,11 @@ export async function verifyTypeScriptSetup({
}: { }: {
dir: string dir: string
distDir: string distDir: string
/** The root dist directory without /dev suffix, used for fixed type paths */
distDirRoot?: string
cacheDir?: string cacheDir?: string
strictRouteTypes: boolean strictRouteTypes: boolean
tsconfigPath: string | undefined tsconfigPath: string | undefined
typeCheckPreflight: boolean typeCheckPreflight: boolean
typedRoutes: boolean
disableStaticImages: boolean disableStaticImages: boolean
hasAppDir: boolean hasAppDir: boolean
hasPagesDir: boolean hasPagesDir: boolean
...@@ -127,10 +126,11 @@ export async function verifyTypeScriptSetup({ ...@@ -127,10 +126,11 @@ export async function verifyTypeScriptSetup({
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: dir, baseDir: dir,
distDir, distDir,
distDirRoot,
imageImportsEnabled: !disableStaticImages, imageImportsEnabled: !disableStaticImages,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
strictRouteTypes,
typedRoutes,
}) })
return { version: null } return { version: null }
...@@ -209,10 +209,11 @@ export async function verifyTypeScriptSetup({ ...@@ -209,10 +209,11 @@ export async function verifyTypeScriptSetup({
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
baseDir: dir, baseDir: dir,
distDir, distDir,
distDirRoot,
imageImportsEnabled: !disableStaticImages, imageImportsEnabled: !disableStaticImages,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
strictRouteTypes,
typedRoutes,
}) })
let result let result
......
...@@ -397,51 +397,3 @@ export async function writeValidatorFile( ...@@ -397,51 +397,3 @@ export async function writeValidatorFile(
: generateValidatorFile(manifest) : generateValidatorFile(manifest)
) )
} }
/**
* Writes the entry file at {distDirRoot}/types/routes.d.ts that re-exports
* from the actual type files. This ensures next-env.d.ts has a consistent
* import path in development and production.
*
* @param entryFilePath - Path to the entry file (e.g., .next/types/routes.d.ts)
* @param actualTypesDir - Path to the actual types directory (e.g., .next/types or .next/dev/types)
* @param options - Configuration options for what to include
*/
export async function writeRouteTypesEntryFile(
entryFilePath: string,
actualTypesDir: string,
options: {
strictRouteTypes: boolean
typedRoutes: boolean
}
) {
const entryDir = path.dirname(entryFilePath)
if (!fs.existsSync(entryDir)) {
await fs.promises.mkdir(entryDir, { recursive: true })
}
// Calculate relative path from entry file to actual types directory
const relativePath = normalizePathSep(path.relative(entryDir, actualTypesDir))
const prefix = relativePath === '' ? './' : `./${relativePath}/`
const lines: string[] = [
'// This is an auto-generated entry file that re-exports route types.',
'// Do not edit this file directly.',
'',
`export type * from "${prefix}route-types.d.ts";`,
]
if (options.strictRouteTypes) {
lines.push(`import "${prefix}cache-life.d.ts";`)
lines.push(`import "${prefix}validator.ts";`)
if (options.typedRoutes) {
lines.push(`import "${prefix}link.d.ts";`)
}
}
lines.push('') // trailing newline
await fs.promises.writeFile(entryFilePath, lines.join('\n'))
}
...@@ -87,7 +87,6 @@ import { ...@@ -87,7 +87,6 @@ import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
writeValidatorFile, writeValidatorFile,
writeRouteTypesEntryFile,
} from './route-types-utils' } from './route-types-utils'
import { writeCacheLifeTypes } from './cache-life-type-utils' import { writeCacheLifeTypes } from './cache-life-type-utils'
import { import {
...@@ -153,10 +152,10 @@ async function verifyTypeScript(opts: SetupOpts) { ...@@ -153,10 +152,10 @@ async function verifyTypeScript(opts: SetupOpts) {
const verifyResult = await verifyTypeScriptSetup({ const verifyResult = await verifyTypeScriptSetup({
dir: opts.dir, dir: opts.dir,
distDir: opts.nextConfig.distDir, distDir: opts.nextConfig.distDir,
distDirRoot: opts.nextConfig.distDirRoot,
strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes), strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes),
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath, tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(opts.nextConfig.typedRoutes),
disableStaticImages: opts.nextConfig.images.disableStaticImages, disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir, hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir, hasPagesDir: !!opts.pagesDir,
...@@ -288,22 +287,10 @@ async function startWatcher( ...@@ -288,22 +287,10 @@ async function startWatcher(
pageApiRoutes: new Set(), pageApiRoutes: new Set(),
filePathToRoute: new Map(), filePathToRoute: new Map(),
}, },
path.join(distTypesDir, 'route-types.d.ts'), path.join(distTypesDir, 'routes.d.ts'),
opts.nextConfig opts.nextConfig
) )
// Write the entry file at {distDirRoot}/types/routes.d.ts for initial state
const initialEntryFilePath = path.join(
opts.dir,
opts.nextConfig.distDirRoot,
'types',
'routes.d.ts'
)
await writeRouteTypesEntryFile(initialEntryFilePath, distTypesDir, {
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
typedRoutes: Boolean(nextConfig.typedRoutes),
})
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: DevRoutesManifest = { const routesManifest: DevRoutesManifest = {
version: 3, version: 3,
...@@ -423,9 +410,7 @@ async function startWatcher( ...@@ -423,9 +410,7 @@ async function startWatcher(
let previousClientRouterFilters: any let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set() let previousConflictingPagePaths: Set<string> = new Set()
// Actual type files go to route-types.d.ts (not routes.d.ts) const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts')
// routes.d.ts is reserved for the entry file
const routeTypesFilePath = path.join(distDir, 'types', 'route-types.d.ts')
const validatorFilePath = path.join(distDir, 'types', 'validator.ts') const validatorFilePath = path.join(distDir, 'types', 'validator.ts')
let initialWatchTime = performance.now() + performance.timeOrigin let initialWatchTime = performance.now() + performance.timeOrigin
...@@ -1203,19 +1188,6 @@ async function startWatcher( ...@@ -1203,19 +1188,6 @@ async function startWatcher(
// Generate cache-life types if cacheLife config exists // Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = path.join(distTypesDir, 'cache-life.d.ts') const cacheLifeFilePath = path.join(distTypesDir, 'cache-life.d.ts')
writeCacheLifeTypes(opts.nextConfig.cacheLife, cacheLifeFilePath) writeCacheLifeTypes(opts.nextConfig.cacheLife, cacheLifeFilePath)
// Write the entry file at {distDirRoot}/types/routes.d.ts
// This ensures next-env.d.ts has a consistent import path
const entryFilePath = path.join(
opts.dir,
opts.nextConfig.distDirRoot,
'types',
'routes.d.ts'
)
await writeRouteTypesEntryFile(entryFilePath, distTypesDir, {
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
typedRoutes: Boolean(nextConfig.typedRoutes),
})
} }
if (!resolved) { if (!resolved) {
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('isolated-dev-build with strictRouteTypes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should use fixed path in next-env.d.ts with strictRouteTypes enabled', async () => {
await retry(async () => {
// next-env.d.ts should use the fixed path .next/types/routes.d.ts
// not the dev-specific path .next/dev/types/routes.d.ts
// even with strictRouteTypes enabled
const nextEnvContent = await next.readFile('next-env.d.ts')
expect(nextEnvContent).toContain('import "./.next/types/routes.d.ts"')
expect(nextEnvContent).not.toContain('.next/dev/types')
// With strictRouteTypes enabled, next-env.d.ts should NOT have
// additional imports for cache-life, validator, link
// These are now re-exported from the entry file
expect(nextEnvContent).not.toContain('cache-life')
expect(nextEnvContent).not.toContain('validator')
expect(nextEnvContent).not.toContain('link.d.ts')
})
})
it('should create entry file that re-exports strict route type files', async () => {
await retry(async () => {
// The entry file should exist at the fixed path
expect(await next.hasFile('.next/types/routes.d.ts')).toBe(true)
// The entry file should reference the actual types in .next/dev/types
const entryFileContent = await next.readFile('.next/types/routes.d.ts')
expect(entryFileContent).toContain('route-types.d.ts')
expect(entryFileContent).toContain('../dev/types/')
// With strictRouteTypes enabled, entry file should also reference
// cache-life.d.ts and validator.ts
expect(entryFileContent).toContain('cache-life.d.ts')
expect(entryFileContent).toContain('validator.ts')
})
})
it('should create strict route type files in .next/dev/types/', async () => {
await retry(async () => {
// Actual type files should be in .next/dev/types/
expect(await next.hasFile('.next/dev/types/route-types.d.ts')).toBe(true)
expect(await next.hasFile('.next/dev/types/cache-life.d.ts')).toBe(true)
expect(await next.hasFile('.next/dev/types/validator.ts')).toBe(true)
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteTypes: true,
},
}
module.exports = nextConfig
...@@ -25,33 +25,4 @@ describe('isolated-dev-build', () => { ...@@ -25,33 +25,4 @@ describe('isolated-dev-build', () => {
expect(await browser.elementByCss('p').text()).toBe('hello updated world') expect(await browser.elementByCss('p').text()).toBe('hello updated world')
}) })
}) })
it('should use fixed path in next-env.d.ts', async () => {
await retry(async () => {
// next-env.d.ts should use the fixed path .next/types/routes.d.ts
// not the dev-specific path .next/dev/types/routes.d.ts
const nextEnvContent = await next.readFile('next-env.d.ts')
expect(nextEnvContent).toContain('import "./.next/types/routes.d.ts"')
expect(nextEnvContent).not.toContain('.next/dev/types')
})
})
it('should create entry file at .next/types/routes.d.ts that references dev types', async () => {
await retry(async () => {
// The entry file should exist at the fixed path
expect(await next.hasFile('.next/types/routes.d.ts')).toBe(true)
// The entry file should reference the actual types in .next/dev/types
const entryFileContent = await next.readFile('.next/types/routes.d.ts')
expect(entryFileContent).toContain('route-types.d.ts')
expect(entryFileContent).toContain('../dev/types/')
})
})
it('should create actual type files in .next/dev/types/', async () => {
await retry(async () => {
// Actual type files should be in .next/dev/types/
expect(await next.hasFile('.next/dev/types/route-types.d.ts')).toBe(true)
})
})
}) })
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", "**/*.mts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import execa from 'execa'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getDistDir } from 'next-test-utils' import { getDistDir } from 'next-test-utils'
...@@ -22,9 +23,39 @@ describe('typed-routes-validator', () => { ...@@ -22,9 +23,39 @@ describe('typed-routes-validator', () => {
} else { } else {
await next.build() await next.build()
} }
const dts = await next.readFile(`${getDistDir()}/types/validator.ts`)
// sanity check that dev generation is working try {
expect(dts).toContain('const handler = {} as typeof import(') const dts = await next.readFile(`${getDistDir()}/types/validator.ts`)
// sanity check that dev generation is working
expect(dts).toContain('const handler = {} as typeof import(')
} finally {
if (isNextDev) {
await next.stop()
}
}
})
it('should have passing tsc after the server generated types', async () => {
if (isNextDev) {
await next.start()
} else {
await next.build()
}
try {
const { stdout, stderr } = await execa('pnpm', ['tsc', '--noEmit'], {
cwd: next.testDir,
reject: false,
})
expect({ stdout, stderr }).toEqual({
stdout: '',
stderr: '',
})
} finally {
if (isNextDev) {
await next.stop()
}
}
}) })
if (isNextStart) { if (isNextStart) {
......
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", "**/*.mts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import execa from 'execa'
import { retry, runNextCommand } from 'next-test-utils' import { retry, runNextCommand } from 'next-test-utils'
const expectedDts = ` const expectedDts = `
...@@ -23,14 +24,31 @@ describe('typed-routes', () => { ...@@ -23,14 +24,31 @@ describe('typed-routes', () => {
it('should generate route types correctly', async () => { it('should generate route types correctly', async () => {
await retry(async () => { await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/route-types.d.ts`) const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
expect(dts).toContain(expectedDts) expect(dts).toContain(expectedDts)
}) })
}) })
it('should have passing tsc after start', async () => {
await next.stop()
try {
const { stdout, stderr } = await execa('pnpm', ['tsc', '--noEmit'], {
cwd: next.testDir,
reject: false,
})
expect({ stdout, stderr }).toEqual({
stdout: '',
stderr: '',
})
} finally {
await next.start()
}
})
it('should correctly convert custom route patterns from path-to-regexp to bracket syntax', async () => { it('should correctly convert custom route patterns from path-to-regexp to bracket syntax', async () => {
await retry(async () => { await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/route-types.d.ts`) const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
// Test standard dynamic segment: :slug -> [slug] // Test standard dynamic segment: :slug -> [slug]
expect(dts).toContain('"/project/[slug]"') expect(dts).toContain('"/project/[slug]"')
...@@ -58,7 +76,7 @@ describe('typed-routes', () => { ...@@ -58,7 +76,7 @@ describe('typed-routes', () => {
await retry(async () => { await retry(async () => {
const routeTypesContent = await next.readFile( const routeTypesContent = await next.readFile(
`${next.distDir}/types/route-types.d.ts` `${next.distDir}/types/routes.d.ts`
) )
expect(routeTypesContent).toContain( expect(routeTypesContent).toContain(
...@@ -70,7 +88,7 @@ describe('typed-routes', () => { ...@@ -70,7 +88,7 @@ describe('typed-routes', () => {
it('should generate RouteContext type for route handlers', async () => { it('should generate RouteContext type for route handlers', async () => {
await retry(async () => { await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/route-types.d.ts`) const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
expect(dts).toContain( expect(dts).toContain(
'interface RouteContext<AppRouteHandlerRoute extends AppRouteHandlerRoutes>' 'interface RouteContext<AppRouteHandlerRoute extends AppRouteHandlerRoutes>'
) )
......
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import './.next/types/routes.d.ts' import './.next/dev/types/routes.d.ts'
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import './.next/types/routes.d.ts' import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts"; import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/cache-life.d.ts";
import "./.next/dev/types/validator.ts";
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
...@@ -22,7 +22,7 @@ describe('types-gen-nounuselocal', () => { ...@@ -22,7 +22,7 @@ describe('types-gen-nounuselocal', () => {
it('should generate route types successfully', async () => { it('should generate route types successfully', async () => {
const routeTypes = await fsp.readFile( const routeTypes = await fsp.readFile(
path.join(next.testDir, '.next', 'types', 'route-types.d.ts'), path.join(next.testDir, '.next', 'types', 'routes.d.ts'),
'utf-8' 'utf-8'
) )
......
...@@ -3,13 +3,12 @@ import os from 'os' ...@@ -3,13 +3,12 @@ import os from 'os'
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { writeAppTypeDeclarations } from 'next/dist/lib/typescript/writeAppTypeDeclarations' import { writeAppTypeDeclarations } from 'next/dist/lib/typescript/writeAppTypeDeclarations'
import { writeRouteTypesEntryFile } from 'next/dist/server/lib/router-utils/route-types-utils'
const fixtureDir = join(__dirname, 'fixtures/app-declarations') const fixtureDir = join(__dirname, 'fixtures/app-declarations')
const declarationFile = join(fixtureDir, 'next-env.d.ts') const declarationFile = join(fixtureDir, 'next-env.d.ts')
const imageImportsEnabled = false const imageImportsEnabled = false
describe('writeAppTypeDeclarations', () => { describe('find config', () => {
beforeEach(async () => { beforeEach(async () => {
await fs.ensureDir(fixtureDir) await fs.ensureDir(fixtureDir)
}) })
...@@ -39,6 +38,8 @@ describe('writeAppTypeDeclarations', () => { ...@@ -39,6 +38,8 @@ describe('writeAppTypeDeclarations', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
}) })
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content) expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
}) })
...@@ -67,6 +68,8 @@ describe('writeAppTypeDeclarations', () => { ...@@ -67,6 +68,8 @@ describe('writeAppTypeDeclarations', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
}) })
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content) expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
}) })
...@@ -93,6 +96,8 @@ describe('writeAppTypeDeclarations', () => { ...@@ -93,6 +96,8 @@ describe('writeAppTypeDeclarations', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
}) })
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content) expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
}) })
...@@ -104,6 +109,8 @@ describe('writeAppTypeDeclarations', () => { ...@@ -104,6 +109,8 @@ describe('writeAppTypeDeclarations', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: true, hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
}) })
await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain( await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
...@@ -116,147 +123,12 @@ describe('writeAppTypeDeclarations', () => { ...@@ -116,147 +123,12 @@ describe('writeAppTypeDeclarations', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: true, hasPagesDir: true,
hasAppDir: true, hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
}) })
await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain( await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain(
'next/navigation-types/compat/navigation' 'next/navigation-types/compat/navigation'
) )
}) })
describe('next-env.d.ts consistency between dev and build', () => {
it('should produce consistent content regardless of distDir', async () => {
// Simulate dev mode: distDir = '.next/dev', distDirRoot = '.next'
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next/dev',
distDirRoot: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: true,
})
const devContent = await fs.readFile(declarationFile, 'utf8')
// Simulate build mode: distDir = '.next', distDirRoot = '.next'
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
distDirRoot: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: true,
})
const buildContent = await fs.readFile(declarationFile, 'utf8')
// Both should be identical
expect(devContent).toBe(buildContent)
// Should use fixed path from distDirRoot
expect(devContent).toContain('import "./.next/types/routes.d.ts";')
expect(devContent).not.toContain('.next/dev')
})
it('should use distDir when distDirRoot is not provided', async () => {
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: true,
})
const content = await fs.readFile(declarationFile, 'utf8')
expect(content).toContain('import "./.next/types/routes.d.ts";')
})
})
})
describe('writeRouteTypesEntryFile', () => {
const entryFileDir = join(fixtureDir, '.next', 'types')
const entryFilePath = join(entryFileDir, 'routes.d.ts')
beforeEach(async () => {
await fs.ensureDir(entryFileDir)
})
afterEach(() => fs.remove(join(fixtureDir, '.next')))
it('should write entry file with strictRouteTypes disabled', async () => {
const actualTypesDir = join(fixtureDir, '.next', 'types')
await writeRouteTypesEntryFile(entryFilePath, actualTypesDir, {
strictRouteTypes: false,
typedRoutes: false,
})
const content = await fs.readFile(entryFilePath, 'utf8')
expect(content).toMatchInlineSnapshot(`
"// This is an auto-generated entry file that re-exports route types.
// Do not edit this file directly.
export type * from "./route-types.d.ts";
"
`)
})
it('should write entry file with strictRouteTypes enabled', async () => {
const actualTypesDir = join(fixtureDir, '.next', 'types')
await writeRouteTypesEntryFile(entryFilePath, actualTypesDir, {
strictRouteTypes: true,
typedRoutes: false,
})
const content = await fs.readFile(entryFilePath, 'utf8')
expect(content).toMatchInlineSnapshot(`
"// This is an auto-generated entry file that re-exports route types.
// Do not edit this file directly.
export type * from "./route-types.d.ts";
import "./cache-life.d.ts";
import "./validator.ts";
"
`)
})
it('should write entry file with strictRouteTypes and typedRoutes enabled', async () => {
const actualTypesDir = join(fixtureDir, '.next', 'types')
await writeRouteTypesEntryFile(entryFilePath, actualTypesDir, {
strictRouteTypes: true,
typedRoutes: true,
})
const content = await fs.readFile(entryFilePath, 'utf8')
expect(content).toMatchInlineSnapshot(`
"// This is an auto-generated entry file that re-exports route types.
// Do not edit this file directly.
export type * from "./route-types.d.ts";
import "./cache-life.d.ts";
import "./validator.ts";
import "./link.d.ts";
"
`)
})
it('should use relative path when entry file and actual types are in different directories', async () => {
// Simulate dev mode: entry file at .next/types, actual types at .next/dev/types
const devTypesDir = join(fixtureDir, '.next', 'dev', 'types')
await fs.ensureDir(devTypesDir)
await writeRouteTypesEntryFile(entryFilePath, devTypesDir, {
strictRouteTypes: true,
typedRoutes: true,
})
const content = await fs.readFile(entryFilePath, 'utf8')
expect(content).toMatchInlineSnapshot(`
"// This is an auto-generated entry file that re-exports route types.
// Do not edit this file directly.
export type * from "./../dev/types/route-types.d.ts";
import "./../dev/types/cache-life.d.ts";
import "./../dev/types/validator.ts";
import "./../dev/types/link.d.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