Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 36 additions & 16 deletions packages/router-core/src/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,33 @@ export function resolvePath({
return result
}

/**
* Create a pre-compiled decode config from allowed characters.
* This should be called once at router initialization.
*/
export function compileDecodeCharMap(
pathParamsAllowedCharacters: ReadonlyArray<string>,
) {
const charMap = new Map(
pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]),
)
// Escape special regex characters and join with |
const pattern = Array.from(charMap.keys())
.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
const regex = new RegExp(pattern, 'g')
return (encoded: string) =>
encoded.replace(regex, (match) => charMap.get(match) ?? match)
}

interface InterpolatePathOptions {
path?: string
params: Record<string, unknown>
// Map of encoded chars to decoded chars (e.g. '%40' -> '@') that should remain decoded in path params
decodeCharMap?: Map<string, string>
/**
* A function that decodes a path parameter value.
* Obtained from `compileDecodeCharMap(pathParamsAllowedCharacters)`.
*/
decoder?: (encoded: string) => string
}

type InterPolatePathResult = {
Expand All @@ -213,7 +235,7 @@ type InterPolatePathResult = {
function encodeParam(
key: string,
params: InterpolatePathOptions['params'],
decodeCharMap: InterpolatePathOptions['decodeCharMap'],
decoder: InterpolatePathOptions['decoder'],
): any {
const value = params[key]
if (typeof value !== 'string') return value
Expand All @@ -222,7 +244,7 @@ function encodeParam(
// the splat/catch-all routes shouldn't have the '/' encoded out
return encodeURI(value)
} else {
return encodePathParam(value, decodeCharMap)
return encodePathParam(value, decoder)
}
}

Expand All @@ -235,7 +257,7 @@ function encodeParam(
export function interpolatePath({
path,
params,
decodeCharMap,
decoder,
}: InterpolatePathOptions): InterPolatePathResult {
// Tracking if any params are missing in the `params` object
// when interpolating the path
Expand Down Expand Up @@ -286,7 +308,7 @@ export function interpolatePath({
continue
}

const value = encodeParam('_splat', params, decodeCharMap)
const value = encodeParam('_splat', params, decoder)
joined += '/' + prefix + value + suffix
continue
}
Expand All @@ -300,7 +322,7 @@ export function interpolatePath({

const prefix = path.substring(start, segment[1])
const suffix = path.substring(segment[4], end)
const value = encodeParam(key, params, decodeCharMap) ?? 'undefined'
const value = encodeParam(key, params, decoder) ?? 'undefined'
joined += '/' + prefix + value + suffix
continue
}
Expand All @@ -316,7 +338,7 @@ export function interpolatePath({

const prefix = path.substring(start, segment[1])
const suffix = path.substring(segment[4], end)
const value = encodeParam(key, params, decodeCharMap) ?? ''
const value = encodeParam(key, params, decoder) ?? ''
joined += '/' + prefix + value + suffix
continue
}
Expand All @@ -329,12 +351,10 @@ export function interpolatePath({
return { usedParams, interpolatedPath, isMissingParams }
}

function encodePathParam(value: string, decodeCharMap?: Map<string, string>) {
let encoded = encodeURIComponent(value)
if (decodeCharMap) {
for (const [encodedChar, char] of decodeCharMap) {
encoded = encoded.replaceAll(encodedChar, char)
}
}
return encoded
function encodePathParam(
value: string,
decoder?: InterpolatePathOptions['decoder'],
) {
const encoded = encodeURIComponent(value)
return decoder?.(encoded) ?? encoded
}
19 changes: 8 additions & 11 deletions packages/router-core/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from './new-process-route-tree'
import {
cleanPath,
compileDecodeCharMap,
interpolatePath,
resolvePath,
trimPath,
Expand Down Expand Up @@ -923,7 +924,7 @@ export class RouterCore<
routesByPath!: RoutesByPath<TRouteTree>
processedTree!: ProcessedTree<TRouteTree, any, any>
isServer!: boolean
pathParamsDecodeCharMap?: Map<string, string>
pathParamsDecoder?: (encoded: string) => string

/**
* @deprecated Use the `createRouter` function instead
Expand Down Expand Up @@ -992,14 +993,10 @@ export class RouterCore<

this.isServer = this.options.isServer ?? typeof document === 'undefined'

this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters
? new Map(
this.options.pathParamsAllowedCharacters.map((char) => [
encodeURIComponent(char),
char,
]),
)
: undefined
if (this.options.pathParamsAllowedCharacters)
this.pathParamsDecoder = compileDecodeCharMap(
this.options.pathParamsAllowedCharacters,
)

if (
!this.history ||
Expand Down Expand Up @@ -1365,7 +1362,7 @@ export class RouterCore<
const { interpolatedPath, usedParams } = interpolatePath({
path: route.fullPath,
params: routeParams,
decodeCharMap: this.pathParamsDecodeCharMap,
decoder: this.pathParamsDecoder,
})

// Waste not, want not. If we already have a match for this route,
Expand Down Expand Up @@ -1721,7 +1718,7 @@ export class RouterCore<
interpolatePath({
path: nextTo,
params: nextParams,
decodeCharMap: this.pathParamsDecodeCharMap,
decoder: this.pathParamsDecoder,
}).interpolatedPath,
)

Expand Down
9 changes: 4 additions & 5 deletions packages/router-core/tests/path.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
compileDecodeCharMap,
exactPathTest,
interpolatePath,
removeTrailingSlash,
Expand Down Expand Up @@ -309,9 +310,7 @@ describe('interpolatePath', () => {
path: '/users/$id',
params: { id: '?#@john+smith' },
result: '/users/%3F%23@john+smith',
decodeCharMap: new Map(
['@', '+'].map((char) => [encodeURIComponent(char), char]),
),
decoder: compileDecodeCharMap(['@', '+']),
},
{
name: 'should interpolate the path with the splat param at the end',
Expand Down Expand Up @@ -348,12 +347,12 @@ describe('interpolatePath', () => {
params: { _splat: 'sean/cassiere' },
result: '/users/sean/cassiere',
},
])('$name', ({ path, params, decodeCharMap, result }) => {
])('$name', ({ path, params, decoder, result }) => {
expect(
interpolatePath({
path,
params,
decodeCharMap,
decoder,
}).interpolatedPath,
).toBe(result)
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ function RouteComp({
const interpolated = interpolatePath({
path: route.fullPath,
params: allParams,
decodeCharMap: router().pathParamsDecodeCharMap,
decoder: router().pathParamsDecoder,
})

// only if `interpolated` is not missing params, return the path since this
Expand Down
Loading