Unverified Commit eead55cb authored by Jan Potoms's avatar Jan Potoms Committed by GitHub

Fix prefetch and some other issues with optional catch all (#14400)

Fix https://github.com/vercel/next.js/issues/14290 and a couple other issues around optional catch-all that popped up after writing these tests

Closes https://github.com/vercel/next.js/pull/14344
parent 051481c5
...@@ -143,17 +143,21 @@ export default class PageLoader { ...@@ -143,17 +143,21 @@ export default class PageLoader {
if ( if (
!Object.keys(dynamicGroups).every((param) => { !Object.keys(dynamicGroups).every((param) => {
let value = dynamicMatches[param] let value = dynamicMatches[param]
const repeat = dynamicGroups[param].repeat const { repeat, optional } = dynamicGroups[param]
// support single-level catch-all // support single-level catch-all
// TODO: more robust handling for user-error (passing `/`) // TODO: more robust handling for user-error (passing `/`)
if (repeat && !Array.isArray(value)) value = [value] if (repeat && !Array.isArray(value)) value = [value]
let replaced = `[${repeat ? '...' : ''}${param}]`
if (optional) {
replaced = `[${replaced}]`
}
return ( return (
param in dynamicMatches && param in dynamicMatches &&
// Interpolate group into data URL if present // Interpolate group into data URL if present
(interpolatedRoute = interpolatedRoute.replace( (interpolatedRoute = interpolatedRoute.replace(
`[${repeat ? '...' : ''}${param}]`, replaced,
repeat repeat
? value.map(encodeURIComponent).join('/') ? value.map(encodeURIComponent).join('/')
: encodeURIComponent(value) : encodeURIComponent(value)
......
...@@ -4,6 +4,20 @@ function escapeRegex(str: string) { ...@@ -4,6 +4,20 @@ function escapeRegex(str: string) {
return str.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&') return str.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')
} }
function parseParameter(param: string) {
const optional = /^\\\[.*\\\]$/.test(param)
if (optional) {
param = param.slice(2, -2)
}
const repeat = /^(\\\.){3}/.test(param)
if (repeat) {
param = param.slice(6)
}
// Un-escape key
const key = param.replace(/\\([|\\{}()[\]^$+*?.-])/g, '$1')
return { key, repeat, optional }
}
export function getRouteRegex( export function getRouteRegex(
normalizedRoute: string normalizedRoute: string
): { ): {
...@@ -25,21 +39,9 @@ export function getRouteRegex( ...@@ -25,21 +39,9 @@ export function getRouteRegex(
const parameterizedRoute = escapedRoute.replace( const parameterizedRoute = escapedRoute.replace(
/\/\\\[([^/]+?)\\\](?=\/|$)/g, /\/\\\[([^/]+?)\\\](?=\/|$)/g,
(_, $1) => { (_, $1) => {
const isOptional = /^\\\[.*\\\]$/.test($1) const { key, optional, repeat } = parseParameter($1)
if (isOptional) { groups[key] = { pos: groupIndex++, repeat, optional }
$1 = $1.slice(2, -2) return repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)'
}
const isCatchAll = /^(\\\.){3}/.test($1)
if (isCatchAll) {
$1 = $1.slice(6)
}
groups[
$1
// Un-escape key
.replace(/\\([|\\{}()[\]^$+*?.-])/g, '$1')
// eslint-disable-next-line no-sequences
] = { pos: groupIndex++, repeat: isCatchAll, optional: isOptional }
return isCatchAll ? (isOptional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)'
} }
) )
...@@ -53,21 +55,12 @@ export function getRouteRegex( ...@@ -53,21 +55,12 @@ export function getRouteRegex(
namedParameterizedRoute = escapedRoute.replace( namedParameterizedRoute = escapedRoute.replace(
/\/\\\[([^/]+?)\\\](?=\/|$)/g, /\/\\\[([^/]+?)\\\](?=\/|$)/g,
(_, $1) => { (_, $1) => {
const isCatchAll = /^(\\\.){3}/.test($1) const { key, repeat } = parseParameter($1)
const key = $1
// Un-escape key
.replace(/\\([|\\{}()[\]^$+*?.-])/g, '$1')
.replace(/^\.{3}/, '')
// replace any non-word characters since they can break // replace any non-word characters since they can break
// the named regex // the named regex
const cleanedKey = key.replace(/\W/g, '') const cleanedKey = key.replace(/\W/g, '')
routeKeys[cleanedKey] = key routeKeys[cleanedKey] = key
return repeat ? `/(?<${cleanedKey}>.+?)` : `/(?<${cleanedKey}>[^/]+?)`
return isCatchAll
? `/(?<${cleanedKey}>.+?)`
: `/(?<${cleanedKey}>[^/]+?)`
} }
) )
......
module.exports = { module.exports = {
experimental: { experimental: {
optionalCatchAll: true,
rewrites() { rewrites() {
return [ return [
{ {
......
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
return {
props: {
slug: slug || [],
},
}
}
export async function getStaticPaths() {
return {
paths: [{ params: { slug: [] } }, { params: { slug: ['value'] } }],
fallback: false,
}
}
export default ({ slug }) => {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="catchall">Catch all: [{slug.join(', ')}]</p>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
...@@ -47,6 +47,13 @@ const Page = ({ world, time }) => { ...@@ -47,6 +47,13 @@ const Page = ({ world, time }) => {
<Link href="/catchall/[...slug]" as="/catchall/first"> <Link href="/catchall/[...slug]" as="/catchall/first">
<a id="to-catchall">to catchall</a> <a id="to-catchall">to catchall</a>
</Link> </Link>
<br />
<Link href="/catchall-optional/[[...slug]]" as="/catchall-optional">
<a id="catchall-optional-root">to optional catchall root</a>
</Link>
<Link href="/catchall-optional/[[...slug]]" as="/catchall-optional/value">
<a id="catchall-optional-value">to optional catchall page /value</a>
</Link>
</> </>
) )
} }
......
...@@ -116,6 +116,16 @@ const expectedManifestRoutes = () => ({ ...@@ -116,6 +116,16 @@ const expectedManifestRoutes = () => ({
initialRevalidateSeconds: 1, initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]', srcRoute: '/catchall-explicit/[...slug]',
}, },
'/catchall-optional': {
dataRoute: `/_next/data/${buildId}/catchall-optional.json`,
initialRevalidateSeconds: false,
srcRoute: '/catchall-optional/[[...slug]]',
},
'/catchall-optional/value': {
dataRoute: `/_next/data/${buildId}/catchall-optional/value.json`,
initialRevalidateSeconds: false,
srcRoute: '/catchall-optional/[[...slug]]',
},
'/another': { '/another': {
dataRoute: `/_next/data/${buildId}/another.json`, dataRoute: `/_next/data/${buildId}/another.json`,
initialRevalidateSeconds: 1, initialRevalidateSeconds: 1,
...@@ -270,6 +280,28 @@ const navigateTest = (dev = false) => { ...@@ -270,6 +280,28 @@ const navigateTest = (dev = false) => {
await browser.elementByCss('#home').click() await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1') await browser.waitForElementByCss('#comment-1')
// go to /catchall-optional
await browser.elementByCss('#catchall-optional-root').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Catch all: \[\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-optional/value
await browser.elementByCss('#catchall-optional-value').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Catch all: \[value\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /blog/post-1/comment-1 // go to /blog/post-1/comment-1
await browser.elementByCss('#comment-1').click() await browser.elementByCss('#comment-1').click()
await browser.waitForElementByCss('#home') await browser.waitForElementByCss('#home')
...@@ -907,6 +939,20 @@ const runTests = (dev = false, isEmulatedServerless = false) => { ...@@ -907,6 +939,20 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
slug: 'slug', slug: 'slug',
}, },
}, },
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/catchall\\-optional/(?<slug>.+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`
),
page: '/catchall-optional/[[...slug]]',
routeKeys: {
slug: 'slug',
},
},
{ {
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex( `^\\/_next\\/data\\/${escapeRegex(
...@@ -1054,6 +1100,7 @@ const runTests = (dev = false, isEmulatedServerless = false) => { ...@@ -1054,6 +1100,7 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
`^\\/user\\/([^\\/]+?)\\/profile(?:\\/)?$` `^\\/user\\/([^\\/]+?)\\/profile(?:\\/)?$`
), ),
}, },
'/catchall/[...slug]': { '/catchall/[...slug]': {
fallback: '/catchall/[...slug].html', fallback: '/catchall/[...slug].html',
routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'), routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'),
...@@ -1062,6 +1109,16 @@ const runTests = (dev = false, isEmulatedServerless = false) => { ...@@ -1062,6 +1109,16 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\/(.+?)\\.json$` `^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\/(.+?)\\.json$`
), ),
}, },
'/catchall-optional/[[...slug]]': {
dataRoute: `/_next/data/${buildId}/catchall-optional/[[...slug]].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/catchall\\-optional(?:\\/(.+?))?(?:\\/)?$'
),
},
'/catchall-explicit/[...slug]': { '/catchall-explicit/[...slug]': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/[...slug].json`, dataRoute: `/_next/data/${buildId}/catchall-explicit/[...slug].json`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
...@@ -1213,6 +1270,7 @@ describe('SSG Prerender', () => { ...@@ -1213,6 +1270,7 @@ describe('SSG Prerender', () => {
` `
module.exports = { module.exports = {
experimental: { experimental: {
optionalCatchAll: true,
rewrites() { rewrites() {
return [ return [
{ {
...@@ -1253,7 +1311,7 @@ describe('SSG Prerender', () => { ...@@ -1253,7 +1311,7 @@ describe('SSG Prerender', () => {
nextConfig, nextConfig,
// we set cpus to 1 so that we make sure the requests // we set cpus to 1 so that we make sure the requests
// aren't being cached at the jest-worker level // aren't being cached at the jest-worker level
`module.exports = { experimental: { cpus: 1 } }`, `module.exports = { experimental: { optionalCatchAll: true, cpus: 1 } }`,
'utf8' 'utf8'
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
...@@ -1321,6 +1379,7 @@ describe('SSG Prerender', () => { ...@@ -1321,6 +1379,7 @@ describe('SSG Prerender', () => {
`module.exports = { `module.exports = {
target: 'serverless', target: 'serverless',
experimental: { experimental: {
optionalCatchAll: true,
rewrites() { rewrites() {
return [ return [
{ {
...@@ -1430,7 +1489,7 @@ describe('SSG Prerender', () => { ...@@ -1430,7 +1489,7 @@ describe('SSG Prerender', () => {
origConfig = await fs.readFile(nextConfig, 'utf8') origConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { target: 'experimental-serverless-trace' }`, `module.exports = { target: 'experimental-serverless-trace', experimental: { optionalCatchAll: true } }`,
'utf8' 'utf8'
) )
await fs.writeFile( await fs.writeFile(
...@@ -1516,6 +1575,7 @@ describe('SSG Prerender', () => { ...@@ -1516,6 +1575,7 @@ describe('SSG Prerender', () => {
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { `module.exports = {
experimental: { optionalCatchAll: true },
exportTrailingSlash: true, exportTrailingSlash: true,
exportPathMap: function(defaultPathMap) { exportPathMap: function(defaultPathMap) {
if (defaultPathMap['/blog/[post]']) { if (defaultPathMap['/blog/[post]']) {
......
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