From d9e403b8b32867f9f84e33120467e0d1bcc13a11 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 21 Nov 2025 21:44:41 +0100 Subject: [PATCH 01/11] feat(router-core): validate params while matching --- .../router-core/src/new-process-route-tree.ts | 118 ++++++++++++++---- 1 file changed, 93 insertions(+), 25 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 7dda425f22..1996bd7afb 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -174,6 +174,7 @@ function parseSegments( const path = route.fullPath ?? route.from const length = path.length const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive + const parse = route.options?.params?.parse ?? null while (cursor < length) { const segment = parseSegment(path, cursor, data) let nextNode: AnySegmentNode @@ -232,12 +233,15 @@ function parseSegments( : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase() - const existingNode = node.dynamic?.find( - (s) => - s.caseSensitive === actuallyCaseSensitive && - s.prefix === prefix && - s.suffix === suffix, - ) + const existingNode = + !parse && + node.dynamic?.find( + (s) => + !s.parse && + s.caseSensitive === actuallyCaseSensitive && + s.prefix === prefix && + s.suffix === suffix, + ) if (existingNode) { nextNode = existingNode } else { @@ -271,12 +275,15 @@ function parseSegments( : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase() - const existingNode = node.optional?.find( - (s) => - s.caseSensitive === actuallyCaseSensitive && - s.prefix === prefix && - s.suffix === suffix, - ) + const existingNode = + !parse && + node.optional?.find( + (s) => + !s.parse && + s.caseSensitive === actuallyCaseSensitive && + s.prefix === prefix && + s.suffix === suffix, + ) if (existingNode) { nextNode = existingNode } else { @@ -326,6 +333,7 @@ function parseSegments( } node = nextNode } + node.parse = parse if ((route.path || !route.children) && !route.isRoot) { const isIndex = path.endsWith('/') // we cannot fuzzy match an index route, @@ -351,9 +359,21 @@ function parseSegments( } function sortDynamic( - a: { prefix?: string; suffix?: string; caseSensitive: boolean }, - b: { prefix?: string; suffix?: string; caseSensitive: boolean }, + a: { + prefix?: string + suffix?: string + caseSensitive: boolean + parse: null | ((params: Record) => any) + }, + b: { + prefix?: string + suffix?: string + caseSensitive: boolean + parse: null | ((params: Record) => any) + }, ) { + if (a.parse && !b.parse) return -1 + if (!a.parse && b.parse) return 1 if (a.prefix && b.prefix && a.prefix !== b.prefix) { if (a.prefix.startsWith(b.prefix)) return -1 if (b.prefix.startsWith(a.prefix)) return 1 @@ -421,6 +441,7 @@ function createStaticNode( parent: null, isIndex: false, notFound: null, + parse: null, } } @@ -451,6 +472,7 @@ function createDynamicNode( parent: null, isIndex: false, notFound: null, + parse: null, caseSensitive, prefix, suffix, @@ -508,6 +530,9 @@ type SegmentNode = { /** Same as `route`, but only present if both an "index route" and a "layout route" exist at this path */ notFound: T | null + + /** route.options.params.parse function, set on the last node of the route */ + parse: null | ((params: Record) => any) } type RouteLike = { @@ -517,6 +542,9 @@ type RouteLike = { isRoot?: boolean options?: { caseSensitive?: boolean + params?: { + parse?: (params: Record) => any + } } } & // router tree @@ -706,7 +734,7 @@ function findMatch( const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null - const params = extractParams(path, parts, leaf) + const [params] = extractParams(path, parts, leaf) const isFuzzyMatch = '**' in leaf if (isFuzzyMatch) params['**'] = leaf['**'] const route = isFuzzyMatch @@ -721,16 +749,23 @@ function findMatch( function extractParams( path: string, parts: Array, - leaf: { node: AnySegmentNode; skipped: number }, -) { + leaf: { + node: AnySegmentNode + skipped: number + extract?: { part: number; node: number; path: number } + params?: Record + }, +): [ + params: Record, + state: { part: number; node: number; path: number }, +] { const list = buildBranch(leaf.node) let nodeParts: Array | null = null const params: Record = {} - for ( - let partIndex = 0, nodeIndex = 0, pathIndex = 0; - nodeIndex < list.length; - partIndex++, nodeIndex++, pathIndex++ - ) { + let partIndex = leaf.extract?.part ?? 0 + let nodeIndex = leaf.extract?.node ?? 0 + let pathIndex = leaf.extract?.path ?? 0 + for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++) { const node = list[nodeIndex]! const part = parts[partIndex] const currentPathIndex = pathIndex @@ -785,7 +820,8 @@ function extractParams( break } } - return params + if (leaf.params) Object.assign(params, leaf.params) + return [params, { part: partIndex, node: nodeIndex, path: pathIndex }] } function buildRouteBranch(route: T) { @@ -823,6 +859,10 @@ type MatchStackFrame = { statics: number dynamics: number optionals: number + /** intermediary state for param extraction */ + extract?: { part: number; node: number; path: number } + /** intermediary params from param extraction */ + params?: Record } function getNodeMatch( @@ -862,8 +902,22 @@ function getNodeMatch( while (stack.length) { const frame = stack.pop()! - // eslint-disable-next-line prefer-const - let { node, index, skipped, depth, statics, dynamics, optionals } = frame + const { node, index, skipped, depth, statics, dynamics, optionals } = frame + let { extract, params } = frame + + if (node.parse) { + // if there is a parse function, we need to extract the params that we have so far and run it. + // if this function throws, we cannot consider this a valid match + try { + ;[params, extract] = extractParams(path, parts, frame) + // TODO: can we store the parsed value somewhere to avoid re-parsing later? + node.parse(params) + frame.extract = extract + frame.params = params + } catch { + continue + } + } // In fuzzy mode, track the best partial match we've found so far if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) { @@ -913,6 +967,8 @@ function getNodeMatch( statics, dynamics, optionals, + extract, + params, } break } @@ -933,6 +989,8 @@ function getNodeMatch( statics, dynamics, optionals, + extract, + params, }) // enqueue skipping the optional } if (!isBeyondPath) { @@ -954,6 +1012,8 @@ function getNodeMatch( statics, dynamics, optionals: optionals + 1, + extract, + params, }) } } @@ -979,6 +1039,8 @@ function getNodeMatch( statics, dynamics: dynamics + 1, optionals, + extract, + params, }) } } @@ -997,6 +1059,8 @@ function getNodeMatch( statics: statics + 1, dynamics, optionals, + extract, + params, }) } } @@ -1013,6 +1077,8 @@ function getNodeMatch( statics: statics + 1, dynamics, optionals, + extract, + params, }) } } @@ -1031,6 +1097,8 @@ function getNodeMatch( return { node: bestFuzzy.node, skipped: bestFuzzy.skipped, + extract: bestFuzzy.extract, + params: bestFuzzy.params, '**': decodeURIComponent(splat), } } From 2fd300956a9be572dbe106a0df85cd137b8c8873 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 30 Nov 2025 12:29:27 +0100 Subject: [PATCH 02/11] more wip --- .../router-core/src/new-process-route-tree.ts | 83 ++++++++++++++----- packages/router-core/src/route.ts | 2 + packages/router-core/src/router.ts | 5 +- 3 files changed, 69 insertions(+), 21 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index b525449885..682eea5ec6 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -175,6 +175,7 @@ function parseSegments( const length = path.length const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive const parse = route.options?.params?.parse ?? null + const skipRouteOnParseError = !!route.options?.skipRouteOnParseError while (cursor < length) { const segment = parseSegment(path, cursor, data) let nextNode: AnySegmentNode @@ -234,10 +235,10 @@ function parseSegments( ? suffix_raw : suffix_raw.toLowerCase() const existingNode = - !parse && + (!parse || !skipRouteOnParseError) && node.dynamic?.find( (s) => - !s.parse && + (!s.parse || !s.skipRouteOnParseError) && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix, @@ -276,10 +277,10 @@ function parseSegments( ? suffix_raw : suffix_raw.toLowerCase() const existingNode = - !parse && + (!parse || !skipRouteOnParseError) && node.optional?.find( (s) => - !s.parse && + (!s.parse || !s.skipRouteOnParseError) && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix, @@ -334,6 +335,7 @@ function parseSegments( node = nextNode } node.parse = parse + node.skipRouteOnParseError = skipRouteOnParseError if ((route.path || !route.children) && !route.isRoot) { const isIndex = path.endsWith('/') // we cannot fuzzy match an index route, @@ -442,6 +444,7 @@ function createStaticNode( isIndex: false, notFound: null, parse: null, + skipRouteOnParseError: false, } } @@ -473,6 +476,7 @@ function createDynamicNode( isIndex: false, notFound: null, parse: null, + skipRouteOnParseError: false, caseSensitive, prefix, suffix, @@ -533,6 +537,9 @@ type SegmentNode = { /** route.options.params.parse function, set on the last node of the route */ parse: null | ((params: Record) => any) + + /** If true, errors thrown during parsing will cause this route to be ignored as a match candidate */ + skipRouteOnParseError: boolean } type RouteLike = { @@ -541,6 +548,7 @@ type RouteLike = { parentRoute?: RouteLike // parent route, isRoot?: boolean options?: { + skipRouteOnParseError?: boolean caseSensitive?: boolean params?: { parse?: (params: Record) => any @@ -635,6 +643,7 @@ type RouteMatch> = { route: T params: Record branch: ReadonlyArray + error?: unknown } export function findRouteMatch< @@ -730,22 +739,29 @@ function findMatch( path: string, segmentTree: AnySegmentNode, fuzzy = false, -): { route: T; params: Record } | null { +): { route: T; params: Record; error?: unknown } | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null const [params] = extractParams(path, parts, leaf) - const isFuzzyMatch = '**' in leaf - if (isFuzzyMatch) params['**'] = leaf['**'] + const isFuzzyMatch = '**' in params const route = isFuzzyMatch ? (leaf.node.notFound ?? leaf.node.route!) : leaf.node.route! return { route, params, + error: leaf.error, } } +/** + * This function is "resumable": + * - the `leaf` input can contain `extract` and `params` properties from a previous `extractParams` call + * - the returned `state` can be passed back as `extract` in a future call to continue extracting params from where we left off + * + * Inputs are *not* mutated. + */ function extractParams( path: string, parts: Array, @@ -862,7 +878,12 @@ type MatchStackFrame = { /** intermediary state for param extraction */ extract?: { part: number; node: number; path: number } /** intermediary params from param extraction */ + // TODO: I'm not sure, but I think we need both the raw strings for `interpolatePath` and the parsed values for the final match object + // I think they can still be accumulated (separately) in a single object (each) because `interpolatePath` returns the `usedParams` anyway params?: Record + /** capture error from parse function */ + // TODO: we might need to get a Map instead, so that matches can be built correctly + error?: unknown } function getNodeMatch( @@ -903,19 +924,25 @@ function getNodeMatch( while (stack.length) { const frame = stack.pop()! const { node, index, skipped, depth, statics, dynamics, optionals } = frame - let { extract, params } = frame + let { extract, params, error } = frame if (node.parse) { // if there is a parse function, we need to extract the params that we have so far and run it. // if this function throws, we cannot consider this a valid match try { ;[params, extract] = extractParams(path, parts, frame) - // TODO: can we store the parsed value somewhere to avoid re-parsing later? - node.parse(params) frame.extract = extract frame.params = params - } catch { - continue + params = node.parse(params) + frame.params = params + } catch (e) { + if (!error) { + error = e + frame.error = e + } + if (node.skipRouteOnParseError) continue + // TODO: when *not* continuing, we need to accumulate all errors so we can assign them to the + // corresponding match objects in `matchRoutesInternal`? } } @@ -959,7 +986,7 @@ function getNodeMatch( if (casePart !== suffix) continue } // the first wildcard match is the highest priority one - wildcardMatch = { + const frame = { node: segment, index, skipped, @@ -969,7 +996,22 @@ function getNodeMatch( optionals, extract, params, + error, } + // TODO: should we handle wildcard candidates like any other frame? + // then we wouldn't need to duplicate the parsing logic here + if (segment.parse) { + try { + const [params, extract] = extractParams(path, parts, frame) + frame.extract = extract + frame.params = params + frame.params = segment.parse(params) + } catch (e) { + frame.error = e + if (segment.skipRouteOnParseError) continue + } + } + wildcardMatch = frame break } } @@ -991,6 +1033,7 @@ function getNodeMatch( optionals, extract, params, + error, }) // enqueue skipping the optional } if (!isBeyondPath) { @@ -1014,6 +1057,7 @@ function getNodeMatch( optionals: optionals + 1, extract, params, + error, }) } } @@ -1041,6 +1085,7 @@ function getNodeMatch( optionals, extract, params, + error, }) } } @@ -1061,6 +1106,7 @@ function getNodeMatch( optionals, extract, params, + error, }) } } @@ -1079,6 +1125,7 @@ function getNodeMatch( optionals, extract, params, + error, }) } } @@ -1100,13 +1147,9 @@ function getNodeMatch( sliceIndex += parts[i]!.length } const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex) - return { - node: bestFuzzy.node, - skipped: bestFuzzy.skipped, - extract: bestFuzzy.extract, - params: bestFuzzy.params, - '**': decodeURIComponent(splat), - } + bestFuzzy.params ??= {} + bestFuzzy.params['**'] = decodeURIComponent(splat) + return bestFuzzy } return null diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 53d726ef05..b87b657da6 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1188,6 +1188,8 @@ export interface UpdatableRouteOptions< in out TBeforeLoadFn, > extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { + /** If true, this route will be skipped during matching if a parse error occurs, and we'll look for another match */ + skipRouteOnParseError?: boolean // If true, this route will be matched as case-sensitive caseSensitive?: boolean // If true, this route will be forcefully wrapped in a suspense boundary diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 4efaa61b7b..ceb0c0cecb 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -700,6 +700,7 @@ export type GetMatchRoutesFn = (pathname: string) => { matchedRoutes: ReadonlyArray routeParams: Record foundRoute: AnyRoute | undefined + parseError?: unknown } export type EmitFn = (routerEvent: RouterEvent) => void @@ -2680,15 +2681,17 @@ export function getMatchedRoutes({ const trimmedPath = trimPathRight(pathname) let foundRoute: TRouteLike | undefined = undefined + let parseError: unknown = undefined const match = findRouteMatch(trimmedPath, processedTree, true) if (match) { foundRoute = match.route Object.assign(routeParams, match.params) // Copy params, because they're cached + parseError = match.error } const matchedRoutes = match?.branch || [routesById[rootRouteId]!] - return { matchedRoutes, routeParams, foundRoute } + return { matchedRoutes, routeParams, foundRoute, parseError } } function applySearchMiddleware({ From b9c416a62790b22890b5ac061657886fbad9281f Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 21 Dec 2025 10:35:04 +0100 Subject: [PATCH 03/11] introduce index node and pathless node --- .../router-core/src/new-process-route-tree.ts | 152 +++++++++---- .../tests/new-process-route-tree.test.ts | 211 ++++++++++++++++++ 2 files changed, 321 insertions(+), 42 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index cf8f911d34..47afccc031 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -7,12 +7,16 @@ export const SEGMENT_TYPE_PATHNAME = 0 export const SEGMENT_TYPE_PARAM = 1 export const SEGMENT_TYPE_WILDCARD = 2 export const SEGMENT_TYPE_OPTIONAL_PARAM = 3 +const SEGMENT_TYPE_PATHLESS = 4 // only used in matching to represent pathless routes that need to carry more information +const SEGMENT_TYPE_INDEX = 5 export type SegmentKind = | typeof SEGMENT_TYPE_PATHNAME | typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM + | typeof SEGMENT_TYPE_PATHLESS + | typeof SEGMENT_TYPE_INDEX const PARAM_W_CURLY_BRACES_RE = /^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ // prefix{$paramName}suffix @@ -332,24 +336,48 @@ function parseSegments( node.wildcard.push(next) } } - node = nextNode + node = nextNode! } + + if ( + parse && + skipRouteOnParseError && + route.children && + !route.isRoot && + route.id && + route.id.charCodeAt(route.id.lastIndexOf('/') + 1) === 95 /* '_' */ + ) { + const pathlessNode = createStaticNode( + route.fullPath ?? route.from, + ) + pathlessNode.kind = SEGMENT_TYPE_PATHLESS + pathlessNode.parent = node + depth++ + pathlessNode.depth = depth + node.pathless ??= [] + node.pathless.push(pathlessNode) + node = pathlessNode + } + + const isLeaf = (route.path || !route.children) && !route.isRoot + if (isLeaf && path.endsWith('/')) { + const indexNode = createStaticNode( + route.fullPath ?? route.from, + ) + indexNode.kind = SEGMENT_TYPE_INDEX + indexNode.parent = node + depth++ + indexNode.depth = depth + node.index = indexNode + node = indexNode + } + node.parse = parse node.skipRouteOnParseError = skipRouteOnParseError - if ((route.path || !route.children) && !route.isRoot) { - const isIndex = path.endsWith('/') - // we cannot fuzzy match an index route, - // but if there is *also* a layout route at this path, save it as notFound - // we can use it when fuzzy matching to display the NotFound component in the layout route - if (!isIndex) node.notFound = route - // does the new route take precedence over an existing one? - // yes if previous is not an index route and new one is an index route - if (!node.route || (!node.isIndex && isIndex)) { - node.route = route - // when replacing, replace all attributes that are route-specific (`fullPath` only at the moment) - node.fullPath = route.fullPath ?? route.from - } - node.isIndex ||= isIndex + if (isLeaf && !node.route) { + node.route = route + // when replacing, replace all attributes that are route-specific (`fullPath` only at the moment) + node.fullPath = route.fullPath ?? route.from } } if (route.children) @@ -403,6 +431,11 @@ function sortDynamic( } function sortTreeNodes(node: SegmentNode) { + if (node.pathless) { + for (const child of node.pathless) { + sortTreeNodes(child) + } + } if (node.static) { for (const child of node.static.values()) { sortTreeNodes(child) @@ -439,6 +472,8 @@ function createStaticNode( return { kind: SEGMENT_TYPE_PATHNAME, depth: 0, + pathless: null, + index: null, static: null, staticInsensitive: null, dynamic: null, @@ -447,8 +482,6 @@ function createStaticNode( route: null, fullPath, parent: null, - isIndex: false, - notFound: null, parse: null, skipRouteOnParseError: false, } @@ -471,6 +504,8 @@ function createDynamicNode( return { kind, depth: 0, + pathless: null, + index: null, static: null, staticInsensitive: null, dynamic: null, @@ -479,8 +514,6 @@ function createDynamicNode( route: null, fullPath, parent: null, - isIndex: false, - notFound: null, parse: null, skipRouteOnParseError: false, caseSensitive, @@ -490,14 +523,17 @@ function createDynamicNode( } type StaticSegmentNode = SegmentNode & { - kind: typeof SEGMENT_TYPE_PATHNAME + kind: + | typeof SEGMENT_TYPE_PATHNAME + | typeof SEGMENT_TYPE_PATHLESS + | typeof SEGMENT_TYPE_INDEX } type DynamicSegmentNode = SegmentNode & { kind: - | typeof SEGMENT_TYPE_PARAM - | typeof SEGMENT_TYPE_WILDCARD - | typeof SEGMENT_TYPE_OPTIONAL_PARAM + | typeof SEGMENT_TYPE_PARAM + | typeof SEGMENT_TYPE_WILDCARD + | typeof SEGMENT_TYPE_OPTIONAL_PARAM prefix?: string suffix?: string caseSensitive: boolean @@ -510,6 +546,10 @@ type AnySegmentNode = type SegmentNode = { kind: SegmentKind + pathless: Array> | null + + index: StaticSegmentNode | null + /** Static segments (highest priority) */ static: Map> | null @@ -535,12 +575,6 @@ type SegmentNode = { depth: number - /** is it an index route (trailing / path), only valid for nodes with a `route` */ - isIndex: boolean - - /** Same as `route`, but only present if both an "index route" and a "layout route" exist at this path */ - notFound: T | null - /** route.options.params.parse function, set on the last node of the route */ parse: null | ((params: Record) => any) @@ -549,6 +583,7 @@ type SegmentNode = { } type RouteLike = { + id?: string path?: string // relative path from the parent, children?: Array // child routes, parentRoute?: RouteLike // parent route, @@ -750,10 +785,7 @@ function findMatch( const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null const [params] = extractParams(path, parts, leaf) - const isFuzzyMatch = '**' in params - const route = isFuzzyMatch - ? (leaf.node.notFound ?? leaf.node.route!) - : leaf.node.route! + const route = leaf.node.route! return { route, params, @@ -778,9 +810,9 @@ function extractParams( params?: Record }, ): [ - params: Record, - state: { part: number; node: number; path: number }, -] { + params: Record, + state: { part: number; node: number; path: number }, + ] { const list = buildBranch(leaf.node) let nodeParts: Array | null = null const params: Record = {} @@ -900,7 +932,7 @@ function getNodeMatch( ) { const trailingSlash = !last(parts) const pathIsIndex = trailingSlash && path !== '/' - const partsLength = parts.length - (trailingSlash ? 1 : 0) + const partsLength = parts.length type Frame = MatchStackFrame @@ -953,19 +985,19 @@ function getNodeMatch( } // In fuzzy mode, track the best partial match we've found so far - if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) { + if (fuzzy && node.kind !== SEGMENT_TYPE_INDEX && isFrameMoreSpecific(bestFuzzy, frame)) { bestFuzzy = frame } const isBeyondPath = index === partsLength if (isBeyondPath) { - if (node.route && (!pathIsIndex || node.isIndex)) { + if (node.route && (!pathIsIndex || node.kind === SEGMENT_TYPE_INDEX)) { if (isFrameMoreSpecific(bestMatch, frame)) { bestMatch = frame } // perfect match, no need to continue - if (statics === partsLength && node.isIndex) return bestMatch + if (statics === partsLength && node.kind === SEGMENT_TYPE_INDEX) return bestMatch } // beyond the length of the path parts, only skipped optional segments or wildcard segments can match if (!node.optional && !node.wildcard) continue @@ -1135,6 +1167,42 @@ function getNodeMatch( }) } } + + // 0. Try index match + if (node.index) { + stack.push({ + node: node.index, + index: index + 1, + skipped, + depth: depth + 1, + statics: statics + 1, + dynamics, + optionals, + extract, + params, + error, + }) + } + + // 0. Try pathless match + if (node.pathless) { + const nextDepth = depth + 1 + for (let i = node.pathless.length - 1; i >= 0; i--) { + const segment = node.pathless[i]! + stack.push({ + node: segment, + index, + skipped, + depth: nextDepth, + statics, + dynamics, + optionals, + extract, + params, + error, + }) + } + } } if (bestMatch && wildcardMatch) { @@ -1175,8 +1243,8 @@ function isFrameMoreSpecific( (next.dynamics === prev.dynamics && (next.optionals > prev.optionals || (next.optionals === prev.optionals && - (next.node.isIndex > prev.node.isIndex || - (next.node.isIndex === prev.node.isIndex && + ((next.node.kind === SEGMENT_TYPE_INDEX) > (prev.node.kind === SEGMENT_TYPE_INDEX) || + ((next.node.kind === SEGMENT_TYPE_INDEX) === (prev.node.kind === SEGMENT_TYPE_INDEX) && next.depth > prev.depth))))))) ) } diff --git a/packages/router-core/tests/new-process-route-tree.test.ts b/packages/router-core/tests/new-process-route-tree.test.ts index 746cd47092..06a70d26eb 100644 --- a/packages/router-core/tests/new-process-route-tree.test.ts +++ b/packages/router-core/tests/new-process-route-tree.test.ts @@ -863,6 +863,217 @@ describe('findRouteMatch', () => { }) }) }) + describe('pathless routes', () => { + it('builds segment tree correctly', () => { + const tree = { + path: '/', + isRoot: true, + id: '__root__', + fullPath: '/', + children: [ + { + path: '/', + id: '/', + fullPath: '/', + options: {}, + }, + { + id: '/$foo/_layout', + path: '$foo', + fullPath: '/$foo', + options: { + params: { parse: () => { } }, + skipRouteOnParseError: true, + }, + children: [ + { + id: '/$foo/_layout/bar', + path: 'bar', + fullPath: '/$foo/bar', + options: {}, + }, + { + id: '/$foo/_layout/', + path: '/', + fullPath: '/$foo/', + options: {}, + }, + ], + }, + { + id: '/$foo/hello', + path: '$foo/hello', + fullPath: '/$foo/hello', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + expect(processedTree.segmentTree).toMatchInlineSnapshot(` + { + "depth": 0, + "dynamic": [ + { + "caseSensitive": false, + "depth": 1, + "dynamic": null, + "fullPath": "/$foo", + "index": null, + "kind": 1, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": [ + { + "depth": 2, + "dynamic": null, + "fullPath": "/$foo", + "index": { + "depth": 3, + "dynamic": null, + "fullPath": "/$foo/", + "index": null, + "kind": 5, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/$foo/", + "id": "/$foo/_layout/", + "options": {}, + "path": "/", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + "kind": 4, + "optional": null, + "parent": [Circular], + "parse": [Function], + "pathless": null, + "route": { + "children": [ + { + "fullPath": "/$foo/bar", + "id": "/$foo/_layout/bar", + "options": {}, + "path": "bar", + }, + { + "fullPath": "/$foo/", + "id": "/$foo/_layout/", + "options": {}, + "path": "/", + }, + ], + "fullPath": "/$foo", + "id": "/$foo/_layout", + "options": { + "params": { + "parse": [Function], + }, + "skipRouteOnParseError": true, + }, + "path": "$foo", + }, + "skipRouteOnParseError": true, + "static": null, + "staticInsensitive": Map { + "bar" => { + "depth": 3, + "dynamic": null, + "fullPath": "/$foo/bar", + "index": null, + "kind": 0, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/$foo/bar", + "id": "/$foo/_layout/bar", + "options": {}, + "path": "bar", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + }, + "wildcard": null, + }, + ], + "prefix": undefined, + "route": null, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": Map { + "hello" => { + "depth": 2, + "dynamic": null, + "fullPath": "/$foo/hello", + "index": null, + "kind": 0, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/$foo/hello", + "id": "/$foo/hello", + "options": {}, + "path": "$foo/hello", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + }, + "suffix": undefined, + "wildcard": null, + }, + ], + "fullPath": "/", + "index": { + "depth": 1, + "dynamic": null, + "fullPath": "/", + "index": null, + "kind": 5, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "route": { + "fullPath": "/", + "id": "/", + "options": {}, + "path": "/", + }, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + }, + "kind": 0, + "optional": null, + "parent": null, + "parse": null, + "pathless": null, + "route": null, + "skipRouteOnParseError": false, + "static": null, + "staticInsensitive": null, + "wildcard": null, + } + `) + }) + }) }) describe('processRouteMasks', { sequential: true }, () => { From 5e0ea276ee524225197947cb19040f8d61351263 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 21 Dec 2025 17:10:46 +0100 Subject: [PATCH 04/11] merge typo --- packages/router-core/src/new-process-route-tree.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 8568124624..33ce245c0b 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -18,13 +18,14 @@ export type SegmentKind = | typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM - | typeof SEGMENT_TYPE_PATHLESS - | typeof SEGMENT_TYPE_INDEX /** * All the kinds of segments that can be present in the segment tree. */ -type ExtendedSegmentKind = SegmentKind | typeof SEGMENT_TYPE_INDEX +type ExtendedSegmentKind = + | SegmentKind + | typeof SEGMENT_TYPE_INDEX + | typeof SEGMENT_TYPE_PATHLESS const PARAM_W_CURLY_BRACES_RE = /^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ // prefix{$paramName}suffix From fca20cefc249bb4ec4ec201823c564c6cccb3952 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 21 Dec 2025 17:22:46 +0100 Subject: [PATCH 05/11] more post-merge fixes --- .../router-core/src/new-process-route-tree.ts | 27 ++++++------------- .../tests/new-process-route-tree.test.ts | 6 ++--- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 33ce245c0b..1f8fb35dc7 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -345,9 +345,10 @@ function parseSegments( node.wildcard.push(next) } } - node = nextNode! + node = nextNode } + // create pathless node if ( parse && skipRouteOnParseError && @@ -384,9 +385,10 @@ function parseSegments( node.parse = parse node.skipRouteOnParseError = skipRouteOnParseError + + // make node "matchable" if (isLeaf && !node.route) { node.route = route - // when replacing, replace all attributes that are route-specific (`fullPath` only at the moment) node.fullPath = route.fullPath ?? route.from } } @@ -948,7 +950,7 @@ function getNodeMatch( const trailingSlash = !last(parts) const pathIsIndex = trailingSlash && path !== '/' - const partsLength = parts.length + const partsLength = parts.length - (trailingSlash ? 1 : 0) type Frame = MatchStackFrame @@ -1032,6 +1034,9 @@ function getNodeMatch( statics, dynamics, optionals, + extract, + params, + error, } // perfect match, no need to continue // this is an optimization, algorithm should work correctly without this block @@ -1207,22 +1212,6 @@ function getNodeMatch( } } - // 0. Try index match - if (node.index) { - stack.push({ - node: node.index, - index: index + 1, - skipped, - depth: depth + 1, - statics: statics + 1, - dynamics, - optionals, - extract, - params, - error, - }) - } - // 0. Try pathless match if (node.pathless) { const nextDepth = depth + 1 diff --git a/packages/router-core/tests/new-process-route-tree.test.ts b/packages/router-core/tests/new-process-route-tree.test.ts index 9e96704043..fd9ea9828d 100644 --- a/packages/router-core/tests/new-process-route-tree.test.ts +++ b/packages/router-core/tests/new-process-route-tree.test.ts @@ -933,7 +933,7 @@ describe('findRouteMatch', () => { "dynamic": null, "fullPath": "/$foo/", "index": null, - "kind": 5, + "kind": 4, "optional": null, "parent": [Circular], "parse": null, @@ -949,7 +949,7 @@ describe('findRouteMatch', () => { "staticInsensitive": null, "wildcard": null, }, - "kind": 4, + "kind": 5, "optional": null, "parent": [Circular], "parse": [Function], @@ -1044,7 +1044,7 @@ describe('findRouteMatch', () => { "dynamic": null, "fullPath": "/", "index": null, - "kind": 5, + "kind": 4, "optional": null, "parent": [Circular], "parse": null, From c577ce9d3f9f9ec40ce716a0e63d7984faf3b57d Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 21 Dec 2025 17:57:40 +0100 Subject: [PATCH 06/11] don't handle regular parsing, only skip parsing --- .../router-core/src/new-process-route-tree.ts | 87 ++++++++----------- packages/router-core/src/router.ts | 4 +- 2 files changed, 36 insertions(+), 55 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 1f8fb35dc7..afdf56346d 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -536,16 +536,16 @@ function createDynamicNode( type StaticSegmentNode = SegmentNode & { kind: - | typeof SEGMENT_TYPE_PATHNAME - | typeof SEGMENT_TYPE_PATHLESS - | typeof SEGMENT_TYPE_INDEX + | typeof SEGMENT_TYPE_PATHNAME + | typeof SEGMENT_TYPE_PATHLESS + | typeof SEGMENT_TYPE_INDEX } type DynamicSegmentNode = SegmentNode & { kind: - | typeof SEGMENT_TYPE_PARAM - | typeof SEGMENT_TYPE_WILDCARD - | typeof SEGMENT_TYPE_OPTIONAL_PARAM + | typeof SEGMENT_TYPE_PARAM + | typeof SEGMENT_TYPE_WILDCARD + | typeof SEGMENT_TYPE_OPTIONAL_PARAM prefix?: string suffix?: string caseSensitive: boolean @@ -802,7 +802,6 @@ function findMatch( return { route, params, - error: leaf.error, } } @@ -823,9 +822,9 @@ function extractParams( params?: Record }, ): [ - params: Record, - state: { part: number; node: number; path: number }, -] { + params: Record, + state: { part: number; node: number; path: number }, + ] { const list = buildBranch(leaf.node) let nodeParts: Array | null = null const params: Record = {} @@ -932,9 +931,6 @@ type MatchStackFrame = { // TODO: I'm not sure, but I think we need both the raw strings for `interpolatePath` and the parsed values for the final match object // I think they can still be accumulated (separately) in a single object (each) because `interpolatePath` returns the `usedParams` anyway params?: Record - /** capture error from parse function */ - // TODO: we might need to get a Map instead, so that matches can be built correctly - error?: unknown } function getNodeMatch( @@ -980,26 +976,13 @@ function getNodeMatch( while (stack.length) { const frame = stack.pop()! const { node, index, skipped, depth, statics, dynamics, optionals } = frame - let { extract, params, error } = frame + let { extract, params } = frame - if (node.parse) { - // if there is a parse function, we need to extract the params that we have so far and run it. - // if this function throws, we cannot consider this a valid match - try { - ;[params, extract] = extractParams(path, parts, frame) - frame.extract = extract - frame.params = params - params = node.parse(params) - frame.params = params - } catch (e) { - if (!error) { - error = e - frame.error = e - } - if (node.skipRouteOnParseError) continue - // TODO: when *not* continuing, we need to accumulate all errors so we can assign them to the - // corresponding match objects in `matchRoutesInternal`? - } + if (node.skipRouteOnParseError && node.parse) { + const result = validateMatchParams(path, parts, frame) + if (!result) continue + params = result[0] + extract = result[1] } // In fuzzy mode, track the best partial match we've found so far @@ -1036,7 +1019,10 @@ function getNodeMatch( optionals, extract, params, - error, + } + if (node.index.skipRouteOnParseError && node.index.parse) { + const result = validateMatchParams(path, parts, indexFrame) + if (!result) continue } // perfect match, no need to continue // this is an optimization, algorithm should work correctly without this block @@ -1078,20 +1064,10 @@ function getNodeMatch( optionals, extract, params, - error, } - // TODO: should we handle wildcard candidates like any other frame? - // then we wouldn't need to duplicate the parsing logic here - if (segment.parse) { - try { - const [params, extract] = extractParams(path, parts, frame) - frame.extract = extract - frame.params = params - frame.params = segment.parse(params) - } catch (e) { - frame.error = e - if (segment.skipRouteOnParseError) continue - } + if (segment.skipRouteOnParseError && segment.parse) { + const result = validateMatchParams(path, parts, frame) + if (!result) continue } wildcardMatch = frame break @@ -1115,7 +1091,6 @@ function getNodeMatch( optionals, extract, params, - error, }) // enqueue skipping the optional } if (!isBeyondPath) { @@ -1139,7 +1114,6 @@ function getNodeMatch( optionals: optionals + 1, extract, params, - error, }) } } @@ -1167,7 +1141,6 @@ function getNodeMatch( optionals, extract, params, - error, }) } } @@ -1188,7 +1161,6 @@ function getNodeMatch( optionals, extract, params, - error, }) } } @@ -1207,7 +1179,6 @@ function getNodeMatch( optionals, extract, params, - error, }) } } @@ -1227,7 +1198,6 @@ function getNodeMatch( optionals, extract, params, - error, }) } } @@ -1257,6 +1227,19 @@ function getNodeMatch( return null } +function validateMatchParams(path: string, parts: Array, frame: MatchStackFrame) { + try { + const result = extractParams(path, parts, frame) + frame.params = result[0] + frame.extract = result[1] + result[0] = frame.node.parse!(result[0]) + frame.params = result[0] + return result + } catch { + return null + } +} + function isFrameMoreSpecific( // the stack frame previously saved as "best match" prev: MatchStackFrame | null, diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 874fd679cb..ffd4de77aa 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -2693,17 +2693,15 @@ export function getMatchedRoutes({ const trimmedPath = trimPathRight(pathname) let foundRoute: TRouteLike | undefined = undefined - let parseError: unknown = undefined const match = findRouteMatch(trimmedPath, processedTree, true) if (match) { foundRoute = match.route Object.assign(routeParams, match.params) // Copy params, because they're cached - parseError = match.error } const matchedRoutes = match?.branch || [routesById[rootRouteId]!] - return { matchedRoutes, routeParams, foundRoute, parseError } + return { matchedRoutes, routeParams, foundRoute } } function applySearchMiddleware({ From 035305935aa121568f1cb26bfc05f1a182e1bc3d Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 22 Dec 2025 00:52:21 +0100 Subject: [PATCH 07/11] fix sorting --- packages/router-core/src/new-process-route-tree.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index afdf56346d..d773e0b3c1 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -412,16 +412,18 @@ function sortDynamic( suffix?: string caseSensitive: boolean parse: null | ((params: Record) => any) + skipRouteOnParseError: boolean }, b: { prefix?: string suffix?: string caseSensitive: boolean parse: null | ((params: Record) => any) + skipRouteOnParseError: boolean }, ) { - if (a.parse && !b.parse) return -1 - if (!a.parse && b.parse) return 1 + if (a.parse && a.skipRouteOnParseError && (!b.parse || !b.skipRouteOnParseError)) return -1 + if ((!a.parse || !a.skipRouteOnParseError) && b.parse && b.skipRouteOnParseError) return 1 if (a.prefix && b.prefix && a.prefix !== b.prefix) { if (a.prefix.startsWith(b.prefix)) return -1 if (b.prefix.startsWith(a.prefix)) return 1 From c67704e3a1c832c57b778fcb4f0387e77c2fb67c Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 22 Dec 2025 00:52:48 +0100 Subject: [PATCH 08/11] format --- .../router-core/src/new-process-route-tree.ts | 38 +++++++++++++------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index d773e0b3c1..0703c9bf44 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -422,8 +422,18 @@ function sortDynamic( skipRouteOnParseError: boolean }, ) { - if (a.parse && a.skipRouteOnParseError && (!b.parse || !b.skipRouteOnParseError)) return -1 - if ((!a.parse || !a.skipRouteOnParseError) && b.parse && b.skipRouteOnParseError) return 1 + if ( + a.parse && + a.skipRouteOnParseError && + (!b.parse || !b.skipRouteOnParseError) + ) + return -1 + if ( + (!a.parse || !a.skipRouteOnParseError) && + b.parse && + b.skipRouteOnParseError + ) + return 1 if (a.prefix && b.prefix && a.prefix !== b.prefix) { if (a.prefix.startsWith(b.prefix)) return -1 if (b.prefix.startsWith(a.prefix)) return 1 @@ -538,16 +548,16 @@ function createDynamicNode( type StaticSegmentNode = SegmentNode & { kind: - | typeof SEGMENT_TYPE_PATHNAME - | typeof SEGMENT_TYPE_PATHLESS - | typeof SEGMENT_TYPE_INDEX + | typeof SEGMENT_TYPE_PATHNAME + | typeof SEGMENT_TYPE_PATHLESS + | typeof SEGMENT_TYPE_INDEX } type DynamicSegmentNode = SegmentNode & { kind: - | typeof SEGMENT_TYPE_PARAM - | typeof SEGMENT_TYPE_WILDCARD - | typeof SEGMENT_TYPE_OPTIONAL_PARAM + | typeof SEGMENT_TYPE_PARAM + | typeof SEGMENT_TYPE_WILDCARD + | typeof SEGMENT_TYPE_OPTIONAL_PARAM prefix?: string suffix?: string caseSensitive: boolean @@ -824,9 +834,9 @@ function extractParams( params?: Record }, ): [ - params: Record, - state: { part: number; node: number; path: number }, - ] { + params: Record, + state: { part: number; node: number; path: number }, +] { const list = buildBranch(leaf.node) let nodeParts: Array | null = null const params: Record = {} @@ -1229,7 +1239,11 @@ function getNodeMatch( return null } -function validateMatchParams(path: string, parts: Array, frame: MatchStackFrame) { +function validateMatchParams( + path: string, + parts: Array, + frame: MatchStackFrame, +) { try { const result = extractParams(path, parts, frame) frame.params = result[0] From c221f3ec2e912a1fb6125570beab42ec07e01c19 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 22 Dec 2025 01:21:03 +0100 Subject: [PATCH 09/11] remove error from types, its currently unused --- packages/router-core/src/new-process-route-tree.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 0703c9bf44..1785e31101 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -709,7 +709,6 @@ type RouteMatch> = { route: T params: Record branch: ReadonlyArray - error?: unknown } export function findRouteMatch< @@ -805,7 +804,7 @@ function findMatch( path: string, segmentTree: AnySegmentNode, fuzzy = false, -): { route: T; params: Record; error?: unknown } | null { +): { route: T; params: Record; } | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null From 1a3df20ba125d5132a401ab7ce30581677a02054 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 22 Dec 2025 01:21:20 +0100 Subject: [PATCH 10/11] format --- packages/router-core/src/new-process-route-tree.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 1785e31101..b2eb99ab01 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -804,7 +804,7 @@ function findMatch( path: string, segmentTree: AnySegmentNode, fuzzy = false, -): { route: T; params: Record; } | null { +): { route: T; params: Record } | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null From 6c36ddf2e2fda9737a7e6a474797fd496efa5292 Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Mon, 22 Dec 2025 10:20:08 +0100 Subject: [PATCH 11/11] implementation and tests --- .../basic-file-based/src/routeTree.gen.ts | 114 +++ .../src/routes/skip-on-parse-error/$num.tsx | 31 + .../src/routes/skip-on-parse-error/$slug.tsx | 23 + .../src/routes/skip-on-parse-error/$uuid.tsx | 33 + .../src/routes/skip-on-parse-error/index.tsx | 70 ++ .../src/routes/skip-on-parse-error/route.tsx | 20 + .../tests/skip-on-parse-error.spec.ts | 180 ++++ e2e/react-router/basic/src/main.tsx | 181 ++++ .../basic/tests/skip-on-parse-error.spec.ts | 181 ++++ .../router-core/src/new-process-route-tree.ts | 45 +- packages/router-core/src/router.ts | 51 +- .../tests/new-process-route-tree.test.ts | 774 ++++++++++++++++++ 12 files changed, 1682 insertions(+), 21 deletions(-) create mode 100644 e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx create mode 100644 e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx create mode 100644 e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx create mode 100644 e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx create mode 100644 e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx create mode 100644 e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts create mode 100644 e2e/react-router/basic/tests/skip-on-parse-error.spec.ts diff --git a/e2e/react-router/basic-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-file-based/src/routeTree.gen.ts index 28197e4d98..2d99238033 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -20,16 +20,21 @@ import { Route as ComponentTypesTestRouteImport } from './routes/component-types import { Route as AnchorRouteImport } from './routes/anchor' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as Char45824Char54620Char48124Char44397RouteRouteImport } from './routes/대한민국/route' +import { Route as SkipOnParseErrorRouteRouteImport } from './routes/skip-on-parse-error/route' import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' import { Route as PathlessLayoutRouteRouteImport } from './routes/pathless-layout/route' import { Route as NonNestedRouteRouteImport } from './routes/non-nested/route' import { Route as IndexRouteImport } from './routes/index' +import { Route as SkipOnParseErrorIndexRouteImport } from './routes/skip-on-parse-error/index' import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' import { Route as RelativeIndexRouteImport } from './routes/relative/index' import { Route as RedirectIndexRouteImport } from './routes/redirect/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as ParamsPsIndexRouteImport } from './routes/params-ps/index' import { Route as StructuralSharingEnabledRouteImport } from './routes/structural-sharing.$enabled' +import { Route as SkipOnParseErrorUuidRouteImport } from './routes/skip-on-parse-error/$uuid' +import { Route as SkipOnParseErrorSlugRouteImport } from './routes/skip-on-parse-error/$slug' +import { Route as SkipOnParseErrorNumRouteImport } from './routes/skip-on-parse-error/$num' import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' @@ -173,6 +178,11 @@ const Char45824Char54620Char48124Char44397RouteRoute = path: '/대한민국', getParentRoute: () => rootRouteImport, } as any) +const SkipOnParseErrorRouteRoute = SkipOnParseErrorRouteRouteImport.update({ + id: '/skip-on-parse-error', + path: '/skip-on-parse-error', + getParentRoute: () => rootRouteImport, +} as any) const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ id: '/search-params', path: '/search-params', @@ -193,6 +203,11 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) +const SkipOnParseErrorIndexRoute = SkipOnParseErrorIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ id: '/', path: '/', @@ -224,6 +239,21 @@ const StructuralSharingEnabledRoute = path: '/structural-sharing/$enabled', getParentRoute: () => rootRouteImport, } as any) +const SkipOnParseErrorUuidRoute = SkipOnParseErrorUuidRouteImport.update({ + id: '/$uuid', + path: '/$uuid', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) +const SkipOnParseErrorSlugRoute = SkipOnParseErrorSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) +const SkipOnParseErrorNumRoute = SkipOnParseErrorNumRouteImport.update({ + id: '/$num', + path: '/$num', + getParentRoute: () => SkipOnParseErrorRouteRoute, +} as any) const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ id: '/default', path: '/default', @@ -705,6 +735,7 @@ export interface FileRoutesByFullPath { '/non-nested': typeof NonNestedRouteRouteWithChildren '/pathless-layout': typeof PathlessLayoutLayoutRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/skip-on-parse-error': typeof SkipOnParseErrorRouteRouteWithChildren '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute @@ -729,12 +760,16 @@ export interface FileRoutesByFullPath { '/posts/$postId': typeof PostsPostIdRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute + '/skip-on-parse-error/$num': typeof SkipOnParseErrorNumRoute + '/skip-on-parse-error/$slug': typeof SkipOnParseErrorSlugRoute + '/skip-on-parse-error/$uuid': typeof SkipOnParseErrorUuidRoute '/structural-sharing/$enabled': typeof StructuralSharingEnabledRoute '/params-ps': typeof ParamsPsIndexRoute '/posts/': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute '/relative': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute + '/skip-on-parse-error/': typeof SkipOnParseErrorIndexRoute '/non-nested/deep/$baz': typeof NonNestedDeepBazRouteRouteWithChildren '/non-nested/named/$baz': typeof NonNestedNamedBazRouteRouteWithChildren '/non-nested/path/baz': typeof NonNestedPathBazRouteRouteWithChildren @@ -832,12 +867,16 @@ export interface FileRoutesByTo { '/lazyinside': typeof groupLazyinsideRoute '/posts/$postId': typeof PostsPostIdRoute '/search-params/default': typeof SearchParamsDefaultRoute + '/skip-on-parse-error/$num': typeof SkipOnParseErrorNumRoute + '/skip-on-parse-error/$slug': typeof SkipOnParseErrorSlugRoute + '/skip-on-parse-error/$uuid': typeof SkipOnParseErrorUuidRoute '/structural-sharing/$enabled': typeof StructuralSharingEnabledRoute '/params-ps': typeof ParamsPsIndexRoute '/posts': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute '/relative': typeof RelativeIndexRoute '/search-params': typeof SearchParamsIndexRoute + '/skip-on-parse-error': typeof SkipOnParseErrorIndexRoute '/params-ps/named/$foo': typeof ParamsPsNamedFooRouteRouteWithChildren '/params-ps/non-nested/$foo': typeof ParamsPsNonNestedFooRouteRouteWithChildren '/insidelayout': typeof groupLayoutInsidelayoutRoute @@ -907,6 +946,7 @@ export interface FileRoutesById { '/non-nested': typeof NonNestedRouteRouteWithChildren '/pathless-layout': typeof PathlessLayoutRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/skip-on-parse-error': typeof SkipOnParseErrorRouteRouteWithChildren '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/anchor': typeof AnchorRoute @@ -935,12 +975,16 @@ export interface FileRoutesById { '/posts/$postId': typeof PostsPostIdRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute + '/skip-on-parse-error/$num': typeof SkipOnParseErrorNumRoute + '/skip-on-parse-error/$slug': typeof SkipOnParseErrorSlugRoute + '/skip-on-parse-error/$uuid': typeof SkipOnParseErrorUuidRoute '/structural-sharing/$enabled': typeof StructuralSharingEnabledRoute '/params-ps/': typeof ParamsPsIndexRoute '/posts/': typeof PostsIndexRoute '/redirect/': typeof RedirectIndexRoute '/relative/': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute + '/skip-on-parse-error/': typeof SkipOnParseErrorIndexRoute '/non-nested/deep/$baz': typeof NonNestedDeepBazRouteRouteWithChildren '/non-nested/named/$baz': typeof NonNestedNamedBazRouteRouteWithChildren '/non-nested/path/baz': typeof NonNestedPathBazRouteRouteWithChildren @@ -1019,6 +1063,7 @@ export interface FileRouteTypes { | '/non-nested' | '/pathless-layout' | '/search-params' + | '/skip-on-parse-error' | '/대한민국' | '/anchor' | '/component-types-test' @@ -1043,12 +1088,16 @@ export interface FileRouteTypes { | '/posts/$postId' | '/redirect/$target' | '/search-params/default' + | '/skip-on-parse-error/$num' + | '/skip-on-parse-error/$slug' + | '/skip-on-parse-error/$uuid' | '/structural-sharing/$enabled' | '/params-ps' | '/posts/' | '/redirect' | '/relative' | '/search-params/' + | '/skip-on-parse-error/' | '/non-nested/deep/$baz' | '/non-nested/named/$baz' | '/non-nested/path/baz' @@ -1146,12 +1195,16 @@ export interface FileRouteTypes { | '/lazyinside' | '/posts/$postId' | '/search-params/default' + | '/skip-on-parse-error/$num' + | '/skip-on-parse-error/$slug' + | '/skip-on-parse-error/$uuid' | '/structural-sharing/$enabled' | '/params-ps' | '/posts' | '/redirect' | '/relative' | '/search-params' + | '/skip-on-parse-error' | '/params-ps/named/$foo' | '/params-ps/non-nested/$foo' | '/insidelayout' @@ -1220,6 +1273,7 @@ export interface FileRouteTypes { | '/non-nested' | '/pathless-layout' | '/search-params' + | '/skip-on-parse-error' | '/대한민국' | '/_layout' | '/anchor' @@ -1248,12 +1302,16 @@ export interface FileRouteTypes { | '/posts/$postId' | '/redirect/$target' | '/search-params/default' + | '/skip-on-parse-error/$num' + | '/skip-on-parse-error/$slug' + | '/skip-on-parse-error/$uuid' | '/structural-sharing/$enabled' | '/params-ps/' | '/posts/' | '/redirect/' | '/relative/' | '/search-params/' + | '/skip-on-parse-error/' | '/non-nested/deep/$baz' | '/non-nested/named/$baz' | '/non-nested/path/baz' @@ -1331,6 +1389,7 @@ export interface RootRouteChildren { NonNestedRouteRoute: typeof NonNestedRouteRouteWithChildren PathlessLayoutRouteRoute: typeof PathlessLayoutRouteRouteWithChildren SearchParamsRouteRoute: typeof SearchParamsRouteRouteWithChildren + SkipOnParseErrorRouteRoute: typeof SkipOnParseErrorRouteRouteWithChildren Char45824Char54620Char48124Char44397RouteRoute: typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren AnchorRoute: typeof AnchorRoute @@ -1451,6 +1510,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteRouteImport parentRoute: typeof rootRouteImport } + '/skip-on-parse-error': { + id: '/skip-on-parse-error' + path: '/skip-on-parse-error' + fullPath: '/skip-on-parse-error' + preLoaderRoute: typeof SkipOnParseErrorRouteRouteImport + parentRoute: typeof rootRouteImport + } '/search-params': { id: '/search-params' path: '/search-params' @@ -1479,6 +1545,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/skip-on-parse-error/': { + id: '/skip-on-parse-error/' + path: '/' + fullPath: '/skip-on-parse-error/' + preLoaderRoute: typeof SkipOnParseErrorIndexRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } '/search-params/': { id: '/search-params/' path: '/' @@ -1521,6 +1594,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof StructuralSharingEnabledRouteImport parentRoute: typeof rootRouteImport } + '/skip-on-parse-error/$uuid': { + id: '/skip-on-parse-error/$uuid' + path: '/$uuid' + fullPath: '/skip-on-parse-error/$uuid' + preLoaderRoute: typeof SkipOnParseErrorUuidRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } + '/skip-on-parse-error/$slug': { + id: '/skip-on-parse-error/$slug' + path: '/$slug' + fullPath: '/skip-on-parse-error/$slug' + preLoaderRoute: typeof SkipOnParseErrorSlugRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } + '/skip-on-parse-error/$num': { + id: '/skip-on-parse-error/$num' + path: '/$num' + fullPath: '/skip-on-parse-error/$num' + preLoaderRoute: typeof SkipOnParseErrorNumRouteImport + parentRoute: typeof SkipOnParseErrorRouteRoute + } '/search-params/default': { id: '/search-params/default' path: '/default' @@ -2377,6 +2471,25 @@ const SearchParamsRouteRouteChildren: SearchParamsRouteRouteChildren = { const SearchParamsRouteRouteWithChildren = SearchParamsRouteRoute._addFileChildren(SearchParamsRouteRouteChildren) +interface SkipOnParseErrorRouteRouteChildren { + SkipOnParseErrorNumRoute: typeof SkipOnParseErrorNumRoute + SkipOnParseErrorSlugRoute: typeof SkipOnParseErrorSlugRoute + SkipOnParseErrorUuidRoute: typeof SkipOnParseErrorUuidRoute + SkipOnParseErrorIndexRoute: typeof SkipOnParseErrorIndexRoute +} + +const SkipOnParseErrorRouteRouteChildren: SkipOnParseErrorRouteRouteChildren = { + SkipOnParseErrorNumRoute: SkipOnParseErrorNumRoute, + SkipOnParseErrorSlugRoute: SkipOnParseErrorSlugRoute, + SkipOnParseErrorUuidRoute: SkipOnParseErrorUuidRoute, + SkipOnParseErrorIndexRoute: SkipOnParseErrorIndexRoute, +} + +const SkipOnParseErrorRouteRouteWithChildren = + SkipOnParseErrorRouteRoute._addFileChildren( + SkipOnParseErrorRouteRouteChildren, + ) + interface Char45824Char54620Char48124Char44397RouteRouteChildren { Char45824Char54620Char48124Char44397WildcardSplatRoute: typeof Char45824Char54620Char48124Char44397WildcardSplatRoute Char45824Char54620Char48124Char44397Char55357Char56960IdRoute: typeof Char45824Char54620Char48124Char44397Char55357Char56960IdRoute @@ -2586,6 +2699,7 @@ const rootRouteChildren: RootRouteChildren = { NonNestedRouteRoute: NonNestedRouteRouteWithChildren, PathlessLayoutRouteRoute: PathlessLayoutRouteRouteWithChildren, SearchParamsRouteRoute: SearchParamsRouteRouteWithChildren, + SkipOnParseErrorRouteRoute: SkipOnParseErrorRouteRouteWithChildren, Char45824Char54620Char48124Char44397RouteRoute: Char45824Char54620Char48124Char44397RouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx new file mode 100644 index 0000000000..6e235f8f72 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$num.tsx @@ -0,0 +1,31 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error/$num')({ + params: { + parse: (params) => { + const num = parseInt(params.num, 10) + if (isNaN(num) || num.toString() !== params.num) { + throw new Error('Invalid numeric format') + } + return { num } + }, + stringify: (params) => ({ num: String(params.num) }), + }, + skipRouteOnParseError: true, + component: NumericRouteComponent, +}) + +function NumericRouteComponent() { + const { num } = Route.useParams() + + return ( +
+

Numeric Route

+

{num}

+

Type: {typeof num}

+

+ This route matched because the param is a valid number. +

+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx new file mode 100644 index 0000000000..35691a5504 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$slug.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error/$slug')({ + // No params.parse - this is the catch-all fallback + // Still has skipRouteOnParseError to participate in the competition + skipRouteOnParseError: true, + component: CatchallRouteComponent, +}) + +function CatchallRouteComponent() { + const { slug } = Route.useParams() + + return ( +
+

Catch-all Route

+

{slug}

+

+ This route matches any string that doesn't match UUID or Numeric + patterns. +

+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx new file mode 100644 index 0000000000..2f08f064d2 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/$uuid.tsx @@ -0,0 +1,33 @@ +import { createFileRoute } from '@tanstack/react-router' + +// UUID validation regex +const UUID_REGEX = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + +export const Route = createFileRoute('/skip-on-parse-error/$uuid')({ + params: { + parse: (params) => { + if (!UUID_REGEX.test(params.uuid)) { + throw new Error('Invalid UUID format') + } + return { uuid: params.uuid } + }, + stringify: (params) => ({ uuid: params.uuid }), + }, + skipRouteOnParseError: true, + component: UuidRouteComponent, +}) + +function UuidRouteComponent() { + const { uuid } = Route.useParams() + + return ( +
+

UUID Route

+

{uuid}

+

+ This route matched because the param is a valid UUID. +

+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx new file mode 100644 index 0000000000..78c825a40e --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/index.tsx @@ -0,0 +1,70 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error/')({ + component: SkipOnParseErrorIndex, +}) + +function SkipOnParseErrorIndex() { + const uuidValue = '123e4567-e89b-12d3-a456-426614174000' + const numericValue = 12345 + const stringValue = 'hello-world' + + return ( +
+

Test Links

+ +
+

UUID Route Tests

+
+ + Navigate to UUID: {uuidValue.slice(0, 8)}... + +
+
+ +
+

Numeric Route Tests

+
+ + Navigate to Numeric: {numericValue} + +
+
+ +
+

String Route Tests (Catch-all)

+
+ + Navigate to String: {stringValue} + +
+
+ +
+

+ Expected behavior: +

+
    +
  • UUID values match the UUID route (validates UUID format)
  • +
  • Numeric values match the Numeric route (validates number)
  • +
  • Other strings match the Catch-all route
  • +
+
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx new file mode 100644 index 0000000000..85aac5d1ac --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/skip-on-parse-error/route.tsx @@ -0,0 +1,20 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/skip-on-parse-error')({ + component: SkipOnParseErrorLayout, +}) + +function SkipOnParseErrorLayout() { + return ( +
+

+ Skip Route on Parse Error Tests (File-Based) +

+

+ This tests the skipRouteOnParseError feature with multiple competing + routes that have different param validators. +

+ +
+ ) +} diff --git a/e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts b/e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts new file mode 100644 index 0000000000..e49c05fe6a --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/skip-on-parse-error.spec.ts @@ -0,0 +1,180 @@ +import { expect, test } from '@playwright/test' + +test.describe('skipRouteOnParseError (file-based)', () => { + const UUID_VALUE = '123e4567-e89b-12d3-a456-426614174000' + const NUMERIC_VALUE = '12345' + const STRING_VALUE = 'hello-world' + + test.describe('direct URL navigation', () => { + test('navigating to UUID value matches UUID route', async ({ page }) => { + await page.goto(`/skip-on-parse-error/${UUID_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('navigating to numeric value matches Numeric route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${NUMERIC_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + + // Verify the param was parsed as a number + const paramType = page.getByTestId('param-type') + await expect(paramType).toHaveText('Type: number') + }) + + test('navigating to string value matches Catch-all route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${STRING_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + + test('navigating to another UUID matches UUID route', async ({ page }) => { + const anotherUuid = 'a1b2c3d4-e5f6-1234-89ab-cdef01234567' + await page.goto(`/skip-on-parse-error/${anotherUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + }) + + test('navigating to zero matches Numeric route', async ({ page }) => { + await page.goto('/skip-on-parse-error/0') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText('0') + }) + + test('navigating to negative number matches Numeric route', async ({ + page, + }) => { + // -123 parses to -123, and "-123" === "-123" check passes + await page.goto('/skip-on-parse-error/-123') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + }) + + test('navigating to float matches Catch-all route', async ({ page }) => { + // 123.45 won't match numeric because parseInt("123.45") === 123, and "123" !== "123.45" + await page.goto('/skip-on-parse-error/123.45') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + + test('navigating to UUID-like but invalid format matches Catch-all', async ({ + page, + }) => { + // Invalid UUID (wrong version digit) + const invalidUuid = '123e4567-e89b-9999-a456-426614174000' + await page.goto(`/skip-on-parse-error/${invalidUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + }) + + test.describe('client-side navigation via Link', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('clicking UUID link navigates to UUID route', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('clicking Numeric link navigates to Numeric route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-numeric') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + }) + + test('clicking String link navigates to Catch-all route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-string') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + }) + + test.describe('Link href generation', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('UUID link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${UUID_VALUE}`, + ) + }) + + test('Numeric link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-numeric') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${NUMERIC_VALUE}`, + ) + }) + + test('String link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-string') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${STRING_VALUE}`, + ) + }) + }) +}) diff --git a/e2e/react-router/basic/src/main.tsx b/e2e/react-router/basic/src/main.tsx index 36e5106654..10aeb78efe 100644 --- a/e2e/react-router/basic/src/main.tsx +++ b/e2e/react-router/basic/src/main.tsx @@ -409,6 +409,179 @@ const paramsPsWildcardSplatSuffixRoute = createRoute({ }, }) +// skipRouteOnParseError test routes +// These routes demonstrate competing routes at the same path level with different validators +const UUID_REGEX = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + +const skipOnParseErrorRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/skip-on-parse-error', + component: function SkipOnParseErrorLayout() { + return ( +
+

+ Skip Route on Parse Error Tests +

+

+ This tests the skipRouteOnParseError feature with multiple competing + routes that have different param validators. +

+ +
+ ) + }, +}) + +const skipOnParseErrorIndexRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '/', + component: function SkipOnParseErrorIndex() { + const uuidValue = '123e4567-e89b-12d3-a456-426614174000' + const numericValue = '12345' + const stringValue = 'hello-world' + + return ( +
+

Test Links

+ +
+

UUID Route Tests

+
+ + Navigate to UUID: {uuidValue.slice(0, 8)}... + +
+
+ +
+

Numeric Route Tests

+
+ + Navigate to Numeric: {numericValue} + +
+
+ +
+

String Route Tests (Catch-all)

+
+ + Navigate to String: {stringValue} + +
+
+ +
+

+ Expected behavior: +

+
    +
  • UUID values match the UUID route (validates UUID format)
  • +
  • Numeric values match the Numeric route (validates number)
  • +
  • Other strings match the Catch-all route
  • +
+
+
+ ) + }, +}) + +// UUID route - has highest priority due to skipRouteOnParseError + specific validation +const skipOnParseErrorUuidRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '$uuid', + params: { + parse: (params: { uuid: string }) => { + if (!UUID_REGEX.test(params.uuid)) { + throw new Error('Invalid UUID format') + } + return { uuid: params.uuid } + }, + stringify: (params: { uuid: string }) => ({ uuid: params.uuid }), + }, + skipRouteOnParseError: true, + component: function UuidRouteComponent() { + const { uuid } = skipOnParseErrorUuidRoute.useParams() + + return ( +
+

UUID Route

+

{uuid}

+

+ This route matched because the param is a valid UUID. +

+
+ ) + }, +}) + +// Numeric route - has priority over catch-all due to skipRouteOnParseError + validation +const skipOnParseErrorNumericRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '$num', + params: { + parse: (params: { num: string }) => { + const num = parseInt(params.num, 10) + if (isNaN(num) || num.toString() !== params.num) { + throw new Error('Invalid numeric format') + } + return { num } + }, + stringify: (params: { num: number }) => ({ num: String(params.num) }), + }, + skipRouteOnParseError: true, + component: function NumericRouteComponent() { + const { num } = skipOnParseErrorNumericRoute.useParams() + + return ( +
+

Numeric Route

+

{num}

+

Type: {typeof num}

+

+ This route matched because the param is a valid number. +

+
+ ) + }, +}) + +// Catch-all route - lowest priority, matches any string that doesn't match UUID or Numeric +const skipOnParseErrorCatchallRoute = createRoute({ + getParentRoute: () => skipOnParseErrorRoute, + path: '$slug', + component: function CatchallRouteComponent() { + const { slug } = skipOnParseErrorCatchallRoute.useParams() + + return ( +
+

