|
|
import type { ParsedUrlQuery } from 'querystring' |
|
|
|
|
|
import { getRouteMatcher } from './route-matcher' |
|
|
import { getRouteRegex } from './route-regex' |
|
|
|
|
|
export function interpolateAs( |
|
|
route: string, |
|
|
asPathname: string, |
|
|
query: ParsedUrlQuery |
|
|
) { |
|
|
let interpolatedRoute = '' |
|
|
|
|
|
const dynamicRegex = getRouteRegex(route) |
|
|
const dynamicGroups = dynamicRegex.groups |
|
|
const dynamicMatches = |
|
|
|
|
|
(asPathname !== route ? getRouteMatcher(dynamicRegex)(asPathname) : '') || |
|
|
|
|
|
|
|
|
query |
|
|
|
|
|
interpolatedRoute = route |
|
|
const params = Object.keys(dynamicGroups) |
|
|
|
|
|
if ( |
|
|
!params.every((param) => { |
|
|
let value = dynamicMatches[param] || '' |
|
|
const { repeat, optional } = dynamicGroups[param] |
|
|
|
|
|
|
|
|
|
|
|
let replaced = `[${repeat ? '...' : ''}${param}]` |
|
|
if (optional) { |
|
|
replaced = `${!value ? '/' : ''}[${replaced}]` |
|
|
} |
|
|
if (repeat && !Array.isArray(value)) value = [value] |
|
|
|
|
|
return ( |
|
|
(optional || param in dynamicMatches) && |
|
|
|
|
|
(interpolatedRoute = |
|
|
interpolatedRoute!.replace( |
|
|
replaced, |
|
|
repeat |
|
|
? (value as string[]) |
|
|
.map( |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
(segment) => encodeURIComponent(segment) |
|
|
) |
|
|
.join('/') |
|
|
: encodeURIComponent(value as string) |
|
|
) || '/') |
|
|
) |
|
|
}) |
|
|
) { |
|
|
interpolatedRoute = '' |
|
|
|
|
|
|
|
|
|
|
|
} |
|
|
return { |
|
|
params, |
|
|
result: interpolatedRoute, |
|
|
} |
|
|
} |
|
|
|