Unverified Commit ceb028a4 authored by Ngô Đức Anh's avatar Ngô Đức Anh Committed by GitHub

Fix(typedRoutes): fixed type Route resolving to type any (#46679)



This PR makes `typedRoutes` stricter by constraining generics in  `Route` to type string. I've also made generating types for routes a bit more efficient by moving `redirects` and `rewrites`'s processing to the plugin's constructor since `rewrites` and `redirects` don't change in both dev and prod.

I've also been trying to fix a bug where route types doesn't generate all the routes (some appear, some don't), but I've got no clues since that doesn't seem easy to reproduce (perhaps it only happens in my case?)

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 7d5a213c
...@@ -136,14 +136,63 @@ async function collectNamedSlots(layoutPath: string) { ...@@ -136,14 +136,63 @@ async function collectNamedSlots(layoutPath: string) {
export const devPageFiles = new Set<string>() export const devPageFiles = new Set<string>()
const edgeRoutes: string[] = [] // By exposing the static route types separately as string literals,
const nodeRoutes: string[] = [] // editors can provide autocompletion for them. However it's currently not
// possible to provide the same experience for dynamic routes.
const routeTypes: Record<
'edge' | 'node' | 'extra',
Record<'static' | 'dynamic', string>
> = {
edge: {
static: '',
dynamic: '',
},
node: {
static: '',
dynamic: '',
},
extra: {
static: '',
dynamic: '',
},
}
function formatRouteToRouteType(route: string) {
const isDynamic = isDynamicRoute(route)
if (isDynamic) {
route = route
.split('/')
.map((part) => {
if (part.startsWith('[') && part.endsWith(']')) {
if (part.startsWith('[...')) {
// /[...slug]
return `\${CatchAllSlug<T>}`
} else if (part.startsWith('[[...') && part.endsWith(']]')) {
// /[[...slug]]
return `\${OptionalCatchAllSlug<T>}`
}
// /[slug]
return `\${SafeSlug<T>}`
}
return part
})
.join('/')
}
return {
isDynamic,
routeType: `\n | \`${route}\``,
}
}
function createRouteDefinitions( // Whether redirects and rewrites have been converted into routeTypes or not.
let redirectsRewritesTypesProcessed = false
// Convert redirects and rewrites into routeTypes.
function addRedirectsRewritesRouteTypes(
rewrites: Rewrites | undefined, rewrites: Rewrites | undefined,
redirects: Redirect[] | undefined redirects: Redirect[] | undefined
) { ) {
const extraRoutes: string[] = []
function addExtraRoute(source: string) { function addExtraRoute(source: string) {
let tokens: Token[] | undefined let tokens: Token[] | undefined
try { try {
...@@ -170,7 +219,9 @@ function createRouteDefinitions( ...@@ -170,7 +219,9 @@ function createRouteDefinitions(
} }
} }
extraRoutes.push(normalizedRoute) const { isDynamic, routeType } = formatRouteToRouteType(normalizedRoute)
routeTypes.extra[isDynamic ? 'dynamic' : 'static'] += routeType
} }
} }
...@@ -195,46 +246,15 @@ function createRouteDefinitions( ...@@ -195,46 +246,15 @@ function createRouteDefinitions(
} }
} }
} }
}
const routes = [...edgeRoutes, ...nodeRoutes, ...extraRoutes] function createRouteDefinitions() {
// By exposing the static route types separately as string literals,
// editors can provide autocompletion for them. However it's currently not
// possible to provide the same experience for dynamic routes.
let staticRouteTypes = '' let staticRouteTypes = ''
let dynamicRouteTypes = '' let dynamicRouteTypes = ''
function addRouteToRouteTypes(route: string) { for (const type of ['edge', 'node', 'extra'] as const) {
const isDynamic = isDynamicRoute(route) staticRouteTypes += routeTypes[type].static
if (isDynamic) { dynamicRouteTypes += routeTypes[type].dynamic
route = route
.split('/')
.map((part) => {
if (part.startsWith('[') && part.endsWith(']')) {
if (part.startsWith('[...')) {
// /[...slug]
return `\${CatchAllSlug<T>}`
} else if (part.startsWith('[[...') && part.endsWith(']]')) {
// /[[...slug]]
return `\${OptionalCatchAllSlug<T>}`
}
// /[slug]
return `\${SafeSlug<T>}`
}
return part
})
.join('/')
}
if (isDynamic) {
dynamicRouteTypes += `\n | \`${route}\``
} else {
staticRouteTypes += `\n | \`${route}\``
}
}
for (const route of routes) {
addRouteToRouteTypes(route)
} }
return `// Type definitions for Next.js routes return `// Type definitions for Next.js routes
...@@ -272,7 +292,9 @@ declare namespace __next_route_internal_types__ { ...@@ -272,7 +292,9 @@ declare namespace __next_route_internal_types__ {
} }
type RouteImpl<T> = type RouteImpl<T> =
| StaticRoutes ${
/* This keeps autocompletion working for static routes */ '| StaticRoutes'
}
| \`\${StaticRoutes}\${Suffix}\` | \`\${StaticRoutes}\${Suffix}\`
| (T extends \`\${DynamicRoutes<infer _>}\${Suffix}\` ? T : never) | (T extends \`\${DynamicRoutes<infer _>}\${Suffix}\` ? T : never)
} }
...@@ -281,7 +303,8 @@ declare module 'next' { ...@@ -281,7 +303,8 @@ declare module 'next' {
export { default } from 'next/types' export { default } from 'next/types'
export * from 'next/types' export * from 'next/types'
export type Route<T = any> = __next_route_internal_types__.RouteImpl<T> export type Route<T extends string = string> =
__next_route_internal_types__.RouteImpl<T>
} }
declare module 'next/link' { declare module 'next/link' {
...@@ -289,10 +312,13 @@ declare module 'next/link' { ...@@ -289,10 +312,13 @@ declare module 'next/link' {
import type { AnchorHTMLAttributes } from 'react' import type { AnchorHTMLAttributes } from 'react'
import type { UrlObject } from 'url' import type { UrlObject } from 'url'
type LinkRestProps = Omit<Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof OriginalLinkProps> & OriginalLinkProps, 'href'>; type LinkRestProps = Omit<
Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof OriginalLinkProps> &
OriginalLinkProps,
'href'
>
// If the href prop can be a Route type with an infer-able S, it's valid. export type LinkProps<T> = LinkRestProps & {
type HrefProp<T> = {
/** /**
* The path or URL to navigate to. This is the only required prop. It can also be an object. * The path or URL to navigate to. This is the only required prop. It can also be an object.
* @see https://nextjs.org/docs/api-reference/next/link * @see https://nextjs.org/docs/api-reference/next/link
...@@ -300,7 +326,6 @@ declare module 'next/link' { ...@@ -300,7 +326,6 @@ declare module 'next/link' {
href: __next_route_internal_types__.RouteImpl<T> | UrlObject href: __next_route_internal_types__.RouteImpl<T> | UrlObject
} }
export type LinkProps<T> = LinkRestProps & HrefProp<T>
export default function Link<RouteType>(props: LinkProps<RouteType>): JSX.Element export default function Link<RouteType>(props: LinkProps<RouteType>): JSX.Element
}` }`
} }
...@@ -314,8 +339,6 @@ export class NextTypesPlugin { ...@@ -314,8 +339,6 @@ export class NextTypesPlugin {
pageExtensions: string[] pageExtensions: string[]
pagesDir: string pagesDir: string
typedRoutes: boolean typedRoutes: boolean
originalRewrites: Rewrites | undefined
originalRedirects: Redirect[] | undefined
constructor(options: Options) { constructor(options: Options) {
this.dir = options.dir this.dir = options.dir
...@@ -326,8 +349,13 @@ export class NextTypesPlugin { ...@@ -326,8 +349,13 @@ export class NextTypesPlugin {
this.pageExtensions = options.pageExtensions this.pageExtensions = options.pageExtensions
this.pagesDir = path.join(this.appDir, '..', 'pages') this.pagesDir = path.join(this.appDir, '..', 'pages')
this.typedRoutes = options.typedRoutes this.typedRoutes = options.typedRoutes
this.originalRewrites = options.originalRewrites if (this.typedRoutes && !redirectsRewritesTypesProcessed) {
this.originalRedirects = options.originalRedirects redirectsRewritesTypesProcessed = true
addRedirectsRewritesRouteTypes(
options.originalRewrites,
options.originalRedirects
)
}
} }
collectPage(filePath: string) { collectPage(filePath: string) {
...@@ -357,7 +385,11 @@ export class NextTypesPlugin { ...@@ -357,7 +385,11 @@ export class NextTypesPlugin {
) )
) )
;(this.isEdgeServer ? edgeRoutes : nodeRoutes).push(route) const { isDynamic, routeType } = formatRouteToRouteType(route)
routeTypes[this.isEdgeServer ? 'edge' : 'node'][
isDynamic ? 'dynamic' : 'static'
] += routeType
} }
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
...@@ -371,9 +403,7 @@ export class NextTypesPlugin { ...@@ -371,9 +403,7 @@ export class NextTypesPlugin {
? '..' ? '..'
: '../..' : '../..'
const handleModule = async (_mod: webpack.Module, assets: any) => { const handleModule = async (mod: webpack.NormalModule, assets: any) => {
const mod: webpack.NormalModule = _mod as any
if (!mod.resource) return if (!mod.resource) return
if (!/\.(js|jsx|ts|tsx|mjs)$/.test(mod.resource)) return if (!/\.(js|jsx|ts|tsx|mjs)$/.test(mod.resource)) return
...@@ -387,7 +417,7 @@ export class NextTypesPlugin { ...@@ -387,7 +417,7 @@ export class NextTypesPlugin {
return return
} }
if (_mod.layer !== WEBPACK_LAYERS.server) return if (mod.layer !== WEBPACK_LAYERS.server) return
const IS_LAYOUT = /[/\\]layout\.[^./\\]+$/.test(mod.resource) const IS_LAYOUT = /[/\\]layout\.[^./\\]+$/.test(mod.resource)
const IS_PAGE = !IS_LAYOUT && /[/\\]page\.[^.]+$/.test(mod.resource) const IS_PAGE = !IS_LAYOUT && /[/\\]page\.[^.]+$/.test(mod.resource)
...@@ -421,13 +451,13 @@ export class NextTypesPlugin { ...@@ -421,13 +451,13 @@ export class NextTypesPlugin {
type: 'layout', type: 'layout',
slots, slots,
}) })
) as unknown as webpack.sources.RawSource )
} else if (IS_PAGE) { } else if (IS_PAGE) {
assets[assetPath] = new sources.RawSource( assets[assetPath] = new sources.RawSource(
createTypeGuardFile(mod.resource, relativeImportPath, { createTypeGuardFile(mod.resource, relativeImportPath, {
type: 'page', type: 'page',
}) })
) as unknown as webpack.sources.RawSource )
} }
} }
...@@ -442,13 +472,15 @@ export class NextTypesPlugin { ...@@ -442,13 +472,15 @@ export class NextTypesPlugin {
// Clear routes // Clear routes
if (this.isEdgeServer) { if (this.isEdgeServer) {
edgeRoutes.length = 0 routeTypes.edge.dynamic = ''
routeTypes.edge.static = ''
} else { } else {
nodeRoutes.length = 0 routeTypes.node.dynamic = ''
routeTypes.node.static = ''
} }
compilation.chunkGroups.forEach((chunkGroup: any) => { compilation.chunkGroups.forEach((chunkGroup) => {
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => { chunkGroup.chunks.forEach((chunk) => {
if (!chunk.name) return if (!chunk.name) return
// Here we only track page chunks. // Here we only track page chunks.
...@@ -467,9 +499,11 @@ export class NextTypesPlugin { ...@@ -467,9 +499,11 @@ export class NextTypesPlugin {
promises.push(handleModule(mod, assets)) promises.push(handleModule(mod, assets))
// If this is a concatenation, register each child to the parent ID. // If this is a concatenation, register each child to the parent ID.
const anyModule = mod as any const anyModule = mod as unknown as {
modules: webpack.NormalModule[]
}
if (anyModule.modules) { if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod: any) => { anyModule.modules.forEach((concatenatedMod) => {
promises.push(handleModule(concatenatedMod, assets)) promises.push(handleModule(concatenatedMod, assets))
}) })
} }
...@@ -490,10 +524,7 @@ export class NextTypesPlugin { ...@@ -490,10 +524,7 @@ export class NextTypesPlugin {
const assetPath = const assetPath =
assetDirRelative + '/' + linkTypePath.replace(/\\/g, '/') assetDirRelative + '/' + linkTypePath.replace(/\\/g, '/')
assets[assetPath] = new sources.RawSource( assets[assetPath] = new sources.RawSource(
createRouteDefinitions( createRouteDefinitions()
this.originalRewrites,
this.originalRedirects
)
) as unknown as webpack.sources.RawSource ) as unknown as webpack.sources.RawSource
} }
......
import { Metadata } from 'next' import { Metadata } from 'next'
export const meta: Metadata = { export const metadata: Metadata = {
title: 'My App', title: 'My App',
} }
......
import type { Route, Metadata } from 'next' import type { Route, Metadata } from 'next'
import Link from 'next/link' import Link from 'next/link'
export function Card<T>({ href }: { href: Route<T> | URL }) { export function Card<T extends string>({ href }: { href: Route<T> | URL }) {
return ( return (
<Link href={href}> <Link href={href}>
<div>My Card</div> <div>My Card</div>
......
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