Catch-all Route

+

{slug}

+

+ This route matches any string that doesn't match UUID or Numeric + patterns. +

+
+ ) + }, +}) + const routeTree = rootRoute.addChildren([ postsRoute.addChildren([postRoute, postsIndexRoute]), layoutRoute.addChildren([ @@ -429,6 +602,14 @@ const routeTree = rootRoute.addChildren([ ]), paramsPsIndexRoute, ]), + // skipRouteOnParseError routes - order matters for priority: + // UUID route (most specific validator) -> Numeric route -> Catch-all (no validator) + skipOnParseErrorRoute.addChildren([ + skipOnParseErrorIndexRoute, + skipOnParseErrorUuidRoute, + skipOnParseErrorNumericRoute, + skipOnParseErrorCatchallRoute, + ]), indexRoute, ]) diff --git a/e2e/react-router/basic/tests/skip-on-parse-error.spec.ts b/e2e/react-router/basic/tests/skip-on-parse-error.spec.ts new file mode 100644 index 0000000000..8f16a73f0f --- /dev/null +++ b/e2e/react-router/basic/tests/skip-on-parse-error.spec.ts @@ -0,0 +1,181 @@ +import { expect, test } from '@playwright/test' + +test.describe('skipRouteOnParseError', () => { + const UUID_VALUE = '123e4567-e89b-12d3-a456-426614174000' + const NUMERIC_VALUE = '12345' + const STRING_VALUE = 'hello-world' + + test.describe('direct URL navigation', () => { + test('navigating to UUID value matches UUID route', async ({ page }) => { + await page.goto(`/skip-on-parse-error/${UUID_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('navigating to numeric value matches Numeric route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${NUMERIC_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + + // Verify the param was parsed as a number + const paramType = page.getByTestId('param-type') + await expect(paramType).toHaveText('Type: number') + }) + + test('navigating to string value matches Catch-all route', async ({ + page, + }) => { + await page.goto(`/skip-on-parse-error/${STRING_VALUE}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + + test('navigating to another UUID matches UUID route', async ({ page }) => { + const anotherUuid = 'a1b2c3d4-e5f6-1234-89ab-cdef01234567' + await page.goto(`/skip-on-parse-error/${anotherUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + }) + + test('navigating to zero matches Numeric route', async ({ page }) => { + await page.goto('/skip-on-parse-error/0') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText('0') + }) + + test('navigating to negative number matches Catch-all (not valid integer parse)', async ({ + page, + }) => { + // Our numeric parser requires the string representation to match exactly + // -123 parses to -123, but "-123" !== "-123" check passes, so this should match numeric + await page.goto('/skip-on-parse-error/-123') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + }) + + test('navigating to float matches Catch-all route', async ({ page }) => { + // 123.45 won't match numeric because parseInt("123.45") === 123, and "123" !== "123.45" + await page.goto('/skip-on-parse-error/123.45') + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + + test('navigating to UUID-like but invalid format matches Catch-all', async ({ + page, + }) => { + // Invalid UUID (wrong version digit) + const invalidUuid = '123e4567-e89b-9999-a456-426614174000' + await page.goto(`/skip-on-parse-error/${invalidUuid}`) + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + }) + }) + + test.describe('client-side navigation via Link', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('clicking UUID link navigates to UUID route', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('UUID Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(UUID_VALUE) + }) + + test('clicking Numeric link navigates to Numeric route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-numeric') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Numeric Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(NUMERIC_VALUE) + }) + + test('clicking String link navigates to Catch-all route', async ({ + page, + }) => { + const link = page.getByTestId('link-to-string') + await link.click() + await page.waitForLoadState('networkidle') + + const routeType = page.getByTestId('route-type') + await expect(routeType).toHaveText('Catch-all Route') + + const paramValue = page.getByTestId('param-value') + await expect(paramValue).toHaveText(STRING_VALUE) + }) + }) + + test.describe('Link href generation', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/skip-on-parse-error') + await page.waitForLoadState('networkidle') + }) + + test('UUID link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-uuid') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${UUID_VALUE}`, + ) + }) + + test('Numeric link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-numeric') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${NUMERIC_VALUE}`, + ) + }) + + test('String link has correct href', async ({ page }) => { + const link = page.getByTestId('link-to-string') + await expect(link).toHaveAttribute( + 'href', + `/skip-on-parse-error/${STRING_VALUE}`, + ) + }) + }) +}) diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index b2eb99ab01..653241e0f3 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -709,6 +709,12 @@ type RouteMatch> = { route: T params: Record branch: ReadonlyArray + /** + * For routes with `skipRouteOnParseError`, this contains the already-parsed params + * from the parse function that was validated during matching. + * This allows `matchRoutesInternal` to avoid re-parsing these params. + */ + parsedParams?: Record } export function findRouteMatch< @@ -804,15 +810,45 @@ function findMatch( path: string, segmentTree: AnySegmentNode, fuzzy = false, -): { route: T; params: Record } | null { +): { + route: T + params: Record + parsedParams?: Record +} | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null - const [params] = extractParams(path, parts, leaf) + // Check if this was a skipRouteOnParseError route that already ran parse + const routeHadSkipParseError = + 'skipRouteOnParseError' in leaf.node && + leaf.node.skipRouteOnParseError && + 'parse' in leaf.node && + leaf.node.parse + // If skipRouteOnParseError was used, leaf.params contains the PARSED params. + // Otherwise (e.g., fuzzy matching), leaf.params may contain raw string params like '**'. + const parsedParams = routeHadSkipParseError + ? 'params' in leaf + ? leaf.params + : undefined + : undefined + // extractParams needs to run from the beginning to get raw string params. + // For fuzzy matches, we need to preserve the '**' param that was computed. + const [params] = extractParams(path, parts, { + node: leaf.node, + skipped: leaf.skipped, + // Don't pass extract state - we want to extract from the beginning + // For non-skipRouteOnParseError routes, pass through params (e.g., fuzzy '**') + params: routeHadSkipParseError + ? undefined + : 'params' in leaf + ? leaf.params + : undefined, + }) const route = leaf.node.route! return { route, params, + parsedParams, } } @@ -1011,8 +1047,9 @@ function getNodeMatch( if (node.route && !pathIsIndex && isFrameMoreSpecific(bestMatch, frame)) { bestMatch = frame } - // beyond the length of the path parts, only index segments, or skipped optional segments, or wildcard segments can match - if (!node.optional && !node.wildcard && !node.index) continue + // beyond the length of the path parts, only index segments, skipped optional segments, wildcard segments, or pathless segments can match + if (!node.optional && !node.wildcard && !node.index && !node.pathless) + continue } const part = isBeyondPath ? undefined : parts[index]! diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index ffd4de77aa..3a2773ffd5 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -701,6 +701,11 @@ export type GetMatchRoutesFn = (pathname: string) => { routeParams: Record foundRoute: AnyRoute | undefined parseError?: unknown + /** + * For routes with `skipRouteOnParseError`, this contains the already-parsed params + * from the parse function that was validated during matching. + */ + parsedParams?: Record } export type EmitFn = (routerEvent: RouterEvent) => void @@ -1249,7 +1254,7 @@ export class RouterCore< opts?: MatchRoutesOpts, ): Array { const matchedRoutesResult = this.getMatchedRoutes(next.pathname) - const { foundRoute, routeParams } = matchedRoutesResult + const { foundRoute, routeParams, parsedParams } = matchedRoutesResult let { matchedRoutes } = matchedRoutesResult let isGlobalNotFound = false @@ -1394,22 +1399,32 @@ export class RouterCore< route.options.params?.parse ?? route.options.parseParams if (strictParseParams) { - try { - Object.assign( - strictParams, - strictParseParams(strictParams as Record), - ) - } catch (err: any) { - if (isNotFound(err) || isRedirect(err)) { - paramsError = err - } else { - paramsError = new PathParamError(err.message, { - cause: err, - }) - } + // If this route used skipRouteOnParseError, the parse was already called + // during matching and the result is in parsedParams. Skip re-parsing. + const alreadyParsed = + route.options.skipRouteOnParseError && parsedParams - if (opts?.throwOnError) { - throw paramsError + if (alreadyParsed) { + // Use the pre-parsed params from the matching phase + Object.assign(strictParams, parsedParams) + } else { + try { + Object.assign( + strictParams, + strictParseParams(strictParams as Record), + ) + } catch (err: any) { + if (isNotFound(err) || isRedirect(err)) { + paramsError = err + } else { + paramsError = new PathParamError(err.message, { + cause: err, + }) + } + + if (opts?.throwOnError) { + throw paramsError + } } } } @@ -2693,15 +2708,17 @@ export function getMatchedRoutes({ const trimmedPath = trimPathRight(pathname) let foundRoute: TRouteLike | undefined = undefined + let parsedParams: Record | undefined = undefined const match = findRouteMatch(trimmedPath, processedTree, true) if (match) { foundRoute = match.route Object.assign(routeParams, match.params) // Copy params, because they're cached + parsedParams = match.parsedParams } const matchedRoutes = match?.branch || [routesById[rootRouteId]!] - return { matchedRoutes, routeParams, foundRoute } + return { matchedRoutes, routeParams, foundRoute, parsedParams } } function applySearchMiddleware({ diff --git a/packages/router-core/tests/new-process-route-tree.test.ts b/packages/router-core/tests/new-process-route-tree.test.ts index fd9ea9828d..9e724a70e2 100644 --- a/packages/router-core/tests/new-process-route-tree.test.ts +++ b/packages/router-core/tests/new-process-route-tree.test.ts @@ -1074,6 +1074,780 @@ describe('findRouteMatch', () => { `) }) }) + + describe('skipRouteOnParseError', () => { + describe('basic matching with parse validation', () => { + it('matches route when parse succeeds', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => ({ + id: parseInt(params.id!, 10), + }), + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + // params contains raw string values for interpolatePath + expect(result?.params).toEqual({ id: '123' }) + // parsedParams contains the transformed values from parse + expect(result?.parsedParams).toEqual({ id: 123 }) + }) + + it('skips route when parse throws and finds no alternative', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/abc', processedTree) + expect(result).toBeNull() + }) + + it('skips route when parse throws and finds alternative match', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + // numeric should match the validated route + const numericResult = findRouteMatch('/123', processedTree) + expect(numericResult?.route.id).toBe('/$id') + // params contains raw string values for interpolatePath + expect(numericResult?.params).toEqual({ id: '123' }) + // parsedParams contains the transformed values from parse + expect(numericResult?.parsedParams).toEqual({ id: 123 }) + + // non-numeric should fall through to the non-validated route + const slugResult = findRouteMatch('/hello-world', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + expect(slugResult?.params).toEqual({ slug: 'hello-world' }) + }) + }) + + describe('priority: validated routes take precedence', () => { + it('validated dynamic route has priority over non-validated dynamic route', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + // validated route should be tried first + const numericResult = findRouteMatch('/123', processedTree) + expect(numericResult?.route.id).toBe('/$id') + }) + + it('static route still has priority over validated dynamic route', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/settings', + fullPath: '/settings', + path: 'settings', + options: {}, + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.id!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { id: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/settings', processedTree) + expect(result?.route.id).toBe('/settings') + }) + }) + + describe('regex-like validation patterns', () => { + it('uuid validation pattern', () => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: (params: Record) => { + if (!uuidRegex.test(params.uuid!)) + throw new Error('Not a UUID') + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const uuidResult = findRouteMatch( + '/550e8400-e29b-41d4-a716-446655440000', + processedTree, + ) + expect(uuidResult?.route.id).toBe('/$uuid') + + const slugResult = findRouteMatch('/my-blog-post', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + }) + + it('date validation pattern (YYYY-MM-DD)', () => { + const dateRegex = /^\d{4}-\d{2}-\d{2}$/ + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/posts/$date', + fullPath: '/posts/$date', + path: 'posts/$date', + options: { + params: { + parse: (params: Record) => { + if (!dateRegex.test(params.date!)) + throw new Error('Not a date') + return { date: new Date(params.date!) } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/posts/$slug', + fullPath: '/posts/$slug', + path: 'posts/$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const dateResult = findRouteMatch('/posts/2024-01-15', processedTree) + expect(dateResult?.route.id).toBe('/posts/$date') + // params contains raw string values for interpolatePath + expect(dateResult?.params.date).toBe('2024-01-15') + // parsedParams contains the transformed values from parse + expect(dateResult?.parsedParams?.date).toBeInstanceOf(Date) + + const slugResult = findRouteMatch('/posts/my-first-post', processedTree) + expect(slugResult?.route.id).toBe('/posts/$slug') + }) + }) + + describe('nested routes with skipRouteOnParseError', () => { + it('parent validation failure prevents child matching', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$orgId', + fullPath: '/$orgId', + path: '$orgId', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.orgId!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { orgId: num } + }, + }, + skipRouteOnParseError: true, + }, + children: [ + { + id: '/$orgId/settings', + fullPath: '/$orgId/settings', + path: 'settings', + options: {}, + }, + ], + }, + { + id: '/$slug/about', + fullPath: '/$slug/about', + path: '$slug/about', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // numeric org should match the validated route + const numericResult = findRouteMatch('/123/settings', processedTree) + expect(numericResult?.route.id).toBe('/$orgId/settings') + + // non-numeric should not match /$orgId/settings, should match /$slug/about + const slugResult = findRouteMatch('/my-org/about', processedTree) + expect(slugResult?.route.id).toBe('/$slug/about') + }) + + it('child validation failure falls back to sibling', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/users', + fullPath: '/users', + path: 'users', + options: {}, + children: [ + { + id: '/users/$userId', + fullPath: '/users/$userId', + path: '$userId', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.userId!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { userId: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/users/$username', + fullPath: '/users/$username', + path: '$username', + options: {}, + }, + ], + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const numericResult = findRouteMatch('/users/42', processedTree) + expect(numericResult?.route.id).toBe('/users/$userId') + // params contains raw string values for interpolatePath + expect(numericResult?.params).toEqual({ userId: '42' }) + // parsedParams contains the transformed values from parse + expect(numericResult?.parsedParams).toEqual({ userId: 42 }) + + const usernameResult = findRouteMatch('/users/johndoe', processedTree) + expect(usernameResult?.route.id).toBe('/users/$username') + // Non-validated route: params are raw strings, parsedParams is undefined + expect(usernameResult?.params).toEqual({ username: 'johndoe' }) + expect(usernameResult?.parsedParams).toBeUndefined() + }) + }) + + describe('pathless routes with skipRouteOnParseError', () => { + // TODO: This test documents expected behavior that is not yet implemented + // Pathless layouts with skipRouteOnParseError should gate their children + it('pathless layout with validation gates children', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/', + fullPath: '/', + path: '/', + options: {}, + }, + { + id: '/$foo/_layout', + fullPath: '/$foo', + path: '$foo', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.foo!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { foo: num } + }, + }, + skipRouteOnParseError: true, + }, + children: [ + { + id: '/$foo/_layout/bar', + fullPath: '/$foo/bar', + path: 'bar', + options: {}, + }, + { + id: '/$foo/_layout/', + fullPath: '/$foo/', + path: '/', + options: {}, + }, + ], + }, + { + id: '/$foo/hello', + fullPath: '/$foo/hello', + path: '$foo/hello', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // numeric foo should match through the validated layout + const numericBarResult = findRouteMatch('/123/bar', processedTree) + expect(numericBarResult?.route.id).toBe('/$foo/_layout/bar') + + const numericIndexResult = findRouteMatch('/123', processedTree) + expect(numericIndexResult?.route.id).toBe('/$foo/_layout/') + expect(numericIndexResult?.params).toEqual({ foo: 123 }) + + // non-numeric foo should fall through to the non-validated route + const helloResult = findRouteMatch('/abc/hello', processedTree) + expect(helloResult?.route.id).toBe('/$foo/hello') + expect(helloResult?.params).toEqual({ foo: 'abc' }) + }) + }) + + describe('optional params with skipRouteOnParseError', () => { + it('optional param with static fallback', () => { + // Optional param with validation, with a static fallback + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/{-$lang}/home', + fullPath: '/{-$lang}/home', + path: '{-$lang}/home', + options: { + params: { + parse: (params: Record) => { + const validLangs = ['en', 'es', 'fr', 'de'] + if (params.lang && !validLangs.includes(params.lang)) { + throw new Error('Invalid language') + } + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/home', + fullPath: '/home', + path: 'home', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // valid language should match the validated route + const enResult = findRouteMatch('/en/home', processedTree) + expect(enResult?.route.id).toBe('/{-$lang}/home') + expect(enResult?.parsedParams).toEqual({ lang: 'en' }) + + // root path + home - both routes can match + // The optional route (with skipped param) has greater depth, so it wins + // This is the expected behavior per the priority system + const rootResult = findRouteMatch('/home', processedTree) + expect(rootResult?.route.id).toBe('/{-$lang}/home') + + // invalid language should NOT match the validated optional route + // and since there's no dynamic fallback, it should return null + const invalidResult = findRouteMatch('/about/home', processedTree) + expect(invalidResult).toBeNull() + }) + + it('optional param at root with validation', () => { + // Optional param that validates and allows skipping + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/{-$lang}', + fullPath: '/{-$lang}', + path: '{-$lang}', + options: { + params: { + parse: (params: Record) => { + const validLangs = ['en', 'es', 'fr', 'de'] + if (params.lang && !validLangs.includes(params.lang)) { + throw new Error('Invalid language') + } + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // valid language should match + const enResult = findRouteMatch('/en', processedTree) + expect(enResult?.route.id).toBe('/{-$lang}') + expect(enResult?.parsedParams).toEqual({ lang: 'en' }) + + // root path should match (optional skipped) + const rootResult = findRouteMatch('/', processedTree) + expect(rootResult?.route.id).toBe('/{-$lang}') + expect(rootResult?.parsedParams).toEqual({}) + + // invalid language should NOT match (no fallback route) + const invalidResult = findRouteMatch('/about', processedTree) + expect(invalidResult).toBeNull() + }) + }) + + describe('wildcard routes with skipRouteOnParseError', () => { + it('wildcard with validation', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/files/$', + fullPath: '/files/$', + path: 'files/$', + options: { + params: { + parse: (params: Record) => { + if (!params._splat!.endsWith('.txt')) { + throw new Error('Only .txt files allowed') + } + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/files', + fullPath: '/files', + path: 'files', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // .txt file should match the validated wildcard route + const txtResult = findRouteMatch( + '/files/docs/readme.txt', + processedTree, + ) + expect(txtResult?.route.id).toBe('/files/$') + + // non-.txt should fall through (fuzzy match to /files) + const otherResult = findRouteMatch( + '/files/images/photo.jpg', + processedTree, + true, + ) + expect(otherResult?.route.id).toBe('/files') + }) + }) + + describe('multiple validated routes competing', () => { + it('first matching validated route wins', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: (params: Record) => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + if (!uuidRegex.test(params.uuid!)) + throw new Error('Not a UUID') + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$number', + fullPath: '/$number', + path: '$number', + options: { + params: { + parse: (params: Record) => { + const num = parseInt(params.number!, 10) + if (isNaN(num)) throw new Error('Not a number') + return { number: num } + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + const uuidResult = findRouteMatch( + '/550e8400-e29b-41d4-a716-446655440000', + processedTree, + ) + expect(uuidResult?.route.id).toBe('/$uuid') + + const numberResult = findRouteMatch('/42', processedTree) + expect(numberResult?.route.id).toBe('/$number') + // params contains raw string values for interpolatePath + expect(numberResult?.params).toEqual({ number: '42' }) + // parsedParams contains the transformed values from parse + expect(numberResult?.parsedParams).toEqual({ number: 42 }) + + const slugResult = findRouteMatch('/hello-world', processedTree) + expect(slugResult?.route.id).toBe('/$slug') + }) + }) + + describe('params.parse without skipRouteOnParseError', () => { + it('params.parse is NOT called during matching when skipRouteOnParseError is false', () => { + let parseCalled = false + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params: Record) => { + parseCalled = true + return { id: parseInt(params.id!, 10) } + }, + }, + // skipRouteOnParseError is NOT set + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + // parse should NOT be called during matching + expect(parseCalled).toBe(false) + // params should be raw strings + expect(result?.params).toEqual({ id: '123' }) + }) + }) + + describe('edge cases', () => { + it('empty param value still goes through validation', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/prefix{$id}suffix', + fullPath: '/prefix{$id}suffix', + path: 'prefix{$id}suffix', + options: { + params: { + parse: (params: Record) => { + if (params.id === '') throw new Error('Empty not allowed') + return params + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/prefixsuffix', + fullPath: '/prefixsuffix', + path: 'prefixsuffix', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + // with value should match validated route + const withValue = findRouteMatch('/prefixFOOsuffix', processedTree) + expect(withValue?.route.id).toBe('/prefix{$id}suffix') + + // empty value should fall through to static route + const empty = findRouteMatch('/prefixsuffix', processedTree) + expect(empty?.route.id).toBe('/prefixsuffix') + }) + + it('validation error type does not matter', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: () => { + throw 'string error' // not an Error object + }, + }, + skipRouteOnParseError: true, + }, + }, + { + id: '/$fallback', + fullPath: '/$fallback', + path: '$fallback', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/test', processedTree) + expect(result?.route.id).toBe('/$fallback') + }) + }) + }) }) describe('processRouteMasks', { sequential: true }, () => {