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

Share generated route types between next dev, next build and next typegen

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent b2579923
......@@ -346,7 +346,7 @@ export function Nav() {
### Type IntelliSense for Environment Variables
During development, Next.js generates a `.d.ts` file in `.next/types` that contains information about the loaded environment variables for your editor's IntelliSense. If the same environment variable key is defined in multiple files, it is deduplicated according to the [Environment Variable Load Order](/docs/app/guides/environment-variables#environment-variable-load-order).
During development, Next.js generates a `.d.ts` file in `.next/dev/types` that contains information about the loaded environment variables for your editor's IntelliSense. If the same environment variable key is defined in multiple files, it is deduplicated according to the [Environment Variable Load Order](/docs/app/guides/environment-variables#environment-variable-load-order).
To opt-into this feature, `experimental.typedEnv` needs to be enabled and the project needs to be using TypeScript.
......
......@@ -196,7 +196,7 @@ The following options are available for the `next typegen` command:
| `-h, --help` | Show all available options. |
| `[directory]` | A directory on which to generate types. If not provided, the current directory will be used. |
Output files are written to `<distDir>/types` (typically `.next/types`). `next dev` writes its own types to `.next/dev/types`. When no `next dev` server is running, `next typegen` removes `.next/dev/types` so that types for moved or deleted routes don't fail type checking. `next dev` regenerates them when it starts.
Output files are written to `<distDir>/types` (typically `.next/types`). `next dev` and `next build` generate the same route types into the same directory, so `next-env.d.ts` and the generated types stay the same across commands. `next dev` also writes development-only types, such as typed environment variables, to `.next/dev/types`. When no `next dev` server is running, `next typegen` removes `.next/dev/types` so that stale types don't fail type checking. `next dev` regenerates them.
```bash filename="Terminal"
next typegen
......
......@@ -238,12 +238,10 @@ import {
} from '../shared/lib/router/utils/sortable-routes'
import { cp, mkdir } from 'fs/promises'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
writeValidatorFile,
} from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { writeRootParamsTypes } from '../server/lib/router-utils/root-params-type-utils'
generateSharedTypes,
SHARED_TYPES_PRESERVED_ENTRIES,
} from '../lib/typescript/shared-types'
import { getSharedTypesDir } from '../lib/typescript/shared-types-dir'
import { Lockfile } from './lockfile'
import {
buildPrefetchSegmentDataRoute,
......@@ -1374,13 +1372,21 @@ export default async function build(
}
if (config.cleanDistDir && !isGenerateMode) {
// Keep the types shared with `next dev` and `next typegen` (and their
// lock) when they live in this `distDir`, so a running dev server
// doesn't lose them. They are regenerated below. Everything else in
// `types` (e.g. webpack type guards) is still removed.
const sharedTypesDir = getSharedTypesDir(dir, config)
const keep = new Set(['cache', 'dev', 'diagnostics', 'lock', 'trace'])
if (sharedTypesDir === path.join(distDir, 'types')) {
for (const entry of SHARED_TYPES_PRESERVED_ENTRIES) {
keep.add(path.join('types', entry))
}
}
await nextBuildSpan
.traceChild('clean')
.traceAsyncFn(() =>
recursiveDeleteSyncWithAsyncRetries(
distDir,
new Set(['cache', 'dev', 'diagnostics', 'lock', 'trace'])
)
recursiveDeleteSyncWithAsyncRetries(distDir, keep)
)
}
......@@ -1586,15 +1592,6 @@ export default async function build(
})
)
const {
pageRoutes,
pageApiRoutes,
appRoutes,
appRouteHandlers,
layoutRoutes,
slots,
} = discovery
const pagesPageKeys = Object.keys(NextBuildContext.mappedPages)
const conflictingAppPagePaths: [pagePath: string, appPath: string][] = []
......@@ -1646,45 +1643,16 @@ export default async function build(
await nextBuildSpan
.traceChild('generate-route-types')
.traceAsyncFn(async () => {
const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts')
const validatorFilePath = path.join(distDir, 'types', 'validator.ts')
const cacheLifeFilePath = path.join(
distDir,
'types',
'cache-life.d.ts'
)
await mkdir(path.dirname(routeTypesFilePath), { recursive: true })
const routeTypesManifest = await createRouteTypesManifest({
// Generates the types shared with `next dev` and `next typegen`
// for every route, including those excluded by
// `--debug-build-paths`.
await generateSharedTypes({
dir,
pageRoutes,
appRoutes,
appRouteHandlers,
pageApiRoutes,
layoutRoutes,
slots,
redirects: config.redirects,
rewrites: config.rewrites,
validatorFilePath,
config,
appDir,
pagesDir,
})
await writeRouteTypesManifest(
routeTypesManifest,
routeTypesFilePath,
config
)
await writeValidatorFile(
routeTypesManifest,
validatorFilePath,
Boolean(config.experimental.strictRouteTypes)
)
writeCacheLifeTypes(config.cacheLife, cacheLifeFilePath)
await writeRootParamsTypes(
routeTypesManifest,
path.join(distDir, 'types', 'root-params.d.ts')
)
// The TypeScript CLI type check includes every file in tsconfig,
// so types left behind by a stopped `next dev` would fail it after
// routes are moved or deleted. `next dev` writes below the
......
import { Lockfile } from './lockfile'
import * as Log from './output/log'
import { getBindingsSync } from './swc'
jest.mock('./swc', () => ({ getBindingsSync: jest.fn() }))
jest.mock('./output/log', () => ({ info: jest.fn(), warn: jest.fn() }))
const WAITING_MESSAGE = 'Waiting for the lock...'
describe('Lockfile.unlock', () => {
beforeEach(() => {
......@@ -24,3 +28,98 @@ describe('Lockfile.unlock', () => {
expect(lockfileUnlock).toHaveBeenCalledTimes(1)
})
})
describe('Lockfile.acquireWithWait', () => {
const lockfile = {} as Lockfile
let tryAcquire: jest.SpyInstance
beforeEach(() => {
jest.useFakeTimers()
jest.clearAllMocks()
;(getBindingsSync as jest.Mock).mockReturnValue({ isWasm: false })
tryAcquire = jest.spyOn(Lockfile, 'tryAcquire')
})
afterEach(() => {
tryAcquire.mockRestore()
jest.useRealTimers()
})
it('waits silently for a lock that is released quickly', async () => {
tryAcquire
.mockReturnValueOnce(undefined)
.mockReturnValueOnce(undefined)
.mockReturnValue(lockfile)
const acquired = Lockfile.acquireWithWait('/lock', {
pollMs: 1,
warnAfterMs: 10_000,
waitingMessage: WAITING_MESSAGE,
})
await jest.advanceTimersByTimeAsync(2)
await expect(acquired).resolves.toBe(lockfile)
expect(tryAcquire).toHaveBeenCalledTimes(3)
expect(Log.info).not.toHaveBeenCalled()
expect(Log.warn).not.toHaveBeenCalled()
})
it('logs the waiting message once after the threshold', async () => {
let released = false
tryAcquire.mockImplementation(() => (released ? lockfile : undefined))
const acquired = Lockfile.acquireWithWait('/lock', {
pollMs: 1,
warnAfterMs: 10,
timeoutMs: 10_000,
waitingMessage: WAITING_MESSAGE,
})
await jest.advanceTimersByTimeAsync(9)
expect(Log.info).not.toHaveBeenCalled()
await jest.advanceTimersByTimeAsync(30)
released = true
await jest.advanceTimersByTimeAsync(1)
await expect(acquired).resolves.toBe(lockfile)
expect(Log.info).toHaveBeenCalledTimes(1)
expect(Log.info).toHaveBeenCalledWith(WAITING_MESSAGE)
expect(Log.warn).not.toHaveBeenCalled()
})
it('proceeds without the lock after the timeout', async () => {
tryAcquire.mockReturnValue(undefined)
const acquired = Lockfile.acquireWithWait('/lock', {
pollMs: 1,
warnAfterMs: 5,
timeoutMs: 20,
waitingMessage: WAITING_MESSAGE,
})
await jest.advanceTimersByTimeAsync(20)
await expect(acquired).resolves.toBeUndefined()
expect(Log.info).toHaveBeenCalledTimes(1)
expect(Log.warn).toHaveBeenCalledTimes(1)
})
it('proceeds without the lock if it cannot be created', async () => {
tryAcquire.mockImplementation(() => {
throw new Error('An IO error occurred')
})
await expect(
Lockfile.acquireWithWait('/lock', { waitingMessage: WAITING_MESSAGE })
).resolves.toBeUndefined()
expect(tryAcquire).toHaveBeenCalledTimes(1)
expect(Log.warn).not.toHaveBeenCalled()
})
it('proceeds without the lock with WASM bindings', async () => {
;(getBindingsSync as jest.Mock).mockReturnValue({ isWasm: true })
await expect(
Lockfile.acquireWithWait('/lock', { waitingMessage: WAITING_MESSAGE })
).resolves.toBeUndefined()
expect(tryAcquire).not.toHaveBeenCalled()
})
})
import fs from 'fs'
import nodePath from 'path'
import createDebug from 'next/dist/compiled/debug'
import { bold, cyan } from '../lib/picocolors'
import * as Log from './output/log'
import { getBindingsSync } from './swc'
......@@ -10,6 +11,8 @@ import type {
LockfileError as NativeLockfileError,
} from './swc/types'
const debugLockfile = createDebug('next:lockfile')
const RETRY_DELAY_MS = 10
const MAX_RETRY_MS = 1000
......@@ -261,6 +264,66 @@ export class Lockfile {
return lockfile
}
/**
* Waits asynchronously for a lockfile that is expected to be held only
* briefly by other processes (e.g. while they generate types). Unlike
* `acquireWithRetriesOrExit`, this never exits the process:
*
* - Polls `tryAcquire` with async sleeps, so the event loop is not blocked.
* - Logs `waitingMessage` once if the lock is still held after
* `warnAfterMs`.
* - Returns `undefined` (after a warning) once `timeoutMs` elapses, so the
* caller can proceed without the lock.
* - Returns `undefined` if the lockfile can't be created, e.g. on filesystems
* without lock support. Callers must be safe to run without the lock.
*/
static async acquireWithWait(
path: string,
{
warnAfterMs = 5_000,
timeoutMs = 30_000,
pollMs = 50,
waitingMessage,
}: {
warnAfterMs?: number
timeoutMs?: number
pollMs?: number
waitingMessage: string
}
): Promise<Lockfile | undefined> {
const startMs = Date.now()
let warned = false
if (getBindingsSync().isWasm) {
// WASM bindings can't lock; run without it (and without the log
// `tryAcquire` prints for every attempt).
return undefined
}
while (true) {
let lockfile
try {
lockfile = Lockfile.tryAcquire(path)
} catch (e) {
debugLockfile(`Proceeding without lockfile ${path}: ${e}`)
return undefined
}
if (lockfile !== undefined) {
return lockfile
}
const elapsedMs = Date.now() - startMs
if (elapsedMs >= timeoutMs) {
Log.warn(
`Timed out waiting for lockfile ${cyan(path)}, continuing without it.`
)
return undefined
}
if (!warned && elapsedMs >= warnAfterMs) {
warned = true
Log.info(waitingMessage)
}
await new Promise((resolve) => setTimeout(resolve, pollMs))
}
}
/**
* Releases the lockfile and closes the file descriptor.
*
......
......@@ -9,6 +9,7 @@ import { eventTypeCheckCompleted } from '../telemetry/events'
import isError from '../lib/is-error'
import { hrtimeDurationToString } from './duration-to-string'
import { getBuildDistDir } from '../export/utils'
import { getSharedTypesDistDir } from '../lib/typescript/shared-types-dir'
/**
* TypeScript setup and type checking run in a worker so the compiler's memory
......@@ -21,6 +22,7 @@ import { getBuildDistDir } from '../export/utils'
function verifyAndRunTypeScript(
dir: string,
distDir: string,
typesDistDir: string,
strictRouteTypes: boolean,
shouldRunTypeCheck: boolean,
tsconfigPath: string | undefined,
......@@ -66,6 +68,7 @@ function verifyAndRunTypeScript(
return impl({
dir,
distDir,
typesDistDir,
strictRouteTypes,
shouldRunTypeCheck,
tsconfigPath,
......@@ -139,6 +142,8 @@ export async function startTypeChecking({
verifyAndRunTypeScript(
dir,
getBuildDistDir(config),
// The shared types directory, see `getSharedTypesDir`.
getSharedTypesDistDir(config),
Boolean(config.experimental.strictRouteTypes),
!ignoreTypeScriptErrors,
config.typescript.tsconfigPath,
......
......@@ -13,6 +13,7 @@ import type { NextConfigComplete } from '../server/config-shared'
import findUp from 'next/dist/compiled/find-up'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyAndRunTypeScript } from '../lib/verify-typescript-setup'
import { getSharedTypesDistDir } from '../lib/typescript/shared-types-dir'
import path from 'path'
import spawn from 'next/dist/compiled/cross-spawn'
......@@ -145,6 +146,7 @@ async function runPlaywright(
const { version: typeScriptVersion } = await verifyAndRunTypeScript({
dir: baseDir,
distDir: nextConfig.distDir,
typesDistDir: getSharedTypesDistDir(nextConfig),
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
shouldRunTypeCheck: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
......
#!/usr/bin/env node
import { existsSync } from 'fs'
import path, { join } from 'path'
import { mkdir } from 'fs/promises'
import { join } from 'path'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
......@@ -11,16 +10,9 @@ import { getProjectDir } from '../lib/get-project-dir'
import { warnMissingReactDependencies } from '../lib/warn-missing-react-dependencies'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyAndRunTypeScript } from '../lib/verify-typescript-setup'
import { discoverRoutes } from '../build/route-discovery'
import { parseBundlerArgs } from '../lib/bundler'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
writeValidatorFile,
} from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { writeRootParamsTypes } from '../server/lib/router-utils/root-params-type-utils'
import { generateSharedTypes } from '../lib/typescript/shared-types'
import { getSharedTypesDistDir } from '../lib/typescript/shared-types-dir'
import { installBindings } from '../build/swc/install-bindings'
import { removeStaleDevTypes } from '../lib/typescript/remove-stale-dev-types'
......@@ -50,6 +42,7 @@ const nextTypegen = async (options: NextTypegenOptions, directory?: string) => {
await verifyAndRunTypeScript({
dir: baseDir,
distDir: nextConfig.distDir,
typesDistDir: getSharedTypesDistDir(nextConfig),
strictRouteTypes,
shouldRunTypeCheck: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
......@@ -64,65 +57,13 @@ const nextTypegen = async (options: NextTypegenOptions, directory?: string) => {
console.log('Generating route types...')
const routeTypesFilePath = join(distDir, 'types', 'routes.d.ts')
const validatorFilePath = join(distDir, 'types', 'validator.ts')
await mkdir(join(distDir, 'types'), { recursive: true })
const isSrcDir = path
.relative(baseDir, pagesDir || appDir || '')
.startsWith('src')
// Build all routes (pages + app + slots)
const {
pageRoutes,
pageApiRoutes,
appRoutes,
appRouteHandlers,
layoutRoutes,
slots,
} = await discoverRoutes({
await generateSharedTypes({
dir: baseDir,
config: nextConfig,
appDir: appDir || undefined,
pagesDir: pagesDir || undefined,
pageExtensions: nextConfig.pageExtensions,
isDev: false,
baseDir,
isSrcDir,
})
const routeTypesManifest = await createRouteTypesManifest({
dir: baseDir,
pageRoutes,
appRoutes,
appRouteHandlers,
pageApiRoutes,
layoutRoutes,
slots,
redirects: nextConfig.redirects,
rewrites: nextConfig.rewrites,
validatorFilePath,
})
await writeRouteTypesManifest(
routeTypesManifest,
routeTypesFilePath,
nextConfig
)
await writeValidatorFile(
routeTypesManifest,
validatorFilePath,
strictRouteTypes
)
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts')
writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath)
await writeRootParamsTypes(
routeTypesManifest,
join(distDir, 'types', 'root-params.d.ts')
)
// Types left behind by a stopped `next dev` would otherwise fail type checking
// after routes are moved or deleted.
await removeStaleDevTypes({
......
......@@ -49,11 +49,13 @@ export async function runTypeCheck(
tsConfigPath
)
// tsconfig includes both .next/types and .next/dev/types to avoid config churn
// between dev/build modes. During build, we filter out .next/dev/types files to
// prevent stale dev types from causing errors when routes have been deleted since
// the last dev session. Build also removes the types of a stopped dev server
// (see `removeStaleDevTypes`), but keeps those of a running one.
// tsconfig includes both .next/types and .next/dev/types. Route types are
// shared by all modes in .next/types (see `getSharedTypesDir`), while
// .next/dev/types only holds dev-specific types (`env.d.ts`, webpack type
// guards). During build, we filter out .next/dev/types files so a dev
// session's stale types can't cause errors when routes have been deleted
// since. Build also removes the dev types of a stopped dev server (see
// `removeStaleDevTypes`), but keeps those of a running one.
let fileNames = effectiveConfiguration.fileNames
// Get the dev types path to filter (null if not applicable)
......
import path from 'path'
import type { NextConfigComplete } from '../../server/config-shared'
/**
* Route types are generated into one directory shared by `next dev`,
* `next build` and `next typegen`: `{getSharedTypesDistDir(config)}/types`
* (see `generateSharedTypes`).
*
* Kept separate from the generator so modules that only need the location
* (e.g. `next test`) don't load route discovery.
*/
export function getSharedTypesDistDir(
config: Pick<NextConfigComplete, 'output' | 'distDirRoot'>
): string {
// With `output: 'export'`, a custom `distDir` is the export destination and
// is replaced by every build, while build artifacts live in `.next` (see
// `getBuildDistDir`). Keep the shared types there, too. `distDirRoot` is
// the configured `distDir` before `next dev` appends `dev`.
return config.output === 'export' && config.distDirRoot !== '.next'
? '.next'
: config.distDirRoot
}
export function getSharedTypesDir(
dir: string,
config: Pick<NextConfigComplete, 'output' | 'distDirRoot'>
): string {
return path.join(dir, getSharedTypesDistDir(config), 'types')
}
This diff is collapsed.
......@@ -2,15 +2,22 @@ import path from 'path'
/**
* Gets the glob patterns for type definition directories in tsconfig.
* Next.js uses different distDir paths in development vs production:
* - Development: "{distDir}/dev"
* - Production: "{distDir}"
* - "{typesDistDir}/types": route types shared by `next dev`, `next build`
* and `next typegen` (see `getSharedTypesDir`). Usually the same as
* "{distDir}/types", but not with `output: 'export'` and a custom `distDir`.
* - "{distDir}/types" and "{distDir}/dev/types": in dev, the latter holds the
* types only `next dev` writes (`env.d.ts`, webpack type guards).
* In development, the `distDir` passed in is "{distDir}/dev".
*/
export function getTypeDefinitionGlobPatterns(distDir: string): string[] {
const distDirPosix =
export function getTypeDefinitionGlobPatterns(
distDir: string,
typesDistDir?: string
): string[] {
const toPosix = (p: string) =>
path.win32.sep === path.sep
? distDir.replaceAll(path.win32.sep, path.posix.sep)
: distDir
? p.replaceAll(path.win32.sep, path.posix.sep)
: p
const distDirPosix = toPosix(distDir)
const typeGlobPatterns: string[] = [`${distDirPosix}/types/**/*.ts`]
......@@ -24,6 +31,12 @@ export function getTypeDefinitionGlobPatterns(distDir: string): string[] {
: // In build, distDir is "{distDir}", so also include "{distDir}/dev/types"
`${distDirPosix}/dev/types/**/*.ts`
)
if (typesDistDir !== undefined) {
const sharedTypes = `${toPosix(typesDistDir)}/types/**/*.ts`
if (!typeGlobPatterns.includes(sharedTypes)) {
typeGlobPatterns.push(sharedTypes)
}
}
// Sort for consistent order
typeGlobPatterns.sort((a, b) => a.length - b.length)
......
......@@ -143,6 +143,37 @@ describe('writeConfigurationDefaults()', () => {
)
})
it('includes the shared types directory when it differs from distDir', async () => {
await writeFile(
tsConfigPath,
JSON.stringify({ compilerOptions: {}, include: ['next-env.d.ts'] }),
{ encoding: 'utf8' }
)
// `output: 'export'` with a custom distDir keeps the shared types in .next.
await writeConfigurationDefaults(
ts.version,
tsConfigPath,
isFirstTimeSetup,
hasAppDir,
'custom-out',
hasPagesDir,
false,
'.next'
)
const { include } = JSON.parse(
await readFile(tsConfigPath, { encoding: 'utf8' })
)
expect(include).toEqual(
expect.arrayContaining([
'custom-out/types/**/*.ts',
'custom-out/dev/types/**/*.ts',
'.next/types/**/*.ts',
])
)
})
it('uses bundler moduleResolution for TypeScript 6+', async () => {
await writeFile(tsConfigPath, JSON.stringify({ compilerOptions: {} }), {
encoding: 'utf8',
......
......@@ -209,7 +209,12 @@ export async function writeConfigurationDefaults(
hasAppDir: boolean,
distDir: string,
hasPagesDir: boolean,
strictRouteTypes: boolean
strictRouteTypes: boolean,
/**
* The `distDir` of the route types shared by all commands (see
* `getSharedTypesDir`). Defaults to `distDir`.
*/
typesDistDir: string = distDir
): Promise<void> {
if (isFirstTimeSetup) {
writeFileSync(tsConfigPath, '{}' + os.EOL)
......@@ -288,7 +293,7 @@ export async function writeConfigurationDefaults(
// Get type definition glob patterns using shared utility to ensure consistency
// with other TypeScript infrastructure (e.g., runTypeCheck.ts)
const nextTypes = getTypeDefinitionGlobPatterns(distDir)
const nextTypes = getTypeDefinitionGlobPatterns(distDir, typesDistDir)
if (!('include' in userTsConfig)) {
const defaultInclude =
......
......@@ -54,6 +54,7 @@ const requiredTypePackages: MissingDependency[] = [
export async function verifyAndRunTypeScript({
dir,
distDir,
typesDistDir = distDir,
cacheDir,
strictRouteTypes,
tsconfigPath,
......@@ -70,6 +71,12 @@ export async function verifyAndRunTypeScript({
}: {
dir: string
distDir: string
/**
* The `distDir` whose `types` directory `next-env.d.ts` imports: the shared
* types directory (`{distDirRoot}/types`, see `getSharedTypesDir`). Defaults
* to `distDir`.
*/
typesDistDir?: string
cacheDir?: string
strictRouteTypes: boolean
tsconfigPath: string | undefined
......@@ -151,7 +158,7 @@ export async function verifyAndRunTypeScript({
// Still write type declarations since they don't require the typescript package
await writeAppTypeDeclarations({
baseDir: dir,
distDir,
distDir: typesDistDir,
imageImportsEnabled: !disableStaticImages,
hasPagesDir,
hasAppDir,
......@@ -236,13 +243,14 @@ export async function verifyAndRunTypeScript({
hasAppDir,
distDir,
hasPagesDir,
strictRouteTypes
strictRouteTypes,
typesDistDir
)
// Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types:
await writeAppTypeDeclarations({
baseDir: dir,
distDir,
distDir: typesDistDir,
imageImportsEnabled: !disableStaticImages,
hasPagesDir,
hasAppDir,
......
import type { LoadedEnvFiles } from '@next/env'
import { join } from 'node:path'
import { writeFile } from 'node:fs/promises'
import { mkdir, writeFile } from 'node:fs/promises'
export async function createEnvDefinitions({
distDir,
......@@ -38,9 +38,9 @@ export {}`
}
try {
// we expect the types directory to already exist
const envDtsPath = join(distDir, 'types', 'env.d.ts')
await writeFile(envDtsPath, definitionStr, 'utf-8')
const typesDir = join(distDir, 'types')
await mkdir(typesDir, { recursive: true })
await writeFile(join(typesDir, 'env.d.ts'), definitionStr, 'utf-8')
} catch (e) {
console.error('Failed to write env.d.ts:', e)
}
......
import type { CacheLife } from '../../use-cache/cache-life'
import fs from 'fs'
import path from 'path'
const MINUTE_IN_SECONDS = 60
const HOUR_IN_SECONDS = MINUTE_IN_SECONDS * 60 // nevermind leap seconds
......@@ -158,26 +156,3 @@ declare module 'next/cache' {
}
`
}
/**
* Writes cache-life type definitions to a file if cacheLifeConfig exists.
* This is used by both the CLI (next type-gen) and dev server to generate
* cache-life.d.ts in the types directory.
*/
export function writeCacheLifeTypes(
cacheLifeConfig: undefined | { [profile: string]: CacheLife },
filePath: string
) {
if (!cacheLifeConfig || Object.keys(cacheLifeConfig).length === 0) {
return
}
const dirname = path.dirname(filePath)
if (!fs.existsSync(dirname)) {
fs.mkdirSync(dirname, { recursive: true })
}
const content = generateCacheLifeTypes(cacheLifeConfig)
fs.writeFileSync(filePath, content)
}
import fs from 'fs'
import path from 'path'
import type { RouteTypesManifest } from './route-types-utils'
export type RootParamValueType = 'string' | 'string[]' | 'undefined'
......@@ -44,25 +42,18 @@ function getRootParamReturnType(valueTypes: RootParamInfo): string {
}
/**
* Writes root-params type definitions to a file if root params were collected
* from layouts.
* Returns the root-params type definitions for the root params collected from
* layouts. Without root params this is an empty declaration, so the import in
* next-env.d.ts still resolves.
*/
export async function writeRootParamsTypes(
manifest: RouteTypesManifest,
filePath: string
) {
export function generateRootParamsFileContent(
manifest: RouteTypesManifest
): string {
const rootParams = manifest.rootParams
await fs.promises.mkdir(path.dirname(filePath), { recursive: true })
if (!rootParams.size) {
// Write an empty declaration so the import in next-env.d.ts resolves.
await fs.promises.writeFile(
filePath,
`// Type definitions for Next.js root params (next/root-params)\n// No root params detected.\nexport {}\n`
)
return
return `// Type definitions for Next.js root params (next/root-params)\n// No root params detected.\nexport {}\n`
}
await fs.promises.writeFile(filePath, generateRootParamsTypes(rootParams))
return generateRootParamsTypes(rootParams)
}
......@@ -5,14 +5,6 @@ import {
} from '../../../shared/lib/router/utils/route-regex'
import type { NextConfigComplete } from '../../config-shared'
import fs from 'fs'
import {
generateRouteTypesFile,
generateLinkTypesFile,
generateValidatorFile,
generateValidatorFileStrict,
generateRouteTypesFileStrict,
} from './typegen'
import { tryToParsePath } from '../../../lib/try-to-parse-path'
import {
extractInterceptionRouteInformation,
......@@ -419,48 +411,3 @@ export async function createRouteTypesManifest({
return manifest
}
export async function writeRouteTypesManifest(
manifest: RouteTypesManifest,
filePath: string,
config: NextConfigComplete
) {
const dirname = path.dirname(filePath)
if (!fs.existsSync(dirname)) {
await fs.promises.mkdir(dirname, { recursive: true })
}
// Write the main routes.d.ts file
await fs.promises.writeFile(
filePath,
config.experimental.strictRouteTypes
? generateRouteTypesFileStrict(manifest)
: generateRouteTypesFile(manifest)
)
// Write the link.d.ts file if typedRoutes is enabled
if (config.typedRoutes === true) {
const linkTypesPath = path.join(dirname, 'link.d.ts')
await fs.promises.writeFile(linkTypesPath, generateLinkTypesFile(manifest))
}
}
export async function writeValidatorFile(
manifest: RouteTypesManifest,
filePath: string,
strict: boolean
) {
const dirname = path.dirname(filePath)
if (!fs.existsSync(dirname)) {
await fs.promises.mkdir(dirname, { recursive: true })
}
await fs.promises.writeFile(
filePath,
strict
? generateValidatorFileStrict(manifest)
: generateValidatorFile(manifest)
)
}
......@@ -104,23 +104,20 @@ import { IncompatibleParallelRouteSlotsError } from '../../../shared/lib/errors/
import { findMissingCanonicalInterceptionRoutes } from '../../../shared/lib/router/utils/interception-routes'
import { getStrictRouteMatchingDefaultWarning } from './strict-route-matching-config'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
writeValidatorFile,
} from './route-types-utils'
import { writeCacheLifeTypes } from './cache-life-type-utils'
import { writeRootParamsTypes } from './root-params-type-utils'
createSharedTypesScheduler,
generateSharedTypes,
writeSharedTypePlaceholders,
} from '../../../lib/typescript/shared-types'
import {
addSlotIfNew,
type RouteInfo,
type SlotInfo,
} from '../../../build/file-classifier'
getSharedTypesDir,
getSharedTypesDistDir,
} from '../../../lib/typescript/shared-types-dir'
import type { RouteInfo } from '../../../build/file-classifier'
import {
normalizeAppPath,
compareAppPaths,
selectAppPageEntry,
} from '../../../shared/lib/router/utils/app-paths'
import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash'
import { Lockfile, type DevServerInfo } from '../../../build/lockfile'
import { deobfuscateText } from '../../../shared/lib/magic-identifier'
import { RouteKind } from '../../route-kind'
......@@ -179,6 +176,9 @@ async function verifyTypeScript(opts: SetupOpts) {
const verifyResult = await verifyAndRunTypeScript({
dir: opts.dir,
distDir: opts.nextConfig.distDir,
// `next-env.d.ts` imports the types shared with `next build` and
// `next typegen`, see `getSharedTypesDir`.
typesDistDir: getSharedTypesDistDir(opts.nextConfig),
strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes),
shouldRunTypeCheck: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
......@@ -301,26 +301,33 @@ async function startWatcher(
await hotReloader.start()
const distTypesDir = path.join(distDir, 'types')
await writeRouteTypesManifest(
{
appRoutes: {},
pageRoutes: {},
layoutRoutes: {},
appRouteHandlerRoutes: {},
redirectRoutes: {},
rewriteRoutes: {},
appPagePaths: new Set(),
pagesRouterPagePaths: new Set(),
layoutPaths: new Set(),
appRouteHandlers: new Set(),
pageApiRoutes: new Set(),
filePathToRoute: new Map(),
rootParams: new Map(),
},
path.join(distTypesDir, 'routes.d.ts'),
opts.nextConfig
// Route types are shared with `next build` and `next typegen`. Create any
// missing file `next-env.d.ts` imports so the imports resolve, then
// generate them in the background without delaying startup.
await writeSharedTypePlaceholders({
typesDir: getSharedTypesDir(opts.dir, nextConfig),
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
typedRoutes: nextConfig.typedRoutes === true,
}).catch((err) => {
Log.warn('Failed to create route type placeholders:', err)
})
// Copies of these types that older versions wrote to the dev `distDir` are
// gone: the hot reloader cleans the dev `distDir` when it starts.
const sharedTypes = createSharedTypesScheduler(() =>
generateSharedTypes({
dir: opts.dir,
config: nextConfig,
appDir,
pagesDir,
})
)
// Generate once on startup, also when Watchpack never reports an aggregation
// (e.g. empty route directories).
sharedTypes.schedule()
// The route files that were last used to generate the shared types. Their
// contents don't affect the generated types, so only additions and
// removals regenerate them.
let sharedTypesRouteFilesKey: string | undefined
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: DevRoutesManifest = {
......@@ -469,9 +476,6 @@ async function startWatcher(
let hadInitialScan = false
let previousDuplicatePagePaths: Set<string> = new Set()
const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts')
const validatorFilePath = path.join(distDir, 'types', 'validator.ts')
let initialWatchTime = performance.now() + performance.timeOrigin
// Startup only waits this long for Watchpack to observe the files found by
// the snapshot above, so a file it never reports cannot stall the server.
......@@ -511,9 +515,6 @@ async function startWatcher(
const appRouteHandlers: Array<RouteInfo & { page: string }> = []
const pageApiRoutes: RouteInfo[] = []
const pageRoutes: RouteInfo[] = []
const appRoutes: RouteInfo[] = []
const layoutRoutes: RouteInfo[] = []
const slots: SlotInfo[] = []
let envFileChange = false
let clientRouterFiltersChange = false
......@@ -750,9 +751,6 @@ async function startWatcher(
// Skip files/directories starting with `_` in the app directory
if (normalizedPageName.includes('/_')) continue
// Record parallel route slots
addSlotIfNew(slots, normalizedPageName)
// Handle layouts separately - they don't get added to appPaths
if (validFileMatcher.isAppLayoutPage(fileName)) {
const layoutPath =
......@@ -760,10 +758,6 @@ async function startWatcher(
.replace(/%5F/g, '_')
.replace(/\/layout$/, '') || '/'
parallelRouteLayoutFiles.set(layoutPath, fileName)
const layoutRoute = ensureLeadingSlash(
normalizeAppPath(normalizedPageName).replace(/\/layout$/, '')
)
layoutRoutes.push({ route: layoutRoute, filePath: fileName })
continue
}
......@@ -777,7 +771,6 @@ async function startWatcher(
const originalPageName = pageName
pageName = normalizeAppPath(pageName).replace(/%5F/g, '_')
const appRoute = normalizePathSep(pageName)
const appPath = opts.turbo
? originalPageName.replace(/%5F/g, '_')
: originalPageName
......@@ -802,11 +795,12 @@ async function startWatcher(
}
}
const routeEntry = { route: appRoute, filePath: fileName }
if (isAppRouteRoute(appPath)) {
appRouteHandlers.push({ ...routeEntry, page: appPath })
} else {
appRoutes.push(routeEntry)
appRouteHandlers.push({
route: normalizePathSep(pageName),
filePath: fileName,
page: appPath,
})
}
if (routedPages.includes(pageName)) continue
......@@ -1436,40 +1430,24 @@ async function startWatcher(
})
}
const routeTypesManifest = await createRouteTypesManifest({
dir,
pageRoutes,
appRoutes,
layoutRoutes,
slots,
redirects: opts.nextConfig.redirects,
rewrites: opts.nextConfig.rewrites,
// Ensure relative paths in validator.ts are computed from validatorFilePath,
// matching behavior of build and CLI typegen.
validatorFilePath,
appRouteHandlers,
pageApiRoutes,
})
await writeRouteTypesManifest(
routeTypesManifest,
routeTypesFilePath,
opts.nextConfig
)
await writeValidatorFile(
routeTypesManifest,
validatorFilePath,
Boolean(nextConfig.experimental.strictRouteTypes)
)
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = path.join(distTypesDir, 'cache-life.d.ts')
writeCacheLifeTypes(opts.nextConfig.cacheLife, cacheLifeFilePath)
await writeRootParamsTypes(
routeTypesManifest,
path.join(distTypesDir, 'root-params.d.ts')
)
// Regenerate the shared route types when route files were added or
// removed. Debounced, and never runs concurrently with itself.
const routeFilesKey = [...devPageFiles]
.filter(
(file) =>
!appDir ||
!normalizePathSep(file).startsWith(
normalizePathSep(appDir) + '/'
) ||
validFileMatcher.isAppRouterPage(file) ||
validFileMatcher.isAppLayoutPage(file) ||
validFileMatcher.isAppDefaultPage(file)
)
.join('\n')
if (routeFilesKey !== sharedTypesRouteFilesKey) {
sharedTypesRouteFilesKey = routeFilesKey
sharedTypes.schedule()
}
}
if (!resolved) {
......
export default async function Page(props: PageProps<'/blog/[slug]'>) {
const { slug } = await props.params
return <p>{slug}</p>
}
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>
}
......@@ -6,19 +6,19 @@ import { retry, runNextCommand } from 'next-test-utils'
// The fixture lives in its own directory so this test file is not copied into
// the app, where `tsc` would type-check it.
const FIXTURE_DIR = join(__dirname, 'fixture')
const DEV_VALIDATOR = '.next/dev/types/validator.ts'
// Route types shared by `next dev`, `next build` and `next typegen`.
const VALIDATOR = '.next/types/validator.ts'
async function waitForDevValidator(
async function waitForValidator(
next: NextInstance,
route: string,
expected: string,
validator = DEV_VALIDATOR
expected: string
) {
// Compile the route so bundler-specific dev types are generated too.
expect((await next.fetch(route)).status).toBe(200)
await retry(
async () => {
const content = await next.readFile(validator).catch(() => '')
const content = await next.readFile(VALIDATOR).catch(() => '')
expect(content).toContain(expected)
},
5000,
......@@ -67,10 +67,10 @@ describe('stale-dev-types', () => {
},
})
it('should not fail build when .next/dev has stale types from deleted routes', async () => {
// Step 1: Wait for dev server to generate .next/dev/types/validator.ts
// that references temp-route
await waitForDevValidator(next, '/temp-route', 'temp-route/page')
it('should not fail build when next dev left types of deleted routes', async () => {
// Step 1: Wait for dev server to generate validator.ts that references
// temp-route
await waitForValidator(next, '/temp-route', 'temp-route/page')
// Step 2: Stop dev server
await next.stop()
......@@ -78,14 +78,14 @@ describe('stale-dev-types', () => {
// Step 3: Delete the temp-route (simulating user deleting a route)
await next.deleteFile('app/temp-route/page.tsx')
// Verify .next/dev/types/validator.ts still references deleted route (stale)
const staleValidator = await next.readFile(DEV_VALIDATOR)
// Verify validator.ts still references deleted route (stale)
const staleValidator = await next.readFile(VALIDATOR)
expect(staleValidator).toContain('temp-route/page')
// Step 4: Run build - should NOT fail due to stale .next/dev types
// Step 4: Run build - should NOT fail due to stale types
const { exitCode, cliOutput } = await next.build()
// Build should succeed - stale dev types should be excluded from type checking
// Build should succeed - the types are regenerated before type checking
expect(cliOutput).not.toContain(
"Cannot find module '../../../app/temp-route/page"
)
......@@ -98,13 +98,14 @@ describe('stale-dev-types', () => {
files: FIXTURE_DIR,
})
it('should not fail build when .next/dev has stale types from deleted routes', async () => {
await waitForDevValidator(next, '/temp-route', 'temp-route/page')
it('should not fail build when next dev left types of deleted routes', async () => {
await waitForValidator(next, '/temp-route', 'temp-route/page')
await next.stop()
await next.deleteFile('app/temp-route/page.tsx')
// The TypeScript CLI checks every file the tsconfig includes, so the
// stale .next/dev/types must be pruned before type checking.
// types must be regenerated and the .next/dev/types pruned before type
// checking.
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain(
......@@ -126,18 +127,14 @@ describe('stale-dev-types', () => {
})
it('should remove the dev types below the configured distDir', async () => {
const validator = 'custom-out/dev/types/validator.ts'
await waitForDevValidator(
next,
'/temp-route',
'temp-route/page',
validator
)
// The custom distDir is replaced by the export, so the shared types
// stay in .next.
await waitForValidator(next, '/temp-route', 'temp-route/page')
await next.stop()
await next.deleteFile('app/temp-route/page.tsx')
// With a custom export distDir, build artifacts are written to .next
// while `next dev` writes its types below the configured distDir.
// With a custom export distDir, build artifacts and shared types are
// written to .next while dev writes below the configured distDir.
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain(
......@@ -145,6 +142,7 @@ describe('stale-dev-types', () => {
)
expect(exitCode).toBe(0)
expect(await next.hasFile('custom-out/dev/types')).toBe(false)
expect(await next.readFile(VALIDATOR)).not.toContain('temp-route/page')
})
})
......@@ -153,8 +151,8 @@ describe('stale-dev-types', () => {
files: FIXTURE_DIR,
})
it('should not leave stale dev types that fail type checking', async () => {
await waitForDevValidator(next, '/before', 'before/layout')
it('should not leave stale types that fail type checking', async () => {
await waitForValidator(next, '/before', 'before/layout')
await next.stop()
// Prints the TypeScript output on failure.
......@@ -179,8 +177,8 @@ describe('stale-dev-types', () => {
files: FIXTURE_DIR,
})
it('should not leave stale dev types that fail type checking', async () => {
await waitForDevValidator(next, '/temp-route', 'temp-route/page')
it('should not leave stale types that fail type checking', async () => {
await waitForValidator(next, '/temp-route', 'temp-route/page')
await next.stop()
await next.deleteFile('app/temp-route/page.tsx')
......@@ -199,12 +197,17 @@ describe('stale-dev-types', () => {
})
it('should keep the dev types of the running dev server', async () => {
await waitForDevValidator(next, '/temp-route', 'temp-route/page')
await waitForValidator(next, '/temp-route', 'temp-route/page')
// Stands in for the mode-specific types `next dev` writes to
// .next/dev/types (`env.d.ts`, webpack type guards).
const devTypesFile = '.next/dev/types/env.d.ts'
await next.patchFile(devTypesFile, 'export {}\n')
await runTypegen(next)
// The running dev server owns .next/dev/types and keeps them up to date.
expect(await next.readFile(DEV_VALIDATOR)).toContain('temp-route/page')
expect(await next.hasFile(devTypesFile)).toBe(true)
expect(await next.readFile(VALIDATOR)).toContain('temp-route/page')
})
})
})
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import './.next/dev/types/routes.d.ts'
import './.next/dev/types/cache-life.d.ts'
import './.next/dev/types/validator.ts'
import './.next/types/routes.d.ts'
import './.next/types/cache-life.d.ts'
import './.next/types/validator.ts'
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
......@@ -14,18 +14,18 @@ const strictRouteTypes =
const nextEnvDts = strictRouteTypes
? `/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/root-params.d.ts";
import "./.next/dev/types/cache-life.d.ts";
import "./.next/dev/types/validator.ts";
import "./.next/types/routes.d.ts";
import "./.next/types/root-params.d.ts";
import "./.next/types/cache-life.d.ts";
import "./.next/types/validator.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
`
: `/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/root-params.d.ts";
import "./.next/types/routes.d.ts";
import "./.next/types/root-params.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
......
......@@ -21,8 +21,12 @@ describe.each([{ fixture: 'simple' }, { fixture: 'multiple-roots' }])(
}
it('should pass typecheck with generated root-params types', async () => {
// Route types are shared by all commands. `next dev` writes an empty
// placeholder first, so wait for the generated types.
await retry(async () => {
await next.readFile(`${next.distDir}/types/root-params.d.ts`)
expect(
await next.readFile('.next/types/root-params.d.ts')
).not.toContain('Types are being generated')
})
await next.stop()
......
......@@ -12,9 +12,9 @@ describe('param-matching-types', () => {
beforeAll(async () => {
await next.fetch('/')
await retry(async () => {
expect(
await next.readFile(`${next.distDir}/types/validator.ts`)
).toContain('unstable_generateParamMatching')
expect(await next.readFile('.next/types/validator.ts')).toContain(
'unstable_generateParamMatching'
)
})
})
......
import execa from 'execa'
import { nextTestSetup } from 'e2e-utils'
import { gate, getDistDir, retry } from 'next-test-utils'
import { gate, retry } from 'next-test-utils'
// TODO(deploy-test-completion): Re-enable this suite in deploy mode.
// It likely expects a local build failure instead of a successful deployment.
......@@ -20,9 +20,13 @@ describe('typed-routes-validator', () => {
}
try {
const dts = await next.readFile(`${getDistDir()}/types/validator.ts`)
// sanity check that dev generation is working
expect(dts).toContain('const handler = {} as typeof import(')
// Route types are shared by `next dev`, `next build` and `next typegen`.
// `next dev` generates them in the background.
await retry(async () => {
const dts = await next.readFile('.next/types/validator.ts')
// sanity check that dev generation is working
expect(dts).toContain('const handler = {} as typeof import(')
})
} finally {
if (isNextDev) {
await next.stop()
......
......@@ -11,14 +11,14 @@ describe('typed-links', () => {
it('should generate types for next/link', async () => {
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/link.d.ts`)
const dts = await next.readFile('.next/types/link.d.ts')
expect(dts).toContain(`declare module 'next/link'`)
})
})
it('should include handler route from app/api-test/route.ts in generated link route definitions', async () => {
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/link.d.ts`)
const dts = await next.readFile('.next/types/link.d.ts')
// Ensure the app route handler at app/api-test/route.ts ("/api-test") is present
expect(dts).toContain('`/api-test`')
})
......
......@@ -2,6 +2,9 @@ import { nextTestSetup } from 'e2e-utils'
import execa from 'execa'
import { retry } from 'next-test-utils'
// Route types are shared by `next dev`, `next build` and `next typegen`.
const SHARED_ROUTES_DTS = '.next/types/routes.d.ts'
const expectedDts = `
type AppRoutes = "/" | "/_shop/[[...category]]" | "/dashboard" | "/dashboard/settings" | "/docs/[...slug]" | "/gallery/photo/[id]" | "/project/[slug]"
type AppRouteHandlerRoutes = "/api-test" | "/api/docs/[...slug]" | "/api/shop/[[...category]]" | "/api/users/[id]"
......@@ -23,7 +26,7 @@ describe('typed-routes', () => {
it('should generate route types correctly', async () => {
// Route type generation happens after the "Ready" log fires; give it time.
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
const dts = await next.readFile(SHARED_ROUTES_DTS)
expect(dts).toContain(expectedDts)
}, 30000)
})
......@@ -32,7 +35,7 @@ describe('typed-routes', () => {
// Wait for routes.d.ts before stopping the server; route type generation
// happens after the "Ready" log fires and tsc may run before it completes.
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
const dts = await next.readFile(SHARED_ROUTES_DTS)
expect(dts).toContain(expectedDts)
}, 30000)
......@@ -55,7 +58,7 @@ describe('typed-routes', () => {
it('should correctly convert custom route patterns from path-to-regexp to bracket syntax', async () => {
// Route type generation happens after the "Ready" log fires; give it time.
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
const dts = await next.readFile(SHARED_ROUTES_DTS)
// Test standard dynamic segment: :slug -> [slug]
expect(dts).toContain('"/project/[slug]"')
......@@ -82,9 +85,7 @@ describe('typed-routes', () => {
)
await retry(async () => {
const routeTypesContent = await next.readFile(
`${next.distDir}/types/routes.d.ts`
)
const routeTypesContent = await next.readFile(SHARED_ROUTES_DTS)
expect(routeTypesContent).toContain(
'type LayoutRoutes = "/" | "/dashboard" | "/new-layout"'
......@@ -95,7 +96,7 @@ describe('typed-routes', () => {
it('should generate RouteContext type for route handlers', async () => {
await retry(async () => {
const dts = await next.readFile(`${next.distDir}/types/routes.d.ts`)
const dts = await next.readFile(SHARED_ROUTES_DTS)
expect(dts).toContain(
'interface RouteContext<AppRouteHandlerRoute extends AppRouteHandlerRoutes>'
)
......
......@@ -16,8 +16,12 @@ describe('cache-life-typecheck', () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('hello world')
// Route types are shared by all commands. `next dev` writes an empty
// placeholder first, so wait for the generated types.
await retry(async () => {
await next.readFile(`${next.distDir}/types/cache-life.d.ts`)
expect(await next.readFile('.next/types/cache-life.d.ts')).not.toContain(
'Types are being generated'
)
}, 10_000)
await next.stop()
......
......@@ -343,6 +343,8 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/typescript/runTypeCheck.js",
"/node_modules/next/dist/lib/typescript/runTypeCheckCli.js",
"/node_modules/next/dist/lib/typescript/runTypeScriptCli.js",
"/node_modules/next/dist/lib/typescript/shared-types-dir.js",
"/node_modules/next/dist/lib/typescript/shared-types.js",
"/node_modules/next/dist/lib/typescript/type-paths.js",
"/node_modules/next/dist/lib/typescript/writeAppTypeDeclarations.js",
"/node_modules/next/dist/lib/typescript/writeConfigurationDefaults.js",
......
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