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

Update route regex for optional catch-all parameters in named regexes (#14456)

Noticed while working on https://github.com/vercel/next.js/pull/14400 that the optional catch-all handling was missing in `namedRegex`.

This whole file also seemed quite regex heavy so I took a look at the overall logic and changed a few things. It worked by regex escaping the whole route then unescape the dynamic parts. I changed it to only regex escape the static parts, this eliminates unnecessary back and forth escaping. It also makes the dynamic parts handling more readable. The whole logic is less reliant on regexes and just uses simple string manipulation to translate the route into a regex, I didn't measure anything but as an effect this should make it more performant.
parent 70783185
interface Group {
pos: number
repeat: boolean
optional: boolean
}
// this isn't importing the escape-string-regex module // this isn't importing the escape-string-regex module
// to reduce bytes // to reduce bytes
function escapeRegex(str: string) { function escapeRegex(str: string) {
...@@ -5,17 +11,15 @@ function escapeRegex(str: string) { ...@@ -5,17 +11,15 @@ function escapeRegex(str: string) {
} }
function parseParameter(param: string) { function parseParameter(param: string) {
const optional = /^\\\[.*\\\]$/.test(param) const optional = param.startsWith('[') && param.endsWith(']')
if (optional) { if (optional) {
param = param.slice(2, -2) param = param.slice(1, -1)
} }
const repeat = /^(\\\.){3}/.test(param) const repeat = param.startsWith('...')
if (repeat) { if (repeat) {
param = param.slice(6) param = param.slice(3)
} }
// Un-escape key return { key: param, repeat, optional }
const key = param.replace(/\\([|\\{}()[\]^$+*?.-])/g, '$1')
return { key, repeat, optional }
} }
export function getRouteRegex( export function getRouteRegex(
...@@ -24,48 +28,52 @@ export function getRouteRegex( ...@@ -24,48 +28,52 @@ export function getRouteRegex(
re: RegExp re: RegExp
namedRegex?: string namedRegex?: string
routeKeys?: { [named: string]: string } routeKeys?: { [named: string]: string }
groups: { groups: { [groupName: string]: Group }
[groupName: string]: { pos: number; repeat: boolean; optional: boolean }
}
} { } {
// Escape all characters that could be considered RegEx const segments = (normalizedRoute.replace(/\/$/, '') || '/')
const escapedRoute = escapeRegex(normalizedRoute.replace(/\/$/, '') || '/') .slice(1)
.split('/')
const groups: { const groups: { [groupName: string]: Group } = {}
[groupName: string]: { pos: number; repeat: boolean; optional: boolean }
} = {}
let groupIndex = 1 let groupIndex = 1
const parameterizedRoute = segments
const parameterizedRoute = escapedRoute.replace( .map((segment) => {
/\/\\\[([^/]+?)\\\](?=\/|$)/g, if (segment.startsWith('[') && segment.endsWith(']')) {
(_, $1) => { const { key, optional, repeat } = parseParameter(segment.slice(1, -1))
const { key, optional, repeat } = parseParameter($1) groups[key] = { pos: groupIndex++, repeat, optional }
groups[key] = { pos: groupIndex++, repeat, optional } return repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)'
return repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)' } else {
} return `/${escapeRegex(segment)}`
) }
})
let namedParameterizedRoute: string | undefined .join('')
// dead code eliminate for browser since it's only needed // dead code eliminate for browser since it's only needed
// while generating routes-manifest // while generating routes-manifest
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const routeKeys: { [named: string]: string } = {} const routeKeys: { [named: string]: string } = {}
namedParameterizedRoute = escapedRoute.replace( let namedParameterizedRoute = segments
/\/\\\[([^/]+?)\\\](?=\/|$)/g, .map((segment) => {
(_, $1) => { if (segment.startsWith('[') && segment.endsWith(']')) {
const { key, repeat } = parseParameter($1) const { key, optional, repeat } = parseParameter(segment.slice(1, -1))
// 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 repeat
} ? optional
) ? `(?:/(?<${cleanedKey}>.+?))?`
: `/(?<${cleanedKey}>.+?)`
: `/(?<${cleanedKey}>[^/]+?)`
} else {
return `/${escapeRegex(segment)}`
}
})
.join('')
return { return {
re: new RegExp('^' + parameterizedRoute + '(?:/)?$', 'i'), re: new RegExp(`^${parameterizedRoute}(?:/)?$`, 'i'),
groups, groups,
routeKeys, routeKeys,
namedRegex: `^${namedParameterizedRoute}(?:/)?$`, namedRegex: `^${namedParameterizedRoute}(?:/)?$`,
...@@ -73,7 +81,7 @@ export function getRouteRegex( ...@@ -73,7 +81,7 @@ export function getRouteRegex(
} }
return { return {
re: new RegExp('^' + parameterizedRoute + '(?:/)?$', 'i'), re: new RegExp(`^${parameterizedRoute}(?:/)?$`, 'i'),
groups, groups,
} }
} }
...@@ -942,7 +942,7 @@ const runTests = (dev = false, isEmulatedServerless = false) => { ...@@ -942,7 +942,7 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
{ {
namedDataRouteRegex: `^/_next/data/${escapeRegex( namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId buildId
)}/catchall\\-optional/(?<slug>.+?)\\.json$`, )}/catchall\\-optional(?:/(?<slug>.+?))?\\.json$`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex( `^\\/_next\\/data\\/${escapeRegex(
buildId buildId
......
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