Unverified Commit 5ff005f7 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Refactor route types to include rewrites and redirects (#46327)

This PR refactors the implementation of `Route<T>` to be more compact
(2/3 fewer union types), and adds support for static rewrites and
redirects. Check the updated test for more details.

In the future I plan to continue to refactor this by extract static
routes out as unions (instead of always relying on type inference) for
better autocompletion. Maybe a dev-only feature?

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] 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 767e9216
import { LoadedEnvFiles } from '@next/env' import type { LoadedEnvFiles } from '@next/env'
import { Ora } from 'next/dist/compiled/ora' import type { Ora } from 'next/dist/compiled/ora'
import { Rewrite } from '../lib/load-custom-routes' import type { Rewrite, Redirect } from '../lib/load-custom-routes'
import { __ApiPreviewProps } from '../server/api-utils' import type { __ApiPreviewProps } from '../server/api-utils'
import { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import { Span } from '../trace' import type { Span } from '../trace'
import type getBaseWebpackConfig from './webpack-config' import type getBaseWebpackConfig from './webpack-config'
import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin' import type { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
// a global object to store context for the current build // a global object to store context for the current build
// this is used to pass data between different steps of the build without having // this is used to pass data between different steps of the build without having
...@@ -23,6 +23,12 @@ export const NextBuildContext: Partial<{ ...@@ -23,6 +23,12 @@ export const NextBuildContext: Partial<{
afterFiles: Rewrite[] afterFiles: Rewrite[]
beforeFiles: Rewrite[] beforeFiles: Rewrite[]
} }
originalRewrites: {
fallback: Rewrite[]
afterFiles: Rewrite[]
beforeFiles: Rewrite[]
}
originalRedirects: Redirect[]
loadedEnvFiles: LoadedEnvFiles loadedEnvFiles: LoadedEnvFiles
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
mappedPages: mappedPages:
......
...@@ -293,6 +293,8 @@ export default async function build( ...@@ -293,6 +293,8 @@ export default async function build(
const { headers, rewrites, redirects } = customRoutes const { headers, rewrites, redirects } = customRoutes
NextBuildContext.rewrites = rewrites NextBuildContext.rewrites = rewrites
NextBuildContext.originalRewrites = config._originalRewrites
NextBuildContext.originalRedirects = config._originalRedirects
const cacheDir = path.join(distDir, 'cache') const cacheDir = path.join(distDir, 'cache')
if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) { if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
......
...@@ -91,6 +91,8 @@ async function webpackBuildImpl(): Promise<{ ...@@ -91,6 +91,8 @@ async function webpackBuildImpl(): Promise<{
appDir: NextBuildContext.appDir!, appDir: NextBuildContext.appDir!,
pagesDir: NextBuildContext.pagesDir!, pagesDir: NextBuildContext.pagesDir!,
rewrites: NextBuildContext.rewrites!, rewrites: NextBuildContext.rewrites!,
originalRewrites: NextBuildContext.originalRewrites!,
originalRedirects: NextBuildContext.originalRedirects!,
reactProductionProfiling: NextBuildContext.reactProductionProfiling!, reactProductionProfiling: NextBuildContext.reactProductionProfiling!,
noMangling: NextBuildContext.noMangling!, noMangling: NextBuildContext.noMangling!,
clientRouterFilters: NextBuildContext.clientRouterFilters!, clientRouterFilters: NextBuildContext.clientRouterFilters!,
......
...@@ -615,6 +615,8 @@ export default async function getBaseWebpackConfig( ...@@ -615,6 +615,8 @@ export default async function getBaseWebpackConfig(
pagesDir, pagesDir,
reactProductionProfiling = false, reactProductionProfiling = false,
rewrites, rewrites,
originalRewrites,
originalRedirects,
runWebpackSpan, runWebpackSpan,
target = COMPILER_NAMES.server, target = COMPILER_NAMES.server,
appDir, appDir,
...@@ -634,6 +636,8 @@ export default async function getBaseWebpackConfig( ...@@ -634,6 +636,8 @@ export default async function getBaseWebpackConfig(
pagesDir?: string pagesDir?: string
reactProductionProfiling?: boolean reactProductionProfiling?: boolean
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
originalRewrites: CustomRoutes['rewrites']
originalRedirects: CustomRoutes['redirects']
runWebpackSpan: Span runWebpackSpan: Span
target?: string target?: string
appDir?: string appDir?: string
...@@ -2201,6 +2205,8 @@ export default async function getBaseWebpackConfig( ...@@ -2201,6 +2205,8 @@ export default async function getBaseWebpackConfig(
isEdgeServer, isEdgeServer,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
typedRoutes: enableTypedRoutes, typedRoutes: enableTypedRoutes,
originalRewrites,
originalRedirects,
}), }),
!dev && !dev &&
isClient && isClient &&
......
import type { Rewrite, Redirect } from '../../../lib/load-custom-routes'
import type { Token } from 'next/dist/compiled/path-to-regexp'
import path from 'path' import path from 'path'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { parse } from 'next/dist/compiled/path-to-regexp'
import { WEBPACK_LAYERS } from '../../../lib/constants' import { WEBPACK_LAYERS } from '../../../lib/constants'
import { isDynamicRoute } from '../../../shared/lib/router/utils' import { isDynamicRoute } from '../../../shared/lib/router/utils'
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
...@@ -11,6 +15,12 @@ import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading ...@@ -11,6 +15,12 @@ import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading
const PLUGIN_NAME = 'NextTypesPlugin' const PLUGIN_NAME = 'NextTypesPlugin'
type Rewrites = {
fallback: Rewrite[]
afterFiles: Rewrite[]
beforeFiles: Rewrite[]
}
interface Options { interface Options {
dir: string dir: string
distDir: string distDir: string
...@@ -19,6 +29,8 @@ interface Options { ...@@ -19,6 +29,8 @@ interface Options {
isEdgeServer: boolean isEdgeServer: boolean
pageExtensions: string[] pageExtensions: string[]
typedRoutes: boolean typedRoutes: boolean
originalRewrites: Rewrites
originalRedirects: Redirect[]
} }
function createTypeGuardFile( function createTypeGuardFile(
...@@ -122,28 +134,110 @@ async function collectNamedSlots(layoutPath: string) { ...@@ -122,28 +134,110 @@ async function collectNamedSlots(layoutPath: string) {
return slots return slots
} }
const edgeRouteTypes: string[] = [] export const devPageFiles = new Set<string>()
const nodeRouteTypes: string[] = []
export const pageFiles = new Set<string>() const edgeRoutes: string[] = []
const nodeRoutes: string[] = []
function createRouteDefinitions() { function createRouteDefinitions(rewrites: Rewrites, redirects: Redirect[]) {
const fallback = const extraRoutes: string[] = []
!edgeRouteTypes.length && !nodeRouteTypes.length ? 'string' : '' function addExtraRoute(source: string) {
let tokens: Token[] | undefined
try {
tokens = parse(source)
} catch {
// Ignore invalid routes - they will be handled by other checks.
}
let routeTypes = '' if (Array.isArray(tokens)) {
let normalizedRoute = ''
edgeRouteTypes.forEach((route) => { for (const token of tokens) {
routeTypes += ` | ${route}\n ` if (typeof token === 'object') {
}) if (token.modifier === '*') {
nodeRouteTypes.forEach((route) => { normalizedRoute += `${token.prefix}[[...${token.name}]]`
routeTypes += ` | ${route}\n ` } else if (token.modifier === '+') {
}) normalizedRoute += `${token.prefix}[...${token.name}]`
} else {
normalizedRoute += `${token.prefix}[${token.name}]`
// TODO: Optional modifier `?` is not supported yet.
}
} else if (typeof token === 'string') {
normalizedRoute += token
}
}
return `declare module 'next' { extraRoutes.push(normalizedRoute)
export { default } from 'next/types' }
export * from 'next/types' }
for (const rewrite of rewrites.beforeFiles) {
addExtraRoute(rewrite.source)
}
for (const rewrite of rewrites.afterFiles) {
addExtraRoute(rewrite.source)
}
for (const rewrite of rewrites.fallback) {
addExtraRoute(rewrite.source)
}
for (const redirect of redirects) {
// Skip internal redirects
// https://github.com/vercel/next.js/blob/8ff3d7ff57836c24088474175d595b4d50b3f857/packages/next/src/lib/load-custom-routes.ts#L704-L710
if (!('internal' in redirect)) {
addExtraRoute(redirect.source)
}
}
const fallback = !edgeRoutes.length && !nodeRoutes.length ? 'string' : ''
const routes = [...edgeRoutes, ...nodeRoutes, ...extraRoutes]
// 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 dynamicRouteTypes = ''
function addRouteToRouteTypes(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('/')
}
if (isDynamic) {
dynamicRouteTypes += `\n | \`${route}\``
} else {
staticRouteTypes += `\n | \`${route}\``
}
}
for (const route of routes) {
addRouteToRouteTypes(route)
}
return `// Type definitions for Next.js routes
/**
* Internal types used by the Next.js router and Link component.
* These types are not meant to be used directly.
* @internal
*/
declare namespace __next_route_internal_types__ {
type SearchOrHash = \`?\${string}\` | \`#\${string}\` type SearchOrHash = \`?\${string}\` | \`#\${string}\`
type Suffix = '' | SearchOrHash type Suffix = '' | SearchOrHash
...@@ -165,10 +259,22 @@ function createRouteDefinitions() { ...@@ -165,10 +259,22 @@ function createRouteDefinitions() {
type OptionalCatchAllSlug<S extends string> = type OptionalCatchAllSlug<S extends string> =
S extends \`\${string}\${SearchOrHash}\` ? never : S S extends \`\${string}\${SearchOrHash}\` ? never : S
export type Route<T extends string = string> = ${fallback} type StaticRoutes = ${staticRouteTypes}
${routeTypes} type DynamicRoutes<T extends string = string> = ${dynamicRouteTypes}
type RouteImpl<T> = ${fallback}
| StaticRoutes
| \`\${StaticRoutes}\${SearchOrHash}\`
| (T extends \`\${DynamicRoutes<infer _>}\${'' | SearchOrHash}\` ? T : never)
} }
declare module 'next' {
export { default } from 'next/types'
export * from 'next/types'
export type Route<T = any> = __next_route_internal_types__.RouteImpl<T>
}
declare module 'next/link' { declare module 'next/link' {
import type { Route } from 'next' import type { Route } from 'next'
import type { LinkProps as OriginalLinkProps } from 'next/dist/client/link' import type { LinkProps as OriginalLinkProps } from 'next/dist/client/link'
...@@ -178,20 +284,12 @@ declare module 'next/link' { ...@@ -178,20 +284,12 @@ declare module 'next/link' {
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. // If the href prop can be a Route type with an infer-able S, it's valid.
type HrefProp<T> = T extends (Route<infer S> | UrlObject) ? { 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
* https://nextjs.org/docs/api-reference/next/link
*/ */
href: T href: __next_route_internal_types__.RouteImpl<T> | UrlObject
} : {
/**
* The path or URL to navigate to. This is the only required prop. It can also be an object.
*
* https://nextjs.org/docs/api-reference/next/link
*/
href: never
} }
export type LinkProps<T> = LinkRestProps & HrefProp<T> export type LinkProps<T> = LinkRestProps & HrefProp<T>
...@@ -208,6 +306,8 @@ export class NextTypesPlugin { ...@@ -208,6 +306,8 @@ export class NextTypesPlugin {
pageExtensions: string[] pageExtensions: string[]
pagesDir: string pagesDir: string
typedRoutes: boolean typedRoutes: boolean
originalRewrites: Rewrites
originalRedirects: Redirect[]
constructor(options: Options) { constructor(options: Options) {
this.dir = options.dir this.dir = options.dir
...@@ -218,6 +318,8 @@ export class NextTypesPlugin { ...@@ -218,6 +318,8 @@ 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
this.originalRedirects = options.originalRedirects
} }
collectPage(filePath: string) { collectPage(filePath: string) {
...@@ -247,29 +349,7 @@ export class NextTypesPlugin { ...@@ -247,29 +349,7 @@ export class NextTypesPlugin {
) )
) )
if (isDynamicRoute(route)) { ;(this.isEdgeServer ? edgeRoutes : nodeRoutes).push(route)
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('/')
}
;(this.isEdgeServer ? edgeRouteTypes : nodeRouteTypes).push(
`\`${route}\${Suffix}\``
)
} }
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
...@@ -354,9 +434,9 @@ export class NextTypesPlugin { ...@@ -354,9 +434,9 @@ export class NextTypesPlugin {
// Clear routes // Clear routes
if (this.isEdgeServer) { if (this.isEdgeServer) {
edgeRouteTypes.length = 0 edgeRoutes.length = 0
} else { } else {
nodeRouteTypes.length = 0 nodeRoutes.length = 0
} }
compilation.chunkGroups.forEach((chunkGroup: any) => { compilation.chunkGroups.forEach((chunkGroup: any) => {
...@@ -393,7 +473,7 @@ export class NextTypesPlugin { ...@@ -393,7 +473,7 @@ export class NextTypesPlugin {
if (this.typedRoutes) { if (this.typedRoutes) {
if (this.dev && !this.isEdgeServer) { if (this.dev && !this.isEdgeServer) {
pageFiles.forEach((file) => { devPageFiles.forEach((file) => {
this.collectPage(file) this.collectPage(file)
}) })
} }
...@@ -402,7 +482,10 @@ export class NextTypesPlugin { ...@@ -402,7 +482,10 @@ 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
} }
......
...@@ -609,6 +609,13 @@ async function loadRewrites(config: NextConfig) { ...@@ -609,6 +609,13 @@ async function loadRewrites(config: NextConfig) {
checkCustomRoutes(afterFiles, 'rewrite') checkCustomRoutes(afterFiles, 'rewrite')
checkCustomRoutes(fallback, 'rewrite') checkCustomRoutes(fallback, 'rewrite')
// save original rewrites before transforms
;(config as any)._originalRewrites = {
beforeFiles: beforeFiles.map((r) => ({ ...r })),
afterFiles: afterFiles.map((r) => ({ ...r })),
fallback: fallback.map((r) => ({ ...r })),
}
beforeFiles = processRoutes(beforeFiles, config, 'rewrite') beforeFiles = processRoutes(beforeFiles, config, 'rewrite')
afterFiles = processRoutes(afterFiles, config, 'rewrite') afterFiles = processRoutes(afterFiles, config, 'rewrite')
fallback = processRoutes(fallback, config, 'rewrite') fallback = processRoutes(fallback, config, 'rewrite')
......
...@@ -18,10 +18,10 @@ function getFormattedLinkDiagnosticMessageText( ...@@ -18,10 +18,10 @@ function getFormattedLinkDiagnosticMessageText(
if (typeof message === 'string' && diagnostic.code === 2322) { if (typeof message === 'string' && diagnostic.code === 2322) {
const match = const match =
message.match( message.match(
/Type '"(.+)"' is not assignable to type 'Route<string> | URL'\./ /Type '"(.+)"' is not assignable to type 'RouteImpl<.+> \| UrlObject'\./
) || ) ||
message.match( message.match(
/Type '"(.+)"' is not assignable to type 'URL | Route<string>'\./ /Type '"(.+)"' is not assignable to type 'UrlObject \| RouteImpl<.+>'\./
) )
if (match) { if (match) {
...@@ -29,14 +29,36 @@ function getFormattedLinkDiagnosticMessageText( ...@@ -29,14 +29,36 @@ function getFormattedLinkDiagnosticMessageText(
return `"${chalk.bold( return `"${chalk.bold(
href href
)}" is not an existing route. If it is intentional, please type it explicitly with \`as Route\`.` )}" is not an existing route. If it is intentional, please type it explicitly with \`as Route\`.`
} else if (message === "Type 'string' is not assignable to type 'never'.") { } else if (
message === "Type 'string' is not assignable to type 'UrlObject'."
) {
const relatedMessage = diagnostic.relatedInformation?.[0]?.messageText
if ( if (
diagnostic.relatedInformation?.[0]?.messageText === typeof relatedMessage === 'string' &&
`The expected type comes from property 'href' which is declared here on type 'IntrinsicAttributes & LinkRestProps & { href: never; }` relatedMessage.match(
/The expected type comes from property 'href' which is declared here on type 'IntrinsicAttributes & /
)
) { ) {
return `Invalid \`href\` property of \`Link\`: the route does not exist. If it is intentional, please type it explicitly with \`as Route\`.` return `Invalid \`href\` property of \`Link\`: the route does not exist. If it is intentional, please type it explicitly with \`as Route\`.`
} }
} }
} else if (typeof message === 'string' && diagnostic.code === 2820) {
const match =
message.match(
/Type '"(.+)"' is not assignable to type 'RouteImpl<.+> \| UrlObject'\. Did you mean '"(.+)"'?/
) ||
message.match(
/Type '"(.+)"' is not assignable to type 'UrlObject \| RouteImpl<.+>'\. Did you mean '"(.+)"'?/
)
if (match) {
const [, href, suggestion] = match
return `"${chalk.bold(
href
)}" is not an existing route. Did you mean "${chalk.bold(
suggestion
)}" instead? If it is intentional, please type it explicitly with \`as Route\`.`
}
} }
} }
......
...@@ -515,6 +515,8 @@ export default class HotReloader { ...@@ -515,6 +515,8 @@ export default class HotReloader {
config: this.config, config: this.config,
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
rewrites: this.rewrites, rewrites: this.rewrites,
originalRewrites: this.config._originalRewrites,
originalRedirects: this.config._originalRedirects,
runWebpackSpan: this.hotReloaderSpan, runWebpackSpan: this.hotReloaderSpan,
appDir: this.appDir, appDir: this.appDir,
} }
...@@ -572,6 +574,12 @@ export default class HotReloader { ...@@ -572,6 +574,12 @@ export default class HotReloader {
afterFiles: [], afterFiles: [],
fallback: [], fallback: [],
}, },
originalRewrites: {
beforeFiles: [],
afterFiles: [],
fallback: [],
},
originalRedirects: [],
isDevFallback: true, isDevFallback: true,
entrypoints: ( entrypoints: (
await createEntrypoints({ await createEntrypoints({
......
...@@ -81,7 +81,7 @@ import { ...@@ -81,7 +81,7 @@ import {
import { getDefineEnv } from '../../build/webpack-config' import { getDefineEnv } from '../../build/webpack-config'
import loadJsConfig from '../../build/load-jsconfig' import loadJsConfig from '../../build/load-jsconfig'
import { formatServerError } from '../../lib/format-server-error' import { formatServerError } from '../../lib/format-server-error'
import { pageFiles } from '../../build/webpack/plugins/next-types-plugin' import { devPageFiles } from '../../build/webpack/plugins/next-types-plugin'
import { import {
DevRouteMatcherManager, DevRouteMatcherManager,
RouteEnsurer, RouteEnsurer,
...@@ -428,7 +428,7 @@ export default class DevServer extends Server { ...@@ -428,7 +428,7 @@ export default class DevServer extends Server {
let envChange = false let envChange = false
let tsconfigChange = false let tsconfigChange = false
pageFiles.clear() devPageFiles.clear()
for (const [fileName, meta] of knownFiles) { for (const [fileName, meta] of knownFiles) {
if ( if (
...@@ -473,7 +473,7 @@ export default class DevServer extends Server { ...@@ -473,7 +473,7 @@ export default class DevServer extends Server {
) )
) )
pageFiles.add(fileName) devPageFiles.add(fileName)
const rootFile = absolutePathToPage(fileName, { const rootFile = absolutePathToPage(fileName, {
pagesDir: this.dir, pagesDir: this.dir,
......
...@@ -25,16 +25,9 @@ describe('app type checking', () => { ...@@ -25,16 +25,9 @@ describe('app type checking', () => {
expect(dts.includes('`/dashboard/user/')).toBeTruthy() expect(dts.includes('`/dashboard/user/')).toBeTruthy()
expect(dts.includes('`/dashboard/another')).toBeTruthy() expect(dts.includes('`/dashboard/another')).toBeTruthy()
expect(errors).toContain(
'Type error: "/(newroot)/dashboard/another" is not an existing route. If it is intentional, please type it explicitly with `as Route`.'
)
// Check type checking errors // Check type checking errors
expect(errors).toContain( expect(errors).toContain(
'Type error: "/dashboard" is not an existing route. If it is intentional, please type it explicitly with `as Route`.' 'Type error: "/(newroot)/dashboard/another" is not an existing route. If it is intentional, please type it explicitly with `as Route`.'
)
expect(errors).toContain(
'Type error: "/blog/a/b/c/d" is not an existing route.'
) )
// Make sure all errors were reported and other links passed type checking // Make sure all errors were reported and other links passed type checking
...@@ -43,7 +36,12 @@ describe('app type checking', () => { ...@@ -43,7 +36,12 @@ describe('app type checking', () => {
/\.\/src\/app\/type-checks\/link\/page\.tsx:(\d+):/g /\.\/src\/app\/type-checks\/link\/page\.tsx:(\d+):/g
), ),
].map(([, line]) => +line) ].map(([, line]) => +line)
expect(errorLines).toEqual([17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27])
const ST = 17
const ED = 33
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
}) })
it('should type check invalid entry exports', () => { it('should type check invalid entry exports', () => {
......
...@@ -3,4 +3,37 @@ export default { ...@@ -3,4 +3,37 @@ export default {
appDir: true, appDir: true,
typedRoutes: true, typedRoutes: true,
}, },
async rewrites() {
return [
{
source: '/rewrite',
destination: 'https://nextjs.org',
},
{
source: '/rewrite-any/(.*)',
destination: 'https://nextjs.org',
},
{
source: '/rewrite-one-or-more/:param+',
destination: 'https://nextjs.org',
},
{
source: '/rewrite-all/:param*',
destination: 'https://nextjs.org',
},
{
source: '/rewrite-param/:param/page',
destination: 'https://nextjs.org',
},
]
},
async redirects() {
return [
{
source: '/redirect',
destination: 'https://nextjs.org',
permanent: false,
},
]
},
} }
import type { Route } from 'next' import type { Route, Metadata } from 'next'
import Link from 'next/link' import Link from 'next/link'
function Card<T extends string>({ href }: { href: Route<T> | URL }) { export function Card<T>({ href }: { href: Route<T> | URL }) {
return ( return (
<Link href={href}> <Link href={href}>
<div>My Card</div> <div>My Card</div>
...@@ -21,10 +21,16 @@ export default function page() { ...@@ -21,10 +21,16 @@ export default function page() {
<Link href="/button">test</Link> <Link href="/button">test</Link>
<Link href="/buttooon">test</Link> <Link href="/buttooon">test</Link>
<Link href="/blog/">test</Link> <Link href="/blog/">test</Link>
<Link href="/blog/a?1/b">test</Link>
<Link href="/blog/a#1/b">test</Link>
<Link href="/blog/v/w/z">test</Link> <Link href="/blog/v/w/z">test</Link>
<Link href="/(newroot)/dashboard/another" /> <Link href="/(newroot)/dashboard/another" />
<Link href="/dashboard/">test</Link> <Link href="/dashboard/">test</Link>
<Link href={`/blog/a/${test}`}>test</Link> <Link href={`/blog/a/${test}`}>test</Link>
<Link href="/rewrite-any">test</Link>
<Link href="/rewrite-one-or-more/">test</Link>
<Link href="/rewrite-param/page">test</Link>
<Link href="/rewrite-param/x/page1">test</Link>
</> </>
) )
...@@ -32,6 +38,7 @@ export default function page() { ...@@ -32,6 +38,7 @@ export default function page() {
<> <>
<Card href="/dashboard/another" /> <Card href="/dashboard/another" />
<Card href="/aaa" /> <Card href="/aaa" />
<Card href="/blog/a/b?1" />
<Link href="/about">test</Link> <Link href="/about">test</Link>
<Link href="/aaa#aaa">test</Link> <Link href="/aaa#aaa">test</Link>
<Link href="/aaa?q=1">test</Link> <Link href="/aaa?q=1">test</Link>
...@@ -42,8 +49,16 @@ export default function page() { ...@@ -42,8 +49,16 @@ export default function page() {
<Link href="/dashboard/user">test</Link> <Link href="/dashboard/user">test</Link>
<Link href="/dashboard/user/">test</Link> <Link href="/dashboard/user/">test</Link>
<Link href="/dashboard/user/x">test</Link> <Link href="/dashboard/user/x">test</Link>
<Link href="/dashboard/x/x">test</Link>
<Link href={`/blog/${test}`}>test</Link> <Link href={`/blog/${test}`}>test</Link>
<Link href={('/blog/' + test) as Route}>test</Link> <Link href={('/blog/' + test) as Route}>test</Link>
<Link href="/rewrite">test</Link>
<Link href="/rewrite-any/x">test</Link>
<Link href="/rewrite-one-or-more/x/y">test</Link>
<Link href="/rewrite-all/x/y/z">test</Link>
<Link href="/rewrite-param/x/page?1">test</Link>
<Link href="/redirect">test</Link>
<Link href={new URL('/about')}>test</Link>
</> </>
) )
...@@ -54,3 +69,7 @@ export default function page() { ...@@ -54,3 +69,7 @@ export default function page() {
</> </>
) )
} }
export const metadata: Metadata = {
title: 'test',
}
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