Open History to see the last commit
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
22}
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 )
34}
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, '/')
41}
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,}/, '')
47}
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,}$/, '')
53}
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))
59}
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
67}
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 )
90}
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
123}
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
168}
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
223}
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
245}
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,
362 }
363 }),
364 )
365β
366 if (pathname.slice(-1) === '/') {
367 pathname = pathname.substring(1)
368 segments.push({
369 type: SEGMENT_TYPE_PATHNAME,
370 value: '/',
371 })
372 }
373β
374 return segments
375}
376β
377interface InterpolatePathOptions {
378 path?: string
379 params: Record<string, unknown>
380 leaveWildcards?: boolean
381 leaveParams?: boolean
382 // Map of encoded chars to decoded chars (e.g. '%40' -> '@') that should remain decoded in path params
383 decodeCharMap?: Map<string, string>
384 parseCache?: ParsePathnameCache
385}
386β
387type InterPolatePathResult = {
388 interpolatedPath: string
389 usedParams: Record<string, unknown>
390 isMissingParams: boolean // true if any params were not available when being looked up in the params object
391}
392/**
393 * Interpolate params and wildcards into a route path template.
394 *
395 * - Encodes params safely (configurable allowed characters)
396 * - Supports `{-$optional}` segments, `{prefix{$id}suffix}` and `{$}` wildcards
397 * - Optionally leaves placeholders or wildcards in place
398 */
399/**
400 * Interpolate params and wildcards into a route path template.
401 * Encodes safely and supports optional params and custom decode char maps.
402 */
403export function interpolatePath({
404 path,
405 params,
406 leaveWildcards,
407 leaveParams,
408 decodeCharMap,
409 parseCache,
410}: InterpolatePathOptions): InterPolatePathResult {
411 const interpolatedPathSegments = parsePathname(path, parseCache)
412β
413 function encodeParam(key: string): any {
414 const value = params[key]
415 const isValueString = typeof value === 'string'
416β
417 if (key === '*' || key === '_splat') {
418 // the splat/catch-all routes shouldn't have the '/' encoded out
419 return isValueString ? encodeURI(value) : value
420 } else {
421 return isValueString ? encodePathParam(value, decodeCharMap) : value
422 }
423 }
424β
425 // Tracking if any params are missing in the `params` object
426 // when interpolating the path
427 let isMissingParams = false
428β
429 const usedParams: Record<string, unknown> = {}
430 const interpolatedPath = joinPaths(
431 interpolatedPathSegments.map((segment) => {
432 if (segment.type === SEGMENT_TYPE_PATHNAME) {
433 return segment.value
434 }
435β
436 if (segment.type === SEGMENT_TYPE_WILDCARD) {
437 usedParams._splat = params._splat
438β
439 // TODO: Deprecate *
440 usedParams['*'] = params._splat
441β
442 const segmentPrefix = segment.prefixSegment || ''
443 const segmentSuffix = segment.suffixSegment || ''
444β
445 // Check if _splat parameter is missing. _splat could be missing if undefined or an empty string or some other falsy value.
446 if (!params._splat) {
447 isMissingParams = true
448 // For missing splat parameters, just return the prefix and suffix without the wildcard
449 if (leaveWildcards) {
450 return `${segmentPrefix}${segment.value}${segmentSuffix}`
451 }
452 // If there is a prefix or suffix, return them joined, otherwise omit the segment
453 if (segmentPrefix || segmentSuffix) {
454 return `${segmentPrefix}${segmentSuffix}`
455 }
456 return undefined
457 }
458β
459 const value = encodeParam('_splat')
460 if (leaveWildcards) {
461 return `${segmentPrefix}${segment.value}${value ?? ''}${segmentSuffix}`
462 }
463 return `${segmentPrefix}${value}${segmentSuffix}`
464 }
465β
466 if (segment.type === SEGMENT_TYPE_PARAM) {
467 const key = segment.value.substring(1)
468 if (!isMissingParams && !(key in params)) {
469 isMissingParams = true
470 }
471 usedParams[key] = params[key]
472β
473 const segmentPrefix = segment.prefixSegment || ''
474 const segmentSuffix = segment.suffixSegment || ''
475 if (leaveParams) {
476 const value = encodeParam(segment.value)
477 return `${segmentPrefix}${segment.value}${value ?? ''}${segmentSuffix}`
478 }
479 return `${segmentPrefix}${encodeParam(key) ?? 'undefined'}${segmentSuffix}`
480 }
481β
482 if (segment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
483 const key = segment.value.substring(1)
484β
485 const segmentPrefix = segment.prefixSegment || ''
486 const segmentSuffix = segment.suffixSegment || ''
487β
488 // Check if optional parameter is missing or undefined
489 if (!(key in params) || params[key] == null) {
490 if (leaveWildcards) {
491 return `${segmentPrefix}${key}${segmentSuffix}`
492 }
493 // For optional params with prefix/suffix, keep the prefix/suffix but omit the param
494 if (segmentPrefix || segmentSuffix) {
495 return `${segmentPrefix}${segmentSuffix}`
496 }
497 // If no prefix/suffix, omit the entire segment
498 return undefined
499 }
500β
501 usedParams[key] = params[key]
502β
503 if (leaveParams) {
504 const value = encodeParam(segment.value)
505 return `${segmentPrefix}${segment.value}${value ?? ''}${segmentSuffix}`
506 }
507 if (leaveWildcards) {
508 return `${segmentPrefix}${key}${encodeParam(key) ?? ''}${segmentSuffix}`
509 }
510 return `${segmentPrefix}${encodeParam(key) ?? ''}${segmentSuffix}`
511 }
512β
513 return segment.value
514 }),
515 )
516 return { usedParams, interpolatedPath, isMissingParams }
517}
518β
519function encodePathParam(value: string, decodeCharMap?: Map<string, string>) {
520 let encoded = encodeURIComponent(value)
521 if (decodeCharMap) {
522 for (const [encodedChar, char] of decodeCharMap) {
523 encoded = encoded.replaceAll(encodedChar, char)
524 }
525 }
526 return encoded
527}
528β
529/**
530 * Match a pathname against a route destination and return extracted params
531 * or `undefined`. Uses the same parsing as the router for consistency.
532 */
533/**
534 * Match a pathname against a route destination and return extracted params
535 * or `undefined`. Uses the same parsing as the router for consistency.
536 */
537export function matchPathname(
538 currentPathname: string,
539 matchLocation: Pick<MatchLocation, 'to' | 'fuzzy' | 'caseSensitive'>,
540 parseCache?: ParsePathnameCache,
541): AnyPathParams | undefined {
542 const pathParams = matchByPath(currentPathname, matchLocation, parseCache)
543 // const searchMatched = matchBySearch(location.search, matchLocation)
544β
545 if (matchLocation.to && !pathParams) {
546 return
547 }
548β
549 return pathParams ?? {}
550}
551β
552/** Low-level matcher that compares two path strings and extracts params. */
553/** Low-level matcher that compares two path strings and extracts params. */
554export function matchByPath(
555 from: string,
556 {
557 to,
558 fuzzy,
559 caseSensitive,
560 }: Pick<MatchLocation, 'to' | 'caseSensitive' | 'fuzzy'>,
561 parseCache?: ParsePathnameCache,
562): Record<string, string> | undefined {
563 const stringTo = to as string
564β
565 // Parse the from and to
566 const baseSegments = parsePathname(
567 from.startsWith('/') ? from : `/${from}`,
568 parseCache,
569 )
570 const routeSegments = parsePathname(
571 stringTo.startsWith('/') ? stringTo : `/${stringTo}`,
572 parseCache,
573 )
574β
575 const params: Record<string, string> = {}
576β
577 const result = isMatch(
578 baseSegments,
579 routeSegments,
580 params,
581 fuzzy,
582 caseSensitive,
583 )
584β
585 return result ? params : undefined
586}
587β
588function isMatch(
589 baseSegments: ReadonlyArray<Segment>,
590 routeSegments: ReadonlyArray<Segment>,
591 params: Record<string, string>,
592 fuzzy?: boolean,
593 caseSensitive?: boolean,
594): boolean {
595 let baseIndex = 0
596 let routeIndex = 0
597β
598 while (baseIndex < baseSegments.length || routeIndex < routeSegments.length) {
599 const baseSegment = baseSegments[baseIndex]
600 const routeSegment = routeSegments[routeIndex]
601β
602 if (routeSegment) {
603 if (routeSegment.type === SEGMENT_TYPE_WILDCARD) {
604 // Capture all remaining segments for a wildcard
605 const remainingBaseSegments = baseSegments.slice(baseIndex)
606β
607 let _splat: string
608β
609 // If this is a wildcard with prefix/suffix, we need to handle the first segment specially
610 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
611 if (!baseSegment) return false
612β
613 const prefix = routeSegment.prefixSegment || ''
614 const suffix = routeSegment.suffixSegment || ''
615β
616 // Check if the base segment starts with prefix and ends with suffix
617 const baseValue = baseSegment.value
618 if ('prefixSegment' in routeSegment) {
619 if (!baseValue.startsWith(prefix)) {
620 return false
621 }
622 }
623 if ('suffixSegment' in routeSegment) {
624 if (
625 !baseSegments[baseSegments.length - 1]?.value.endsWith(suffix)
626 ) {
627 return false
628 }
629 }
630β
631 let rejoinedSplat = decodeURI(
632 joinPaths(remainingBaseSegments.map((d) => d.value)),
633 )
634β
635 // Remove the prefix and suffix from the rejoined splat
636 if (prefix && rejoinedSplat.startsWith(prefix)) {
637 rejoinedSplat = rejoinedSplat.slice(prefix.length)
638 }
639β
640 if (suffix && rejoinedSplat.endsWith(suffix)) {
641 rejoinedSplat = rejoinedSplat.slice(
642 0,
643 rejoinedSplat.length - suffix.length,
644 )
645 }
646β
647 _splat = rejoinedSplat
648 } else {
649 // If no prefix/suffix, just rejoin the remaining segments
650 _splat = decodeURI(
651 joinPaths(remainingBaseSegments.map((d) => d.value)),
652 )
653 }
654β
655 // TODO: Deprecate *
656 params['*'] = _splat
657 params['_splat'] = _splat
658 return true
659 }
660β
661 if (routeSegment.type === SEGMENT_TYPE_PATHNAME) {
662 if (routeSegment.value === '/' && !baseSegment?.value) {
663 routeIndex++
664 continue
665 }
666β
667 if (baseSegment) {
668 if (caseSensitive) {
669 if (routeSegment.value !== baseSegment.value) {
670 return false
671 }
672 } else if (
673 routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()
674 ) {
675 return false
676 }
677 baseIndex++
678 routeIndex++
679 continue
680 } else {
681 return false
682 }
683 }
684β
685 if (routeSegment.type === SEGMENT_TYPE_PARAM) {
686 if (!baseSegment) {
687 return false
688 }
689β
690 if (baseSegment.value === '/') {
691 return false
692 }
693β
694 let _paramValue = ''
695 let matched = false
696β
697 // If this param has prefix/suffix, we need to extract the actual parameter value
698 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
699 const prefix = routeSegment.prefixSegment || ''
700 const suffix = routeSegment.suffixSegment || ''
701β
702 // Check if the base segment starts with prefix and ends with suffix
703 const baseValue = baseSegment.value
704 if (prefix && !baseValue.startsWith(prefix)) {
705 return false
706 }
707 if (suffix && !baseValue.endsWith(suffix)) {
708 return false
709 }
710β
711 let paramValue = baseValue
712 if (prefix && paramValue.startsWith(prefix)) {
713 paramValue = paramValue.slice(prefix.length)
714 }
715 if (suffix && paramValue.endsWith(suffix)) {
716 paramValue = paramValue.slice(0, paramValue.length - suffix.length)
717 }
718β
719 _paramValue = decodeURIComponent(paramValue)
720 matched = true
721 } else {
722 // If no prefix/suffix, just decode the base segment value
723 _paramValue = decodeURIComponent(baseSegment.value)
724 matched = true
725 }
726β
727 if (matched) {
728 params[routeSegment.value.substring(1)] = _paramValue
729 baseIndex++
730 }
731β
732 routeIndex++
733 continue
734 }
735β
736 if (routeSegment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
737 // Optional parameters can be missing - don't fail the match
738 if (!baseSegment) {
739 // No base segment for optional param - skip this route segment
740 routeIndex++
741 continue
742 }
743β
744 if (baseSegment.value === '/') {
745 // Skip slash segments for optional params
746 routeIndex++
747 continue
748 }
749β
750 let _paramValue = ''
751 let matched = false
752β
753 // If this optional param has prefix/suffix, we need to extract the actual parameter value
754 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
755 const prefix = routeSegment.prefixSegment || ''
756 const suffix = routeSegment.suffixSegment || ''
757β
758 // Check if the base segment starts with prefix and ends with suffix
759 const baseValue = baseSegment.value
760 if (
761 (!prefix || baseValue.startsWith(prefix)) &&
762 (!suffix || baseValue.endsWith(suffix))
763 ) {
764 let paramValue = baseValue
765 if (prefix && paramValue.startsWith(prefix)) {
766 paramValue = paramValue.slice(prefix.length)
767 }
768 if (suffix && paramValue.endsWith(suffix)) {
769 paramValue = paramValue.slice(
770 0,
771 paramValue.length - suffix.length,
772 )
773 }
774β
775 _paramValue = decodeURIComponent(paramValue)
776 matched = true
777 }
778 } else {
779 // For optional params without prefix/suffix, we need to check if the current
780 // base segment should match this optional param or a later route segment
781β
782 // Look ahead to see if there's a later route segment that matches the current base segment
783 let shouldMatchOptional = true
784 for (
785 let lookAhead = routeIndex + 1;
786 lookAhead < routeSegments.length;
787 lookAhead++
788 ) {
789 const futureRouteSegment = routeSegments[lookAhead]
790 if (
791 futureRouteSegment?.type === SEGMENT_TYPE_PATHNAME &&
792 futureRouteSegment.value === baseSegment.value
793 ) {
794 // The current base segment matches a future pathname segment,
795 // so we should skip this optional parameter
796 shouldMatchOptional = false
797 break
798 }
799β
800 // If we encounter a required param or wildcard, stop looking ahead
801 if (
802 futureRouteSegment?.type === SEGMENT_TYPE_PARAM ||
803 futureRouteSegment?.type === SEGMENT_TYPE_WILDCARD
804 ) {
805 if (baseSegments.length < routeSegments.length) {
806 shouldMatchOptional = false
807 }
808 break
809 }
810 }
811β
812 if (shouldMatchOptional) {
813 // If no prefix/suffix, just decode the base segment value
814 _paramValue = decodeURIComponent(baseSegment.value)
815 matched = true
816 }
817 }
818β
819 if (matched) {
820 params[routeSegment.value.substring(1)] = _paramValue
821 baseIndex++
822 }
823β
824 routeIndex++
825 continue
826 }
827 }
828β
829 // If we have base segments left but no route segments, it's a fuzzy match
830 if (baseIndex < baseSegments.length && routeIndex >= routeSegments.length) {
831 params['**'] = joinPaths(
832 baseSegments.slice(baseIndex).map((d) => d.value),
833 )
834 return !!fuzzy && routeSegments[routeSegments.length - 1]?.value !== '/'
835 }
836β
837 // If we have route segments left but no base segments, check if remaining are optional
838 if (routeIndex < routeSegments.length && baseIndex >= baseSegments.length) {
839 // Check if all remaining route segments are optional
840 for (let i = routeIndex; i < routeSegments.length; i++) {
841 if (routeSegments[i]?.type !== SEGMENT_TYPE_OPTIONAL_PARAM) {
842 return false
843 }
844 }
845 // All remaining are optional, so we can finish
846 break
847 }
848β
849 break
850 }
851β
852 return true
853}