| import { NEXT_URL } from '../client/components/app-router-headers' |
| import { |
| extractInterceptionRouteInformation, |
| isInterceptionRouteAppPath, |
| } from '../shared/lib/router/utils/interception-routes' |
| import type { Rewrite } from './load-custom-routes' |
| import { safePathToRegexp } from '../shared/lib/router/utils/route-match-utils' |
| import type { DeepReadonly } from '../shared/lib/deep-readonly' |
|
|
| |
| function toPathToRegexpPath(path: string): string { |
| return path.replace(/\[\[?([^\]]+)\]\]?/g, (_, capture) => { |
| |
| const paramName = capture.replace(/\W+/g, '_') |
|
|
| |
| if (capture.startsWith('...')) { |
| return `:${capture.slice(3)}*` |
| } |
| return ':' + paramName |
| }) |
| } |
|
|
| export function generateInterceptionRoutesRewrites( |
| appPaths: string[], |
| basePath = '' |
| ): Rewrite[] { |
| const rewrites: Rewrite[] = [] |
|
|
| for (const appPath of appPaths) { |
| if (isInterceptionRouteAppPath(appPath)) { |
| const { interceptingRoute, interceptedRoute } = |
| extractInterceptionRouteInformation(appPath) |
|
|
| const normalizedInterceptingRoute = `${ |
| interceptingRoute !== '/' ? toPathToRegexpPath(interceptingRoute) : '' |
| }/(.*)?` |
|
|
| const normalizedInterceptedRoute = toPathToRegexpPath(interceptedRoute) |
| const normalizedAppPath = toPathToRegexpPath(appPath) |
|
|
| |
| |
| |
| let interceptingRouteRegex = safePathToRegexp(normalizedInterceptingRoute) |
| .toString() |
| .slice(2, -3) |
|
|
| rewrites.push({ |
| source: `${basePath}${normalizedInterceptedRoute}`, |
| destination: `${basePath}${normalizedAppPath}`, |
| has: [ |
| { |
| type: 'header', |
| key: NEXT_URL, |
| value: interceptingRouteRegex, |
| }, |
| ], |
| }) |
| } |
| } |
|
|
| return rewrites |
| } |
|
|
| export function isInterceptionRouteRewrite(route: DeepReadonly<Rewrite>) { |
| |
| return route.has?.[0]?.key === NEXT_URL |
| } |
|
|