Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

path.ts

858 lines26.1 KB

1import { last } from './utils'
2import type { LRUCache } from './lru-cache'
3import type { MatchLocation } from './RouterProvider'
4import type { AnyPathParams } from './route'
5​
6export const SEGMENT_TYPE_PATHNAME = 0
7export const SEGMENT_TYPE_PARAM = 1
8export const SEGMENT_TYPE_WILDCARD = 2
9export const SEGMENT_TYPE_OPTIONAL_PARAM = 3
10​
11export interface Segment {
12 readonly type:
13 | typeof SEGMENT_TYPE_PATHNAME
14 | typeof SEGMENT_TYPE_PARAM
15 | typeof SEGMENT_TYPE_WILDCARD
16 | typeof SEGMENT_TYPE_OPTIONAL_PARAM
17 readonly value: string
18 readonly prefixSegment?: string
19 readonly suffixSegment?: string
20 // Indicates if there is a static segment after this required/optional param
21 readonly hasStaticAfter?: boolean
23​
24/** Join path segments, cleaning duplicate slashes between parts. */
25/** Join path segments, cleaning duplicate slashes between parts. */
26export function joinPaths(paths: Array<string | undefined>) {
27 return cleanPath(
28 paths
29 .filter((val) => {
30 return val !== undefined
31 })
32 .join('/'),
33 )
35​
36/** Remove repeated slashes from a path string. */
37/** Remove repeated slashes from a path string. */
38export function cleanPath(path: string) {
39 // remove double slashes
40 return path.replace(/\/{2,}/g, '/')
42​
43/** Trim leading slashes (except preserving root '/'). */
44/** Trim leading slashes (except preserving root '/'). */
45export function trimPathLeft(path: string) {
46 return path === '/' ? path : path.replace(/^\/{1,}/, '')
48​
49/** Trim trailing slashes (except preserving root '/'). */
50/** Trim trailing slashes (except preserving root '/'). */
51export function trimPathRight(path: string) {
52 return path === '/' ? path : path.replace(/\/{1,}$/, '')
54​
55/** Trim both leading and trailing slashes. */
56/** Trim both leading and trailing slashes. */
57export function trimPath(path: string) {
58 return trimPathRight(trimPathLeft(path))
60​
61/** Remove a trailing slash from value when appropriate for comparisons. */
62export function removeTrailingSlash(value: string, basepath: string): string {
63 if (value?.endsWith('/') && value !== '/' && value !== `${basepath}/`) {
64 return value.slice(0, -1)
65 }
66 return value
68​
69// intended to only compare path name
70// see the usage in the isActive under useLinkProps
71// /sample/path1 = /sample/path1/
72// /sample/path1/some <> /sample/path1
73/**
74 * Compare two pathnames for exact equality after normalizing trailing slashes
75 * relative to the provided `basepath`.
76 */
77/**
78 * Compare two pathnames for exact equality after normalizing trailing slashes
79 * relative to the provided `basepath`.
80 */
81export function exactPathTest(
82 pathName1: string,
83 pathName2: string,
84 basepath: string,
85): boolean {
86 return (
87 removeTrailingSlash(pathName1, basepath) ===
88 removeTrailingSlash(pathName2, basepath)
89 )
91​
92// When resolving relative paths, we treat all paths as if they are trailing slash
93// documents. All trailing slashes are removed after the path is resolved.
94// Here are a few examples:
95//
96// /a/b/c + ./d = /a/b/c/d
97// /a/b/c + ../d = /a/b/d
98// /a/b/c + ./d/ = /a/b/c/d
99// /a/b/c + ../d/ = /a/b/d
100// /a/b/c + ./ = /a/b/c
101//
102// Absolute paths that start with `/` short circuit the resolution process to the root
103// path.
104//
105// Here are some examples:
106//
107// /a/b/c + /d = /d
108// /a/b/c + /d/ = /d
109// /a/b/c + / = /
110//
111// Non-.-prefixed paths are still treated as relative paths, resolved like `./`
112//
113// Here are some examples:
114//
115// /a/b/c + d = /a/b/c/d
116// /a/b/c + d/ = /a/b/c/d
117// /a/b/c + d/e = /a/b/c/d/e
118interface ResolvePathOptions {
119 base: string
120 to: string
121 trailingSlash?: 'always' | 'never' | 'preserve'
122 parseCache?: ParsePathnameCache
124​
125function segmentToString(segment: Segment): string {
126 const { type, value } = segment
127 if (type === SEGMENT_TYPE_PATHNAME) {
128 return value
129 }
130​
131 const { prefixSegment, suffixSegment } = segment
132​
133 if (type === SEGMENT_TYPE_PARAM) {
134 const param = value.substring(1)
135 if (prefixSegment && suffixSegment) {
136 return `${prefixSegment}{$${param}}${suffixSegment}`
137 } else if (prefixSegment) {
138 return `${prefixSegment}{$${param}}`
139 } else if (suffixSegment) {
140 return `{$${param}}${suffixSegment}`
141 }
142 }
143​
144 if (type === SEGMENT_TYPE_OPTIONAL_PARAM) {
145 const param = value.substring(1)
146 if (prefixSegment && suffixSegment) {
147 return `${prefixSegment}{-$${param}}${suffixSegment}`
148 } else if (prefixSegment) {
149 return `${prefixSegment}{-$${param}}`
150 } else if (suffixSegment) {
151 return `{-$${param}}${suffixSegment}`
152 }
153 return `{-$${param}}`
154 }
155​
156 if (type === SEGMENT_TYPE_WILDCARD) {
157 if (prefixSegment && suffixSegment) {
158 return `${prefixSegment}{$}${suffixSegment}`
159 } else if (prefixSegment) {
160 return `${prefixSegment}{$}`
161 } else if (suffixSegment) {
162 return `{$}${suffixSegment}`
163 }
164 }
165​
166 // This case should never happen, should we throw instead?
167 return value
169​
170/**
171 * Resolve a destination path against a base, honoring trailing-slash policy
172 * and supporting relative segments (`.`/`..`) and absolute `to` values.
173 */
174export function resolvePath({
175 base,
176 to,
177 trailingSlash = 'never',
178 parseCache,
179}: ResolvePathOptions) {
180 let baseSegments = parsePathname(base, parseCache).slice()
181 const toSegments = parsePathname(to, parseCache)
182​
183 if (baseSegments.length > 1 && last(baseSegments)?.value === '/') {
184 baseSegments.pop()
185 }
186​
187 for (let index = 0, length = toSegments.length; index < length; index++) {
188 const toSegment = toSegments[index]!
189 const value = toSegment.value
190 if (value === '/') {
191 if (!index) {
192 // Leading slash
193 baseSegments = [toSegment]
194 } else if (index === length - 1) {
195 // Trailing Slash
196 baseSegments.push(toSegment)
197 } else {
198 // ignore inter-slashes
199 }
200 } else if (value === '..') {
201 baseSegments.pop()
202 } else if (value === '.') {
203 // ignore
204 } else {
205 baseSegments.push(toSegment)
206 }
207 }
208​
209 if (baseSegments.length > 1) {
210 if (last(baseSegments)!.value === '/') {
211 if (trailingSlash === 'never') {
212 baseSegments.pop()
213 }
214 } else if (trailingSlash === 'always') {
215 baseSegments.push({ type: SEGMENT_TYPE_PATHNAME, value: '/' })
216 }
217 }
218​
219 const segmentValues = baseSegments.map(segmentToString)
220 // const joined = joinPaths([basepath, ...segmentValues])
221 const joined = joinPaths(segmentValues)
222 return joined
224​
225export type ParsePathnameCache = LRUCache<string, ReadonlyArray<Segment>>
226​
227/**
228 * Parse a pathname into an array of typed segments used by the router's
229 * matcher. Results are optionally cached via an LRU cache.
230 */
231/**
232 * Parse a pathname into an array of typed segments used by the router's
233 * matcher. Results are optionally cached via an LRU cache.
234 */
235export const parsePathname = (
236 pathname?: string,
237 cache?: ParsePathnameCache,
238): ReadonlyArray<Segment> => {
239 if (!pathname) return []
240 const cached = cache?.get(pathname)
241 if (cached) return cached
242 const parsed = baseParsePathname(pathname)
243 cache?.set(pathname, parsed)
244 return parsed
246​
247const PARAM_RE = /^\$.{1,}$/ // $paramName
248const PARAM_W_CURLY_BRACES_RE = /^(.*?)\{(\$[a-zA-Z_$][a-zA-Z0-9_$]*)\}(.*)$/ // prefix{$paramName}suffix
249const OPTIONAL_PARAM_W_CURLY_BRACES_RE =
250 /^(.*?)\{-(\$[a-zA-Z_$][a-zA-Z0-9_$]*)\}(.*)$/ // prefix{-$paramName}suffix
251​
252const WILDCARD_RE = /^\$$/ // $
253const WILDCARD_W_CURLY_BRACES_RE = /^(.*?)\{\$\}(.*)$/ // prefix{$}suffix
254​
255/**
256 * Required: `/foo/$bar` βœ…
257 * Prefix and Suffix: `/foo/prefix${bar}suffix` βœ…
258 * Wildcard: `/foo/$` βœ…
259 * Wildcard with Prefix and Suffix: `/foo/prefix{$}suffix` βœ…
260 *
261 * Optional param: `/foo/{-$bar}`
262 * Optional param with Prefix and Suffix: `/foo/prefix{-$bar}suffix`
263​
264 * Future:
265 * Optional named segment: `/foo/{bar}`
266 * Optional named segment with Prefix and Suffix: `/foo/prefix{-bar}suffix`
267 * Escape special characters:
268 * - `/foo/[$]` - Static route
269 * - `/foo/[$]{$foo} - Dynamic route with a static prefix of `$`
270 * - `/foo/{$foo}[$]` - Dynamic route with a static suffix of `$`
271 */
272function baseParsePathname(pathname: string): ReadonlyArray<Segment> {
273 pathname = cleanPath(pathname)
274​
275 const segments: Array<Segment> = []
276​
277 if (pathname.slice(0, 1) === '/') {
278 pathname = pathname.substring(1)
279 segments.push({
280 type: SEGMENT_TYPE_PATHNAME,
281 value: '/',
282 })
283 }
284​
285 if (!pathname) {
286 return segments
287 }
288​
289 // Remove empty segments and '.' segments
290 const split = pathname.split('/').filter(Boolean)
291​
292 segments.push(
293 ...split.map((part): Segment => {
294 // Check for wildcard with curly braces: prefix{$}suffix
295 const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE)
296 if (wildcardBracesMatch) {
297 const prefix = wildcardBracesMatch[1]
298 const suffix = wildcardBracesMatch[2]
299 return {
300 type: SEGMENT_TYPE_WILDCARD,
301 value: '$',
302 prefixSegment: prefix || undefined,
303 suffixSegment: suffix || undefined,
304 }
305 }
306​
307 // Check for optional parameter format: prefix{-$paramName}suffix
308 const optionalParamBracesMatch = part.match(
309 OPTIONAL_PARAM_W_CURLY_BRACES_RE,
310 )
311 if (optionalParamBracesMatch) {
312 const prefix = optionalParamBracesMatch[1]
313 const paramName = optionalParamBracesMatch[2]!
314 const suffix = optionalParamBracesMatch[3]
315 return {
316 type: SEGMENT_TYPE_OPTIONAL_PARAM,
317 value: paramName, // Now just $paramName (no prefix)
318 prefixSegment: prefix || undefined,
319 suffixSegment: suffix || undefined,
320 }
321 }
322​
323 // Check for the new parameter format: prefix{$paramName}suffix
324 const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE)
325 if (paramBracesMatch) {
326 const prefix = paramBracesMatch[1]
327 const paramName = paramBracesMatch[2]
328 const suffix = paramBracesMatch[3]
329 return {
330 type: SEGMENT_TYPE_PARAM,
331 value: '' + paramName,
332 prefixSegment: prefix || undefined,
333 suffixSegment: suffix || undefined,
334 }
335 }
336​
337 // Check for bare parameter format: $paramName (without curly braces)
338 if (PARAM_RE.test(part)) {
339 const paramName = part.substring(1)
340 return {
341 type: SEGMENT_TYPE_PARAM,
342 value: '$' + paramName,
343 prefixSegment: undefined,
344 suffixSegment: undefined,
345 }
346 }
347​
348 // Check for bare wildcard: $ (without curly braces)
349 if (WILDCARD_RE.test(part)) {
350 return {
351 type: SEGMENT_TYPE_WILDCARD,
352 value: '$',
353 prefixSegment: undefined,
354 suffixSegment: undefined,
355 }
356 }
357​
358 // Handle regular pathname segment
359 return {
360 type: SEGMENT_TYPE_PATHNAME,
361 value: part.includes('%25')
362 ? part
363 .split('%25')
364 .map((segment) => decodeURI(segment))
365 .join('%25')
366 : decodeURI(part),
367 }
368 }),
369 )
370​
371 if (pathname.slice(-1) === '/') {
372 pathname = pathname.substring(1)
373 segments.push({
374 type: SEGMENT_TYPE_PATHNAME,
375 value: '/',
376 })
377 }
378​
379 return segments
381​
382interface InterpolatePathOptions {
383 path?: string
384 params: Record<string, unknown>
385 leaveWildcards?: boolean
386 leaveParams?: boolean
387 // Map of encoded chars to decoded chars (e.g. '%40' -> '@') that should remain decoded in path params
388 decodeCharMap?: Map<string, string>
389 parseCache?: ParsePathnameCache
391​
392type InterPolatePathResult = {
393 interpolatedPath: string
394 usedParams: Record<string, unknown>
395 isMissingParams: boolean // true if any params were not available when being looked up in the params object
397/**
398 * Interpolate params and wildcards into a route path template.
399 *
400 * - Encodes params safely (configurable allowed characters)
401 * - Supports `{-$optional}` segments, `{prefix{$id}suffix}` and `{$}` wildcards
402 * - Optionally leaves placeholders or wildcards in place
403 */
404/**
405 * Interpolate params and wildcards into a route path template.
406 * Encodes safely and supports optional params and custom decode char maps.
407 */
408export function interpolatePath({
409 path,
410 params,
411 leaveWildcards,
412 leaveParams,
413 decodeCharMap,
414 parseCache,
415}: InterpolatePathOptions): InterPolatePathResult {
416 const interpolatedPathSegments = parsePathname(path, parseCache)
417​
418 function encodeParam(key: string): any {
419 const value = params[key]
420 const isValueString = typeof value === 'string'
421​
422 if (key === '*' || key === '_splat') {
423 // the splat/catch-all routes shouldn't have the '/' encoded out
424 return isValueString ? encodeURI(value) : value
425 } else {
426 return isValueString ? encodePathParam(value, decodeCharMap) : value
427 }
428 }
429​
430 // Tracking if any params are missing in the `params` object
431 // when interpolating the path
432 let isMissingParams = false
433​
434 const usedParams: Record<string, unknown> = {}
435 const interpolatedPath = joinPaths(
436 interpolatedPathSegments.map((segment) => {
437 if (segment.type === SEGMENT_TYPE_PATHNAME) {
438 return segment.value
439 }
440​
441 if (segment.type === SEGMENT_TYPE_WILDCARD) {
442 usedParams._splat = params._splat
443​
444 // TODO: Deprecate *
445 usedParams['*'] = params._splat
446​
447 const segmentPrefix = segment.prefixSegment || ''
448 const segmentSuffix = segment.suffixSegment || ''
449​
450 // Check if _splat parameter is missing. _splat could be missing if undefined or an empty string or some other falsy value.
451 if (!params._splat) {
452 isMissingParams = true
453 // For missing splat parameters, just return the prefix and suffix without the wildcard
454 if (leaveWildcards) {
455 return `${segmentPrefix}${segment.value}${segmentSuffix}`
456 }
457 // If there is a prefix or suffix, return them joined, otherwise omit the segment
458 if (segmentPrefix || segmentSuffix) {
459 return `${segmentPrefix}${segmentSuffix}`
460 }
461 return undefined
462 }
463​
464 const value = encodeParam('_splat')
465 if (leaveWildcards) {
466 return `${segmentPrefix}${segment.value}${value ?? ''}${segmentSuffix}`
467 }
468 return `${segmentPrefix}${value}${segmentSuffix}`
469 }
470​
471 if (segment.type === SEGMENT_TYPE_PARAM) {
472 const key = segment.value.substring(1)
473 if (!isMissingParams && !(key in params)) {
474 isMissingParams = true
475 }
476 usedParams[key] = params[key]
477​
478 const segmentPrefix = segment.prefixSegment || ''
479 const segmentSuffix = segment.suffixSegment || ''
480 if (leaveParams) {
481 const value = encodeParam(segment.value)
482 return `${segmentPrefix}${segment.value}${value ?? ''}${segmentSuffix}`
483 }
484 return `${segmentPrefix}${encodeParam(key) ?? 'undefined'}${segmentSuffix}`
485 }
486​
487 if (segment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
488 const key = segment.value.substring(1)
489​
490 const segmentPrefix = segment.prefixSegment || ''
491 const segmentSuffix = segment.suffixSegment || ''
492​
493 // Check if optional parameter is missing or undefined
494 if (!(key in params) || params[key] == null) {
495 if (leaveWildcards) {
496 return `${segmentPrefix}${key}${segmentSuffix}`
497 }
498 // For optional params with prefix/suffix, keep the prefix/suffix but omit the param
499 if (segmentPrefix || segmentSuffix) {
500 return `${segmentPrefix}${segmentSuffix}`
501 }
502 // If no prefix/suffix, omit the entire segment
503 return undefined
504 }
505​
506 usedParams[key] = params[key]
507​
508 if (leaveParams) {
509 const value = encodeParam(segment.value)
510 return `${segmentPrefix}${segment.value}${value ?? ''}${segmentSuffix}`
511 }
512 if (leaveWildcards) {
513 return `${segmentPrefix}${key}${encodeParam(key) ?? ''}${segmentSuffix}`
514 }
515 return `${segmentPrefix}${encodeParam(key) ?? ''}${segmentSuffix}`
516 }
517​
518 return segment.value
519 }),
520 )
521 return { usedParams, interpolatedPath, isMissingParams }
523​
524function encodePathParam(value: string, decodeCharMap?: Map<string, string>) {
525 let encoded = encodeURIComponent(value)
526 if (decodeCharMap) {
527 for (const [encodedChar, char] of decodeCharMap) {
528 encoded = encoded.replaceAll(encodedChar, char)
529 }
530 }
531 return encoded
533​
534/**
535 * Match a pathname against a route destination and return extracted params
536 * or `undefined`. Uses the same parsing as the router for consistency.
537 */
538/**
539 * Match a pathname against a route destination and return extracted params
540 * or `undefined`. Uses the same parsing as the router for consistency.
541 */
542export function matchPathname(
543 currentPathname: string,
544 matchLocation: Pick<MatchLocation, 'to' | 'fuzzy' | 'caseSensitive'>,
545 parseCache?: ParsePathnameCache,
546): AnyPathParams | undefined {
547 const pathParams = matchByPath(currentPathname, matchLocation, parseCache)
548 // const searchMatched = matchBySearch(location.search, matchLocation)
549​
550 if (matchLocation.to && !pathParams) {
551 return
552 }
553​
554 return pathParams ?? {}
556​
557/** Low-level matcher that compares two path strings and extracts params. */
558/** Low-level matcher that compares two path strings and extracts params. */
559export function matchByPath(
560 from: string,
561 {
562 to,
563 fuzzy,
564 caseSensitive,
565 }: Pick<MatchLocation, 'to' | 'caseSensitive' | 'fuzzy'>,
566 parseCache?: ParsePathnameCache,
567): Record<string, string> | undefined {
568 const stringTo = to as string
569​
570 // Parse the from and to
571 const baseSegments = parsePathname(
572 from.startsWith('/') ? from : `/${from}`,
573 parseCache,
574 )
575 const routeSegments = parsePathname(
576 stringTo.startsWith('/') ? stringTo : `/${stringTo}`,
577 parseCache,
578 )
579​
580 const params: Record<string, string> = {}
581​
582 const result = isMatch(
583 baseSegments,
584 routeSegments,
585 params,
586 fuzzy,
587 caseSensitive,
588 )
589​
590 return result ? params : undefined
592​
593function isMatch(
594 baseSegments: ReadonlyArray<Segment>,
595 routeSegments: ReadonlyArray<Segment>,
596 params: Record<string, string>,
597 fuzzy?: boolean,
598 caseSensitive?: boolean,
599): boolean {
600 let baseIndex = 0
601 let routeIndex = 0
602​
603 while (baseIndex < baseSegments.length || routeIndex < routeSegments.length) {
604 const baseSegment = baseSegments[baseIndex]
605 const routeSegment = routeSegments[routeIndex]
606​
607 if (routeSegment) {
608 if (routeSegment.type === SEGMENT_TYPE_WILDCARD) {
609 // Capture all remaining segments for a wildcard
610 const remainingBaseSegments = baseSegments.slice(baseIndex)
611​
612 let _splat: string
613​
614 // If this is a wildcard with prefix/suffix, we need to handle the first segment specially
615 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
616 if (!baseSegment) return false
617​
618 const prefix = routeSegment.prefixSegment || ''
619 const suffix = routeSegment.suffixSegment || ''
620​
621 // Check if the base segment starts with prefix and ends with suffix
622 const baseValue = baseSegment.value
623 if ('prefixSegment' in routeSegment) {
624 if (!baseValue.startsWith(prefix)) {
625 return false
626 }
627 }
628 if ('suffixSegment' in routeSegment) {
629 if (
630 !baseSegments[baseSegments.length - 1]?.value.endsWith(suffix)
631 ) {
632 return false
633 }
634 }
635​
636 let rejoinedSplat = decodeURI(
637 joinPaths(remainingBaseSegments.map((d) => d.value)),
638 )
639​
640 // Remove the prefix and suffix from the rejoined splat
641 if (prefix && rejoinedSplat.startsWith(prefix)) {
642 rejoinedSplat = rejoinedSplat.slice(prefix.length)
643 }
644​
645 if (suffix && rejoinedSplat.endsWith(suffix)) {
646 rejoinedSplat = rejoinedSplat.slice(
647 0,
648 rejoinedSplat.length - suffix.length,
649 )
650 }
651​
652 _splat = rejoinedSplat
653 } else {
654 // If no prefix/suffix, just rejoin the remaining segments
655 _splat = decodeURI(
656 joinPaths(remainingBaseSegments.map((d) => d.value)),
657 )
658 }
659​
660 // TODO: Deprecate *
661 params['*'] = _splat
662 params['_splat'] = _splat
663 return true
664 }
665​
666 if (routeSegment.type === SEGMENT_TYPE_PATHNAME) {
667 if (routeSegment.value === '/' && !baseSegment?.value) {
668 routeIndex++
669 continue
670 }
671​
672 if (baseSegment) {
673 if (caseSensitive) {
674 if (routeSegment.value !== baseSegment.value) {
675 return false
676 }
677 } else if (
678 routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()
679 ) {
680 return false
681 }
682 baseIndex++
683 routeIndex++
684 continue
685 } else {
686 return false
687 }
688 }
689​
690 if (routeSegment.type === SEGMENT_TYPE_PARAM) {
691 if (!baseSegment) {
692 return false
693 }
694​
695 if (baseSegment.value === '/') {
696 return false
697 }
698​
699 let _paramValue = ''
700 let matched = false
701​
702 // If this param has prefix/suffix, we need to extract the actual parameter value
703 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
704 const prefix = routeSegment.prefixSegment || ''
705 const suffix = routeSegment.suffixSegment || ''
706​
707 // Check if the base segment starts with prefix and ends with suffix
708 const baseValue = baseSegment.value
709 if (prefix && !baseValue.startsWith(prefix)) {
710 return false
711 }
712 if (suffix && !baseValue.endsWith(suffix)) {
713 return false
714 }
715​
716 let paramValue = baseValue
717 if (prefix && paramValue.startsWith(prefix)) {
718 paramValue = paramValue.slice(prefix.length)
719 }
720 if (suffix && paramValue.endsWith(suffix)) {
721 paramValue = paramValue.slice(0, paramValue.length - suffix.length)
722 }
723​
724 _paramValue = decodeURIComponent(paramValue)
725 matched = true
726 } else {
727 // If no prefix/suffix, just decode the base segment value
728 _paramValue = decodeURIComponent(baseSegment.value)
729 matched = true
730 }
731​
732 if (matched) {
733 params[routeSegment.value.substring(1)] = _paramValue
734 baseIndex++
735 }
736​
737 routeIndex++
738 continue
739 }
740​
741 if (routeSegment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
742 // Optional parameters can be missing - don't fail the match
743 if (!baseSegment) {
744 // No base segment for optional param - skip this route segment
745 routeIndex++
746 continue
747 }
748​
749 if (baseSegment.value === '/') {
750 // Skip slash segments for optional params
751 routeIndex++
752 continue
753 }
754​
755 let _paramValue = ''
756 let matched = false
757​
758 // If this optional param has prefix/suffix, we need to extract the actual parameter value
759 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
760 const prefix = routeSegment.prefixSegment || ''
761 const suffix = routeSegment.suffixSegment || ''
762​
763 // Check if the base segment starts with prefix and ends with suffix
764 const baseValue = baseSegment.value
765 if (
766 (!prefix || baseValue.startsWith(prefix)) &&
767 (!suffix || baseValue.endsWith(suffix))
768 ) {
769 let paramValue = baseValue
770 if (prefix && paramValue.startsWith(prefix)) {
771 paramValue = paramValue.slice(prefix.length)
772 }
773 if (suffix && paramValue.endsWith(suffix)) {
774 paramValue = paramValue.slice(
775 0,
776 paramValue.length - suffix.length,
777 )
778 }
779​
780 _paramValue = decodeURIComponent(paramValue)
781 matched = true
782 }
783 } else {
784 // For optional params without prefix/suffix, we need to check if the current
785 // base segment should match this optional param or a later route segment
786​
787 // Look ahead to see if there's a later route segment that matches the current base segment
788 let shouldMatchOptional = true
789 for (
790 let lookAhead = routeIndex + 1;
791 lookAhead < routeSegments.length;
792 lookAhead++
793 ) {
794 const futureRouteSegment = routeSegments[lookAhead]
795 if (
796 futureRouteSegment?.type === SEGMENT_TYPE_PATHNAME &&
797 futureRouteSegment.value === baseSegment.value
798 ) {
799 // The current base segment matches a future pathname segment,
800 // so we should skip this optional parameter
801 shouldMatchOptional = false
802 break
803 }
804​
805 // If we encounter a required param or wildcard, stop looking ahead
806 if (
807 futureRouteSegment?.type === SEGMENT_TYPE_PARAM ||
808 futureRouteSegment?.type === SEGMENT_TYPE_WILDCARD
809 ) {
810 if (baseSegments.length < routeSegments.length) {
811 shouldMatchOptional = false
812 }
813 break
814 }
815 }
816​
817 if (shouldMatchOptional) {
818 // If no prefix/suffix, just decode the base segment value
819 _paramValue = decodeURIComponent(baseSegment.value)
820 matched = true
821 }
822 }
823​
824 if (matched) {
825 params[routeSegment.value.substring(1)] = _paramValue
826 baseIndex++
827 }
828​
829 routeIndex++
830 continue
831 }
832 }
833​
834 // If we have base segments left but no route segments, it's a fuzzy match
835 if (baseIndex < baseSegments.length && routeIndex >= routeSegments.length) {
836 params['**'] = joinPaths(
837 baseSegments.slice(baseIndex).map((d) => d.value),
838 )
839 return !!fuzzy && routeSegments[routeSegments.length - 1]?.value !== '/'
840 }
841​
842 // If we have route segments left but no base segments, check if remaining are optional
843 if (routeIndex < routeSegments.length && baseIndex >= baseSegments.length) {
844 // Check if all remaining route segments are optional
845 for (let i = routeIndex; i < routeSegments.length; i++) {
846 if (routeSegments[i]?.type !== SEGMENT_TYPE_OPTIONAL_PARAM) {
847 return false
848 }
849 }
850 // All remaining are optional, so we can finish
851 break
852 }
853​
854 break
855 }
856​
857 return true