refactor(router-core): Process routeTree into segment tree instead of flatRoutes #5722
main fromrefs/pull/5722/head·merged by Sheraff(GitHub profile, opens in a new tab) This PR rewrites processRouteTree to yield a trie-like tree of segments. This replaces
packages/router-core/src/process-route-tree.ts- parts of
packages/router-core/src/path.ts
Matching complexity now grows linearly with the number of segments (i.e. /a/b/c => 3 segments), as opposed to the previous algorithm that was correlated with the number of routes.
Goals:
- faster pre-processing at start-time
- faster matching at run-time
- more consistent priority matching
Non-goals:
- low RAM usage
Fixes https://github.com/TanStack/router/issues/5635 Fixes https://github.com/TanStack/router/issues/5674 Fixes https://github.com/TanStack/router/issues/5799
to-do:#
- fix "off-by-1" (leading/trailing
/) - implement sorting of same-type siblings at the node level (case sensitivity, prefix/suffix length)
- implement single-match ("does A match B")
- implement all-route-match ("which route does A match")
- bench pre-processing against current implementation
- bench single-match against current implementation
- bench all-route-match against current implementation
- fix not found page
- fix URL param encoding (see failing tests)
- write more tests and clean up existing tests
- document priorities and "matching logic quirks"
Bench:#
- pre-processing
- consistently >2x faster
- needle-in-a-haystack route matching
- for very small route trees: 3.5x faster
- for very large route trees: 950x faster (430 routes)
- non-matching: 90x faster (430 routes, random path "that almost matches" requested, this is a worst-case-scenario simulation)
- 1-to-1 route matching (
useMatchRoute)- for very simple routes: 1.5x slower
- for very complex routes: 1x
- resolvePath
- 2.7x faster (added a LRU cache to this, it's called a lot and is easy to cache, but function itself could be improved)
- interpolatePath
- 1.4x faster
Notes:#
- in its current implementation, 1-to-1 route matching (
useMatchRoute) does not care about therouteTree. It will match 2 arbitrary strings. This can lead to unexpected results, and is probably not the behavior we want in the long term. For now, this PR implementsfindSingleMatchto preserve that behavior, and this method is slower than the current implementation. However, when we switch to matching against the routeTree (usingfindRouteMatchinstead), it will be faster. - We use an int32 bitmask to keep track of skipped optional segments, which means that segments beyond the 32nd segment cannot be optional
- We use a UInt16Array to keep track of some indices, which also has a theoretical limit (65536 chars) but it is greater than the maximum length of URLs supported by most browsers (AFAIK, Chrome has the lowest limit, Firefox is exactly 65536, and Safari supports longer)
- the segment tree can be built in several passes (like we do for route masks, provided as a list instead of a tree), so it is compatible with a "fog of war" approach. However, the tree must be walked to re-sort siblings after a batch of modifications.
Future improvements:#
- we could consider flattening the tree branches that contain a single child at each node
- removing route-by-route case sensitivity configuration (keep global option) could yield some performance improvements
- we could take inspiration from
find-my-way(router forfastify) and use nodes that are smaller than a full pathname segment. This yields a structure close to a radix tree, which could perform better.
Summary by CodeRabbit#
Deprecations
- caseSensitive on match-route options is deprecated; use route- or router-level case sensitivity.
Breaking Changes
- Legacy path parsing/matching public APIs removed; integrations must adopt the new route-tree pipeline.
- DevTools explorer no longer exposes flatRoutes.
New Features
- New processed route-tree matcher with revamped path resolution and interpolation for more accurate matching and params.
Tests
- Added and updated tests covering the new route-tree matcher and parsing semantics.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
View your CI Pipeline Execution ↗ for commit b6570e3c3f3b9fd7cff1ecf2ff4d3f3757987541
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 6m 52s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 23s View ↗
☁️ Nx Cloud last updated this comment at
2025-11-15 12:32:53UTCMore templates
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-i18n-paraglide
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-static
- tanstack-start-bun-hosting
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-i18n-paraglide
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-streaming-data-from-server-functions
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
- tanstack-router-solid-example-authenticated-routes
- tanstack-router-solid-example-authenticated-routes-firebase
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-default-search-params
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-basic-virtual-file-based
- tanstack-router-solid-example-basic-virtual-inside-file-based
- tanstack-router-solid-example-deferred-data
- tanstack-router-solid-i18n-paraglide
- tanstack-router-solid-example-kitchen-sink
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-kitchen-sink-solid-query
- tanstack-router-solid-example-kitchen-sink-solid-query-file-based
- tanstack-router-solid-example-large-file-based
- tanstack-router-solid-example-location-masking
- tanstack-router-solid-example-navigation-blocking
- tanstack-router-solid-example-quickstart
- tanstack-router-solid-example-quickstart-esbuild-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-router-solid-example-quickstart-rspack-file-based
- tanstack-router-solid-example-quickstart-webpack-file-based
- router-solid-mono-simple
- router-solid-mono-simple-lazy
- router-solid-monorepo-solid-query
- tanstack-router-solid-example-scroll-restoration
- tanstack-solid-router-search-validator-adapters
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-auth
- tanstack-solid-start-example-basic-cloudflare
- tanstack-solid-start-example-basic-netlify
- tanstack-solid-start-example-basic-nitro
- tanstack-start-example-basic-solid-query
- tanstack-solid-start-example-basic-static
- tanstack-solid-start-bun-hosting
- tanstack-solid-start-example-convex-better-auth
- tanstack-solid-start-example-counter
- tanstack-solid-start-i18n-paraglide
- tanstack-solid-start-example-large
- tanstack-solid-start-streaming-data-from-server-functions
- tanstack-solid-start-example-supabase-basic
- tanstack-solid-start-tailwind-v4
- tanstack-router-solid-example-view-transitions
- tanstack-router-solid-example-with-framer-motion
- tanstack-router-solid-example-with-trpc
@tanstack/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5722@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5722@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5722@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5722@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5722@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5722@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5722@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5722@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5722@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5722@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5722@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5722@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5722@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5722@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5722@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5722@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5722@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5722@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5722@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5722@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5722@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5722@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5722@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@5722@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5722@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5722@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5722@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5722@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5722@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5722@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5722@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5722@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5722@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5722@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5722commit:
b6570e3- @@ -0,0 +225,21 @@225+ if (route.children) for (const child of route.children) {226+ parseSegments(data, child as TRouteLike, cursor, node, onRoute)227+ }228+}229+230+function sortDynamic(a: { prefix?: string, suffix?: string }, b: { prefix?: string, suffix?: string }) {231+ const aScore =232+ // bonus for having both prefix and suffix233+ (a.prefix && a.suffix ? 500 : 0)234+ // prefix counts double235+ + (a.prefix ? a.prefix.length * 2 : 0)236+ // suffix counts single237+ + (a.suffix ? a.suffix.length : 0)238+ const bScore =239+ // bonus for having both prefix and suffix240+ (b.prefix && b.suffix ? 500 : 0)241+ // prefix counts double242+ + (b.prefix ? b.prefix.length * 2 : 0)243+ // suffix counts single244+ + (b.suffix ? b.suffix.length : 0)245+ return bScore - aScore
fallback to alphabetical if same score
- @@ -0,0 +581,21 @@581+ continue main582+ }583+ }584+585+ // 5. Try wildcard match586+ if (node.wildcard) {587+ for (const segment of node.wildcard) {588+ const { prefix, suffix } = segment589+ if (prefix) {590+ const casePart = segment.caseSensitive ? part : part.toLowerCase()591+ if (!casePart.startsWith(prefix)) continue592+ }593+ if (suffix) {594+ const part = parts[parts.length - 1]!595+ const casePart = segment.caseSensitive ? part : part.toLowerCase()596+ if (!casePart.endsWith(suffix)) continue597+ }598+ // a wildcard match terminates the loop, but we need to continue searching in case there's a longer match599+ if (!wildcardMatch || (wildcardMatch.index < index)) {600+ wildcardMatch = { node: segment, index, skipped, depth }601+ }
score should be on
DynamicNode, used in sort above, and in here if both indices are equal. - @@ -0,0 +230,21 @@230+ }231+ if (route.children) for (const child of route.children) {232+ parseSegments(data, child as TRouteLike, cursor, node, depth, onRoute)233+ }234+}235+236+function sortDynamic(a: { prefix?: string, suffix?: string }, b: { prefix?: string, suffix?: string }) {237+ if (a.prefix && b.prefix && a.prefix !== b.prefix) {238+ if (a.prefix.startsWith(b.prefix)) return -1239+ if (b.prefix.startsWith(a.prefix)) return 1240+ }241+ if (a.suffix && b.suffix && a.suffix !== b.suffix) {242+ if (a.suffix.endsWith(b.suffix)) return -1243+ if (b.suffix.endsWith(a.suffix)) return 1244+ }245+ if (a.prefix && !b.prefix) return -1246+ if (!a.prefix && b.prefix) return 1247+ if (a.suffix && !b.suffix) return -1248+ if (!a.suffix && b.suffix) return 1249+ return 0250+}
should rank case-sensitive routes w/ prefix/suffix higher than case-insensitive ones
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-devtools-core
github-actions[bot](GitHub profile, opens in a new tab) added labelsdocumentation
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-server-core
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/router-core/tests/optional-path-params.test.ts (1)
7-7: Type safety reduced in skipped tests.The change from
Array<PathSegment>toArray<any>loses type safety. Since these tests are skipped for the WIP phase, this is acceptable, but if these tests are migrated later, restore proper typing.Also applies to: 11-11
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 54042014c5a7fbde2456657ce18b61b9c3231dd0 and 56808aa2e42335c5ea3621401a5e3ae5b6e90058.
📒 Files selected for processing (15)
docs/router/framework/react/api/router/MatchRouteOptionsType.md(2 hunks)packages/react-router/src/index.tsx(0 hunks)packages/router-core/src/Matches.ts(1 hunks)packages/router-core/src/Untitled-1.md(1 hunks)packages/router-core/src/index.ts(0 hunks)packages/router-core/src/new-process-route-tree.ts(1 hunks)packages/router-core/src/path.ts(4 hunks)packages/router-core/src/process-route-tree.ts(0 hunks)packages/router-core/src/router.ts(11 hunks)packages/router-core/tests/match-by-path.test.ts(3 hunks)packages/router-core/tests/new-process-route-tree.test.ts(1 hunks)packages/router-core/tests/optional-path-params-clean.test.ts(2 hunks)packages/router-core/tests/optional-path-params.test.ts(1 hunks)packages/router-core/tests/path.test.ts(2 hunks)packages/solid-router/src/index.tsx(0 hunks)
💤 Files with no reviewable changes (4)
- packages/solid-router/src/index.tsx
- packages/router-core/src/process-route-tree.ts
- packages/router-core/src/index.ts
- packages/react-router/src/index.tsx
🧰 Additional context used
📓 Path-based instructions (4)
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/Untitled-1.mdpackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/Matches.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/tests/new-process-route-tree.test.tspackages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/Matches.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
docs/**/*.{md,mdx}
📄 CodeRabbit inference engine (AGENTS.md)
Use internal docs links relative to the docs/ folder (e.g., ./guide/data-loading)
Files:
docs/router/framework/react/api/router/MatchRouteOptionsType.md
docs/{router,start}/**
📄 CodeRabbit inference engine (AGENTS.md)
Place router docs under docs/router/ and start framework docs under docs/start/
Files:
docs/router/framework/react/api/router/MatchRouteOptionsType.md
🧠 Learnings (13)
📓 Common learnings
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Applied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/Matches.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/tests/new-process-route-tree.test.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directoriesApplied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{react-router,solid-router}/** : Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/Applied to files:
packages/router-core/src/Untitled-1.md
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/tests/path.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to docs/{router,start}/** : Place router docs under docs/router/ and start framework docs under docs/start/Applied to files:
packages/router-core/src/Untitled-1.md
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/src/path.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/src/Untitled-1.mdpackages/router-core/src/path.ts
📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.Applied to files:
packages/router-core/tests/new-process-route-tree.test.tsdocs/router/framework/react/api/router/MatchRouteOptionsType.mdpackages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/tests/optional-path-params-clean.test.ts
📚 Learning: 2025-10-09T12:59:02.129Z
Learnt from: hokkyss Repo: TanStack/router PR: 5418 File: e2e/react-start/custom-identifier-prefix/src/styles/app.css:19-21 Timestamp: 2025-10-09T12:59:02.129Z Learning: In e2e test directories (paths containing `e2e/`), accessibility concerns like outline suppression patterns are less critical since the code is for testing purposes, not production use.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/tests/optional-path-params-clean.test.ts
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/path.tspackages/router-core/src/router.ts
🧬 Code graph analysis (4)
packages/router-core/tests/new-process-route-tree.test.ts (1)
packages/router-core/src/new-process-route-tree.ts (3)
processFlatRouteList(404-414)processRouteTree(475-528)findRouteMatch(454-463)
packages/router-core/src/path.ts (3)
packages/router-core/src/utils.ts (1)
last(191-193)
packages/router-core/src/new-process-route-tree.ts (6)
parseSegment(23-115)SegmentKind(8-8)SEGMENT_TYPE_PATHNAME(3-3)SEGMENT_TYPE_PARAM(4-4)SEGMENT_TYPE_WILDCARD(5-5)SEGMENT_TYPE_OPTIONAL_PARAM(6-6)
packages/router-generator/src/utils.ts (1)
cleanPath(38-41)
packages/router-core/src/new-process-route-tree.ts (2)
packages/router-core/src/route.ts (3)
path(1551-1553)RouteLike(1968-1979)fullPath(1555-1557)
packages/router-core/src/path.ts (1)
trimPathRight(32-34)
packages/router-core/src/router.ts (3)
packages/router-core/src/new-process-route-tree.ts (6)
ProcessedTree(391-402)processRouteTree(475-528)findFlatMatch(419-435)findSingleMatch(440-452)trimPathRight(467-469)findRouteMatch(454-463)
packages/router-core/src/route.ts (1)
RouteMask(1466-1475)
packages/router-core/src/utils.ts (1)
deepEqual(333-387)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Test
🔇 Additional comments (7)
packages/router-core/src/Matches.ts (1)
275-277: LGTM—Clear deprecation notice.The deprecation message provides clear guidance to configure case sensitivity at the route or router level instead of per-match options, aligning with the PR's move to route-tree-based configuration.
packages/router-core/tests/match-by-path.test.ts (1)
3-3: Skipped tests acceptable for WIP.The test suites are appropriately skipped as part of the API migration. Before merging, these tests should either be migrated to the new
processedTree-based API or removed if the functionality is covered bynew-process-route-tree.test.ts.Do you plan to migrate these test scenarios to the new API, or is the coverage in
new-process-route-tree.test.tssufficient?Also applies to: 78-78, 138-138
packages/router-core/tests/path.test.ts (1)
496-496: Skipped tests align with API migration.These test suites for
matchPathnameandparsePathnameare appropriately skipped as these utilities are being replaced by the new route-tree processing approach.Also applies to: 722-722
docs/router/framework/react/api/router/MatchRouteOptionsType.md (1)
11-11: Documentation properly reflects API deprecation.The documentation updates clearly communicate the deprecation of
caseSensitiveand guide users to configure case sensitivity at the route or router level instead.Also applies to: 27-27, 32-32
packages/router-core/tests/optional-path-params-clean.test.ts (1)
8-8: Selective test skipping appropriate for migration.Good approach to skip only the
parsePathnameandmatchPathnametests while keepinginterpolatePathtests active, as interpolation logic remains relevant in the new API.Also applies to: 96-96
packages/router-core/tests/optional-path-params.test.ts (1)
5-5: Import update shows new module location.The segment type constants have been moved to
new-process-route-tree.ts, establishing the new home for route processing types.packages/router-core/tests/new-process-route-tree.test.ts (1)
1-428: Comprehensive test coverage for new route processing API.The test suite provides excellent coverage of the new
processRouteTreeandfindRouteMatchfunctions, including:- Static and dynamic segments
- Optional parameters with prefix/suffix
- Wildcard routes
- Fuzzy matching
- Edge cases like multiple params at the same level
The use of inline snapshots is well-suited for this WIP phase, making it easy to review the new matching behavior.
@@ -0,0 +431,21 @@431+ tree = processFlatRouteList(list)432+ processedTree.flatCache.set(list, tree)433+ }434+ return findMatch(path, tree)435+}436+437+/**438+ * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree439+ */440+export function findSingleMatch(from: string, caseSensitive: boolean, fuzzy: boolean, path: string, processedTree: ProcessedTree<any, any, { from: string }>) {441+ const key = `${caseSensitive}|${from}`442+ let tree = processedTree.singleCache.get(key)443+ if (!tree) {444+ // single flat routes (router.matchRoute) are not eagerly processed,445+ // if we haven't seen this route before, process it now446+ tree = createStaticNode<{ from: string }>('/')447+ const data = new Uint16Array(6)448+ parseSegments(false, data, { from }, 1, tree, 1)449+ processedTree.singleCache.set(key, tree)450+ }451+ return findMatch(path, tree, fuzzy)⚠️ Potential issue | 🟠 Major
Case-sensitive matches never honor the flag.
findSingleMatchalways feedsfalseintoparseSegments, so the cached tree is built with case-insensitive semantics even when callers requestcaseSensitive: true. That regressesrouter.matchRoute({ caseSensitive: true }), because static segments are lowercased and keep matching regardless of case. Pass the caller’s flag through when materialising the temporary tree.- parseSegments(false, data, { from }, 1, tree, 1) + parseSegments(caseSensitive, data, { from }, 1, tree, 1)🤖 Prompt for AI Agents
In packages/router-core/src/new-process-route-tree.ts around lines 440 to 451, the temporary tree for single-route matching is always built with case-insensitive semantics because parseSegments is called with a hardcoded false; change that call to pass the incoming caseSensitive parameter so the cached tree is materialised with the correct case handling (i.e., replace the false argument with caseSensitive) so callers of findSingleMatch(caseSensitive: true, ...) get case-sensitive behaviour.✅ Addressed in commit 58baf3e
@@ -371,0 +159,21 @@159+ for (let i = 0; i < baseSegments.length; i++) {160+ if (i > 0) joined += '/'161+ const segment = baseSegments[i]!162+ if (!segment) continue163+ parseSegment(segment, 0, data)164+ const kind = data[0] as SegmentKind165+ if (kind === SEGMENT_TYPE_PATHNAME) {166+ joined += segment167+ continue168+ }169+ const end = data[5]!170+ const prefix = segment.substring(0, data[1])171+ const suffix = segment.substring(data[4]!, end)172+ const value = segment.substring(data[2]!, data[3])173+ if (kind === SEGMENT_TYPE_PARAM) {174+ joined += prefix || suffix ? `${prefix}{$${value}}${suffix}` : `$${value}`175+ } else if (kind === SEGMENT_TYPE_WILDCARD) {176+ joined += prefix || suffix ? `${prefix}{$}${suffix}` : '$'177+ } else { // SEGMENT_TYPE_OPTIONAL_PARAM178+ joined += `${prefix}{-$${value}}${suffix}`179+ }⚠️ Potential issue | 🔴 Critical
Optional-param segments serialize to invalid strings.
When
prefix/suffixare absent we now emit the literal text"undefined{-$…}undefined", and the template itself becomes{-$$param}. Both issues corrupt the placeholder, so optional params can no longer be matched or interpolated (the regex reads the param name as$param). Please normalise the prefix/suffix to empty strings and rebuild the fragment without inserting a second dollar sign.- } else { // SEGMENT_TYPE_OPTIONAL_PARAM - joined += `${prefix}{-$${value}}${suffix}` - } + } else { // SEGMENT_TYPE_OPTIONAL_PARAM + const safePrefix = prefix ?? '' + const safeSuffix = suffix ?? '' + joined += safePrefix + '{-$' + value + '}' + safeSuffix + }🤖 Prompt for AI Agents
In packages/router-core/src/path.ts around lines 173 to 179, normalize prefix and suffix to empty strings (e.g. const p = prefix || '' and const s = suffix || '') before building fragments, and change the optional-param branch to use those normalized values and a single dollar token for the param so the fragment is built like: p + '{-' + '$' + value + '}' + s (i.e. `${p}{-$${value}}${s}`) — this prevents "undefined" being injected and avoids inserting a second dollar sign.@@ -0,0 +38,21 @@38+- optional dynamic segments ('{-$userId}' => { userId: '123' } or { })39+- wildcard segments ('$' => { '*': 'some/long/path' })40+41+When the app is live, we need 2 abilities:42+- know whether a path matches a specific route (i.e. match(route: Route, path: string): Params | false)43+- find which route (if any) is matching a given path (i.e. findRoute(path: string): {route: Route, params: Params} | null)44+45+To optimize these operations, we pre-process the route tree. Both pre-processing and matching should be highly performant in the browser.46+</routing-requirements>47+48+<some-details>49+- scale: we expect to have between 2 and 2000 routes (approximately)50+- all routes are known at app start time, no dynamic route addition/removal51+- memory is not an issue, don't hesitate to use more memory to gain speed52+- routes can be nested from 1 to 10 levels deep (approximately)53+- we have no preference for certain patterns, we are open to rewriting everything54+- matching must be deterministic55+- we always favor a more specific route over a less specific one (e.g. /users/123/profile over /users/$userId/$)56+- each segment can be case sensitive or case insensitive, it can be different for each segment. We know this at pre-processing time.57+- we cannot pre-process at build time, all pre-processing must happen at app start time in the browser58+</some-details>🛠️ Refactor suggestion | 🟠 Major
Relocate design document and use descriptive filename.
This design specification document should be moved out of
packages/router-core/src/to a more appropriate location likedocs/router/design/or a top-leveldesign/folder. Additionally, rename fromUntitled-1.mdto something descriptive likesegment-tree-design.mdorroute-matching-architecture.md.The
src/directory should contain only source code, not design documentation.🤖 Prompt for AI Agents
packages/router-core/src/Untitled-1.md lines 1-58: This design doc lives in src/ and has a non-descriptive name; move it to a docs location (e.g. docs/router/design/segment-tree-design.md or design/route-matching-architecture.md), commit using git mv to preserve history, update any README or other doc indexes/links that referenced the old path, and remove it from the package's build/source exports so src/ contains only code.Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/router-core/tests/optional-path-params-clean.test.ts (1)
6-138: Remove references to deleted helpers in skipped suites.After dropping
parsePathname/matchPathnamefrom the public API, this test file no longer imports them, yet the bodies still reference the symbols. TypeScript errors out even though the suites are skipped. Please delete or stub these blocks so the file compiles.Apply this diff:
- describe.skip('parsePathname', () => { - it('should parse single optional dynamic param', () => { - const result = parsePathname('/posts/{-$category}') - expect(result).toEqual([ - { type: SEGMENT_TYPE_PATHNAME, value: '/' }, - { type: SEGMENT_TYPE_PATHNAME, value: 'posts' }, - { type: SEGMENT_TYPE_OPTIONAL_PARAM, value: '$category' }, - ]) - }) - … - }) + describe.skip('parsePathname', () => { + // Removed along with parsePathname export; keeping the suite placeholder + // avoids reintroducing the dependency while preserving history. + }) @@ - describe.skip('matchPathname', () => { - it('should match optional dynamic params when present', () => { - const result = matchPathname('/posts/tech', { - to: '/posts/{-$category}', - }) - expect(result).toEqual({ category: 'tech' }) - }) - … - }) + describe.skip('matchPathname', () => { + // Placeholder; original tests referenced removed matchPathname helper. + })packages/router-core/src/router.ts (1)
2617-2647: Update test file to use newgetMatchedRoutesAPI signature.The test in
packages/router-core/tests/processRouteTree.test.ts(lines 286-302) callsgetMatchedRouteswith an outdated API signature. The function now accepts{ pathname, routesById, processedTree }instead of{ pathname, caseSensitive, routesByPath, routesById, flatRoutes }.Update the test call to pass
processedTreefrom theprocessRouteTreeresult instead of the removed parameters. Additionally, note that thecaseSensitiveoption is no longer configurable at the function level—getMatchedRoutesnow always uses fuzzy matching (enabled at line 2630), which is intentional for server-side routing scenarios.♻️ Duplicate comments (3)
packages/react-router/src/useBlocker.tsx (1)
180-180: API signature change mirrors solid-router implementation.This change is identical to the one in
packages/solid-router/src/useBlocker.tsxat line 189, appropriately maintaining consistency across framework bindings.packages/router-core/src/new-process-route-tree.ts (1)
540-546: Honor caseSensitive when caching single-route trees.findSingleMatchstill hardcodesfalse, so any caller asking for a case-sensitive match gets a lowercased cache and the route keeps matching insensitive. This regressesrouter.matchRoute({ caseSensitive: true }).Apply this diff:
- parseSegments(false, data, { from }, 1, tree, 1) + parseSegments(caseSensitive, data, { from }, 1, tree, 1)packages/router-core/src/path.ts (1)
171-186: Optional param serialization now emits{−$$param}.Switching to the new segment parser is great, but this branch now injects a second
$, so{-$id}becomes{−$$id}and prefixes/suffixes get the string"undefined"when absent. The generated template can’t be re-parsed or matched.Apply this diff:
- const prefix = segment.substring(0, data[1]) - const suffix = segment.substring(data[4]!, end) + const prefix = segment.substring(0, data[1]) + const suffix = segment.substring(data[4]!, end) @@ - joined += `${prefix}{-$${value}}${suffix}` + const safePrefix = prefix ?? '' + const safeSuffix = suffix ?? '' + joined += safePrefix + '{-$' + value + '}' + safeSuffix🧹 Nitpick comments (1)
packages/router-core/src/router.ts (1)
904-904: Consider improving type safety forprocessedTreegeneric parameters.The
processedTreeproperty usesanyfor the second and third generic parameters (TFlatandTSingle), which reduces type safety. While this may be acceptable for the initial refactor (given the PR is marked WIP), consider whether these can be properly typed based on the route tree structure.If the flat and single route types can be derived from
TRouteTree, consider updating the type to:-processedTree!: ProcessedTree<TRouteTree, any, any> +processedTree!: ProcessedTree<TRouteTree, RouteMask<TRouteTree>, { from: string }>Or introduce helper types if the proper types can be inferred from the route tree.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 56808aa2e42335c5ea3621401a5e3ae5b6e90058 and 162a3d75960e80379377e0b4b979699ba55212fd.
📒 Files selected for processing (10)
packages/react-router/src/useBlocker.tsx(1 hunks)packages/router-core/src/Matches.ts(1 hunks)packages/router-core/src/new-process-route-tree.ts(1 hunks)packages/router-core/src/path.ts(4 hunks)packages/router-core/src/router.ts(10 hunks)packages/router-core/tests/new-process-route-tree.test.ts(1 hunks)packages/router-core/tests/optional-path-params-clean.test.ts(2 hunks)packages/router-core/tests/optional-path-params.test.ts(1 hunks)packages/solid-router/src/useBlocker.tsx(1 hunks)packages/start-server-core/src/createStartHandler.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/router-core/src/Matches.ts
- packages/router-core/tests/optional-path-params.test.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/solid-router/src/useBlocker.tsxpackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/start-server-core/src/createStartHandler.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/react-router/src/useBlocker.tsxpackages/router-core/src/new-process-route-tree.ts
packages/{react-router,solid-router}/**
📄 CodeRabbit inference engine (AGENTS.md)
Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/
Files:
packages/solid-router/src/useBlocker.tsxpackages/react-router/src/useBlocker.tsx
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/src/new-process-route-tree.ts
packages/{*-start,start-*}/**
📄 CodeRabbit inference engine (AGENTS.md)
Name and place Start framework packages under packages/-start/ or packages/start-/
Files:
packages/start-server-core/src/createStartHandler.ts
🧠 Learnings (14)
📓 Common learnings
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directories📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/solid-router/src/useBlocker.tsxpackages/router-core/tests/optional-path-params-clean.test.tspackages/start-server-core/src/createStartHandler.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/react-router/src/useBlocker.tsxpackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{react-router,solid-router}/** : Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/Applied to files:
packages/solid-router/src/useBlocker.tsxpackages/react-router/src/useBlocker.tsx
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Applied to files:
packages/solid-router/src/useBlocker.tsxpackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/start-server-core/src/createStartHandler.tspackages/router-core/src/router.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-09T12:59:02.129Z
Learnt from: hokkyss Repo: TanStack/router PR: 5418 File: e2e/react-start/custom-identifier-prefix/src/styles/app.css:19-21 Timestamp: 2025-10-09T12:59:02.129Z Learning: In e2e test directories (paths containing `e2e/`), accessibility concerns like outline suppression patterns are less critical since the code is for testing purposes, not production use.Applied to files:
packages/router-core/tests/optional-path-params-clean.test.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directoriesApplied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/router.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/router.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.Applied to files:
packages/router-core/tests/new-process-route-tree.test.ts
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
packages/router-core/tests/new-process-route-tree.test.tspackages/start-server-core/src/createStartHandler.tspackages/router-core/src/path.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to docs/{router,start}/** : Place router docs under docs/router/ and start framework docs under docs/start/Applied to files:
packages/start-server-core/src/createStartHandler.ts
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-devtools,*-router-devtools}/** : Keep router devtools packages in packages/router-devtools/ and packages/*-router-devtools/Applied to files:
packages/router-core/src/router.ts
🧬 Code graph analysis (4)
packages/router-core/tests/new-process-route-tree.test.ts (1)
packages/router-core/src/new-process-route-tree.ts (3)
processFlatRouteList(494-504)processRouteTree(572-632)findRouteMatch(550-561)
packages/router-core/src/path.ts (3)
packages/router-core/src/utils.ts (1)
last(191-193)
packages/router-core/src/new-process-route-tree.ts (6)
parseSegment(29-122)SegmentKind(8-12)SEGMENT_TYPE_PATHNAME(3-3)SEGMENT_TYPE_PARAM(4-4)SEGMENT_TYPE_WILDCARD(5-5)SEGMENT_TYPE_OPTIONAL_PARAM(6-6)
packages/router-generator/src/utils.ts (1)
cleanPath(38-41)
packages/router-core/src/router.ts (3)
packages/router-core/src/new-process-route-tree.ts (6)
ProcessedTree(481-492)processRouteTree(572-632)findFlatMatch(509-525)findSingleMatch(530-548)trimPathRight(564-566)findRouteMatch(550-561)
packages/router-core/src/route.ts (1)
RouteMask(1466-1475)
packages/router-core/src/utils.ts (1)
deepEqual(333-387)
packages/router-core/src/new-process-route-tree.ts (2)
packages/router-core/src/route.ts (3)
path(1551-1553)RouteLike(1968-1979)fullPath(1555-1557)
packages/router-core/src/path.ts (1)
trimPathRight(38-40)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Test
🔇 Additional comments (6)
packages/solid-router/src/useBlocker.tsx (1)
189-189: API signature change is complete and consistent across the codebase.The
GetMatchRoutesFntype definition atpackages/router-core/src/router.ts:697already enforces a single-argument signature:(pathname: string) => { ... }. All 7 callers across the codebase already use this pattern with no two-argument calls present. The change at line 189 inuseBlocker.tsxis fully consistent with the existing router-core API and requires no further updates.packages/router-core/src/router.ts (5)
1095-1118: LGTM!The
buildRouteTreemethod has been correctly updated to use the newprocessRouteTreeAPI, storing the result inprocessedTreeinstead offlatRoutes. The destructuring and assignment are consistent with the new architecture.
1536-1542: LGTM!The
getMatchedRoutesmethod has been correctly updated to match the newGetMatchRoutesFnsignature, passing onlypathnameand delegating to the helper function withprocessedTree.
2499-2524: LGTM with a note on parameter semantics.The
matchRoutemethod has been correctly updated to usefindSingleMatchfrom the new API. The logic for comparing params and search is preserved.Note: The
findSingleMatchparameter names (from,path) may be a bit unintuitive here -fromreceives the route pattern (next.pathname) andpathreceives the location to test against (baseLocation.pathname). This is semantically correct for the matchRoute use case but worth documenting if not already clear in the function's JSDoc.
1773-1789: No issues found — the return type structure is correct.The
findFlatMatchfunction returns{ route: T; params: Record<string, string> } | null(as confirmed by its delegation tofindMatchat line 524 ofnew-process-route-tree.ts), and the usage in router.ts lines 1780-1781 correctly accessesmatch.paramsandmatch.routeafter the null check on line 1779.
697-701: All callers properly updated for the new GetMatchRoutesFn signature.Verification confirms the signature simplification from
(pathname, routePathname)to(pathname)is complete and consistent across the codebase. All five call sites (start-server-core, solid-router, react-router, and internal router usage) have been updated and correctly destructure the return value{ matchedRoutes, foundRoute, routeParams }. No legacy calls with two parameters remain.@@ -0,0 +174,21 @@174+ if (existingNode) {175+ nextNode = existingNode176+ } else {177+ node.staticInsensitive ??= new Map()178+ const next = createStaticNode<TRouteLike>(179+ route.fullPath ?? route.from,180+ )181+ next.parent = node182+ next.depth = ++depth183+ nextNode = next184+ node.staticInsensitive.set(name, next)185+ }186+ }187+ break188+ }189+ case SEGMENT_TYPE_PARAM: {190+ const prefix_raw = path.substring(start, data[1])191+ const suffix_raw = path.substring(data[4]!, end)192+ const prefix = !prefix_raw193+ ? undefined194+ : caseSensitive⚠️ Potential issue | 🔴 Critical
Fix depth propagation when reusing existing nodes.
When the loop hits an existing child (static or dynamic),
depthnever advances to the child’s actual depth. The next sibling therefore reuses a stale value, so newly created nodes getdepth = 1even when they live several levels down. That breaksbuildBranch/extractParamsfor any route that shares a prefix (e.g./foo/barfollowed by/foo/baz), because the branch array loses intermediate segments and optional-param bit masks no longer line up. Please set the new node’s depth from its parent and resynchronisedepthfor both new and existing nodes.Apply this diff:
@@ - next.parent = node - next.depth = ++depth + next.parent = node + next.depth = node.depth + 1 @@ - next.parent = node - next.depth = ++depth + next.parent = node + next.depth = node.depth + 1 @@ - next.parent = node - next.depth = ++depth + next.parent = node + next.depth = node.depth + 1 @@ - next.parent = node - next.depth = ++depth + next.parent = node + next.depth = node.depth + 1 @@ - node = nextNode + node = nextNode + depth = node.depthCommittable suggestion skipped: line range outside the PR's diff.
Actionable comments posted: 3
♻️ Duplicate comments (1)
packages/router-core/src/new-process-route-tree.ts (1)
147-290: Fix depth propagation bug when reusing existing nodes.The depth tracking breaks when the loop reuses an existing node (lines 158-160, 173-175, 202-209, 239-246). When
nextNodepoints to an existing node, the localdepthvariable is never synchronized withnextNode.depth, so subsequent iterations compute incorrect depths for newly created nodes. This corrupts thebuildBrancharray (line 716), causingextractParamsto misalign parameter extraction.Apply this diff to fix depth propagation:
if (existingNode) { nextNode = existingNode } else { node.static ??= new Map() const next = createStaticNode<TRouteLike>( route.fullPath ?? route.from, ) next.parent = node - next.depth = ++depth + next.depth = node.depth + 1 nextNode = next node.static.set(value, next) }if (existingNode) { nextNode = existingNode } else { node.staticInsensitive ??= new Map() const next = createStaticNode<TRouteLike>( route.fullPath ?? route.from, ) next.parent = node - next.depth = ++depth + next.depth = node.depth + 1 nextNode = next node.staticInsensitive.set(name, next) }} else { const next = createDynamicNode<TRouteLike>( SEGMENT_TYPE_PARAM, route.fullPath ?? route.from, caseSensitive, prefix, suffix, ) nextNode = next - next.depth = ++depth + next.depth = node.depth + 1 next.parent = node node.dynamic ??= [] node.dynamic.push(next) }} else { const next = createDynamicNode<TRouteLike>( SEGMENT_TYPE_OPTIONAL_PARAM, route.fullPath ?? route.from, caseSensitive, prefix, suffix, ) nextNode = next next.parent = node - next.depth = ++depth + next.depth = node.depth + 1 node.optional ??= [] node.optional.push(next) }) nextNode = next next.parent = node - next.depth = ++depth + next.depth = node.depth + 1 node.wildcard ??= [] node.wildcard.push(next) } } node = nextNode + depth = node.depth }🧹 Nitpick comments (2)
packages/router-core/src/new-process-route-tree.ts (2)
309-326: Add case-sensitivity and alphabetical fallback to sort criteria.The current comparator doesn't distinguish case-sensitive from case-insensitive routes, nor does it provide an alphabetical fallback for stable sorting when prefix/suffix scores are equal. Past review comments flagged these omissions. Case-sensitive routes should rank higher, and ties should break alphabetically.
Apply this diff to add the missing criteria:
function sortDynamic( - a: { prefix?: string; suffix?: string }, - b: { prefix?: string; suffix?: string }, + a: { prefix?: string; suffix?: string; caseSensitive?: boolean; fullPath: string }, + b: { prefix?: string; suffix?: string; caseSensitive?: boolean; fullPath: string }, ) { 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 } if (a.suffix && b.suffix && a.suffix !== b.suffix) { if (a.suffix.endsWith(b.suffix)) return -1 if (b.suffix.endsWith(a.suffix)) return 1 } if (a.prefix && !b.prefix) return -1 if (!a.prefix && b.prefix) return 1 if (a.suffix && !b.suffix) return -1 if (!a.suffix && b.suffix) return 1 + if (a.caseSensitive && !b.caseSensitive) return -1 + if (!a.caseSensitive && b.caseSensitive) return 1 + return a.fullPath.localeCompare(b.fullPath) - return 0 }Based on learnings
693-693: Document bitmask limitation for optional parameters.The bitmask approach (lines 693, 793) limits the implementation to approximately 31 optional parameters per path, since JavaScript bitwise operations are 32-bit signed. For most use cases this is sufficient, but worth documenting as a constraint.
Add a comment documenting the constraint:
// Optional dynamic segments ({-$param}) + // Note: Bitmask approach limits the implementation to ~31 optional params per path optional: Array<DynamicSegmentNode<T>> | nullAlso applies to: 793-793
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 162a3d75960e80379377e0b4b979699ba55212fd and 58baf3e8158874b96a05f0b8598881e35cd76124.
📒 Files selected for processing (2)
packages/router-core/src/new-process-route-tree.ts(1 hunks)packages/solid-router/src/index.tsx(0 hunks)
💤 Files with no reviewable changes (1)
- packages/solid-router/src/index.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/src/new-process-route-tree.ts
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/new-process-route-tree.ts
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directories📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directoriesApplied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/src/new-process-route-tree.ts
🧬 Code graph analysis (1)
packages/router-core/src/new-process-route-tree.ts (2)
packages/router-core/src/route.ts (3)
path(1551-1553)RouteLike(1968-1979)fullPath(1555-1557)
packages/router-core/src/path.ts (1)
trimPathRight(38-40)
🔇 Additional comments (3)
packages/router-core/src/new-process-route-tree.ts (3)
29-122: LGTM: Clean segment parsing with appropriate fallback.The function correctly handles all segment types (static, wildcard, param, optional param) with early returns for common cases. The defensive fallback at lines 115-122 is appropriate even though it should theoretically never be reached.
359-492: LGTM: Well-structured types and factory functions.The node factories correctly initialize all fields, and the comment at lines 377-379 about key ordering for V8 optimization is a good practice. Type definitions are comprehensive and properly discriminated.
572-632: LGTM: Correct route tree processing with proper validation.The function correctly initializes depth at 0, validates for duplicate route IDs with
invariant, and maintains both ID and path lookup maps. The trailing-slash preference at line 613 is reasonable for route resolution.@@ -0,0 +484,21 @@484+ TSingle extends Extract<RouteLike, { from: string }>,485+> = {486+ /** a representation of the `routeTree` as a segment tree, for performant path matching */487+ segmentTree: AnySegmentNode<TTree>488+ /** a cache of mini route trees generated from flat route lists, for performant route mask matching */489+ flatCache: Map<any, AnySegmentNode<TFlat>>490+ /** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */491+ singleCache: Map<any, AnySegmentNode<TSingle>>492+}493+494+export function processFlatRouteList<TRouteLike extends RouteLike>(495+ routeList: Array<TRouteLike>,496+) {497+ const segmentTree = createStaticNode<TRouteLike>('/')498+ const data = new Uint16Array(6)499+ for (const route of routeList) {500+ parseSegments(false, data, route, 1, segmentTree, 1)501+ }502+ sortTreeNodes(segmentTree)503+ return segmentTree504+}⚠️ Potential issue | 🟠 Major
Fix inconsistent depth initialization in processFlatRouteList.
Line 500 initializes depth at
1, butprocessRouteTree(line 600) uses0for the same parameter. The root node should be at depth 0. This inconsistency causes the depth values in flat route trees to be offset by 1, breakingbuildBranchwhen mixing flat and tree routes.Apply this diff:
const segmentTree = createStaticNode<TRouteLike>('/') const data = new Uint16Array(6) for (const route of routeList) { - parseSegments(false, data, route, 1, segmentTree, 1) + parseSegments(false, data, route, 1, segmentTree, 0) } sortTreeNodes(segmentTree) return segmentTree📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export function processFlatRouteList<TRouteLike extends RouteLike>( routeList: Array<TRouteLike>, ) { const segmentTree = createStaticNode<TRouteLike>('/') const data = new Uint16Array(6) for (const route of routeList) { parseSegments(false, data, route, 1, segmentTree, 0) } sortTreeNodes(segmentTree) return segmentTree }🤖 Prompt for AI Agents
In packages/router-core/src/new-process-route-tree.ts around lines 494 to 504, the loop calls parseSegments with an initial depth of 1 which is inconsistent with processRouteTree (which uses depth 0) and causes root depth to be offset; change the call to parseSegments to pass depth 0 (i.e., replace the trailing 1 with 0) so flat route trees use the same root depth as tree routes, then run tests/build to confirm buildBranch mixing flat and tree routes behaves correctly.Resolvedby Sheraff(GitHub profile, opens in a new tab)@@ -0,0 +528,21 @@528+ * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree529+ */530+export function findSingleMatch(531+ from: string,532+ caseSensitive: boolean,533+ fuzzy: boolean,534+ path: string,535+ processedTree: ProcessedTree<any, any, { from: string }>,536+) {537+ const key = `${caseSensitive}|${from}`538+ let tree = processedTree.singleCache.get(key)539+ if (!tree) {540+ // single flat routes (router.matchRoute) are not eagerly processed,541+ // if we haven't seen this route before, process it now542+ tree = createStaticNode<{ from: string }>('/')543+ const data = new Uint16Array(6)544+ parseSegments(caseSensitive, data, { from }, 1, tree, 1)545+ processedTree.singleCache.set(key, tree)546+ }547+ return findMatch(path, tree, fuzzy)548+}⚠️ Potential issue | 🟠 Major
Fix depth initialization in findSingleMatch.
Line 544 passes
1for the initial depth parameter, but the root node should be at depth 0 (consistent withprocessRouteTreeat line 600). This causes depth offset errors in the cached single-route trees.Apply this diff:
tree = createStaticNode<{ from: string }>('/') const data = new Uint16Array(6) - parseSegments(caseSensitive, data, { from }, 1, tree, 1) + parseSegments(caseSensitive, data, { from }, 1, tree, 0) processedTree.singleCache.set(key, tree) } return findMatch(path, tree, fuzzy)🤖 Prompt for AI Agents
In packages/router-core/src/new-process-route-tree.ts around lines 530 to 548, the root node for the single-route tree is being initialized with depth 1 when calling parseSegments, causing a depth offset compared to processRouteTree which uses depth 0; change the initial depth argument from 1 to 0 (i.e., call parseSegments with depth 0) so the cached single-route trees use the correct root depth and avoid depth-related mismatches.@@ -0,0 +840,21 @@840+841+ // 5. Try wildcard match842+ if (node.wildcard) {843+ for (const segment of node.wildcard) {844+ const { prefix, suffix } = segment845+ if (prefix) {846+ const casePart = segment.caseSensitive ? part : part.toLowerCase()847+ if (!casePart.startsWith(prefix)) continue848+ }849+ if (suffix) {850+ const part = parts[parts.length - 1]!851+ const casePart = segment.caseSensitive ? part : part.toLowerCase()852+ if (!casePart.endsWith(suffix)) continue853+ }854+ // a wildcard match terminates the loop, but we need to continue searching in case there's a longer match855+ if (!wildcardMatch || wildcardMatch.index < index) {856+ wildcardMatch = { node: segment, index, skipped, depth }857+ }858+ break main859+ }860+ }⚠️ Potential issue | 🔴 Critical
Fix variable shadowing in wildcard suffix check.
Line 850 redeclares
part(already declared at line 770), shadowing the current segment. This reads the last part of the path instead of the current segment, breaking suffix validation for wildcards in the middle of a path.Apply this diff:
// 5. Try wildcard match if (node.wildcard) { for (const segment of node.wildcard) { const { prefix, suffix } = segment if (prefix) { const casePart = segment.caseSensitive ? part : part.toLowerCase() if (!casePart.startsWith(prefix)) continue } if (suffix) { - const part = parts[parts.length - 1]! - const casePart = segment.caseSensitive ? part : part.toLowerCase() + const lastPart = parts[parts.length - 1]! + const casePart = segment.caseSensitive ? lastPart : lastPart.toLowerCase() if (!casePart.endsWith(suffix)) continue }🤖 Prompt for AI Agents
In packages/router-core/src/new-process-route-tree.ts around lines 842 to 860, the suffix check mistakenly redeclares "part" (shadowing the outer "part" declared earlier) so it reads the last path segment instead of the current segment; remove the inner redeclaration and use the existing current segment variable (or rename consistently, e.g., currentPart) when building casePart and checking endsWith(suffix) so suffix validation applies to the correct segment.✅ Addressed in commit b6570e3
Actionable comments posted: 0
♻️ Duplicate comments (1)
packages/router-core/src/new-process-route-tree.ts (1)
147-291: Critical: Fix depth synchronization when reusing existing nodes.When an existing node is reused (lines 159, 174, 208, 245, etc.), the local
depthvariable is never updated to match that node's depth. This causes newly created sibling nodes to be assigned incorrect depth values, breaking the invariant thatnode.depthequals the node's distance from root.Example scenario:
- First route
/foo/barcreatesfoo(depth=1) andbar(depth=2) - Second route
/foo/bazreusesfoonode but leaves localdepth=0 - New node
bazgetsdepth = ++depth = 1, but should be2
This breaks
buildBranch(line 716) which usesnode.depthas an array index, and causesextractParamsbitmask alignment errors for optional parameters.Apply this fix after line 290 to resynchronize depth whenever we advance to the next node:
} node = nextNode + depth = node.depth }This ensures
depthstays consistent whether we create a new node or reuse an existing one.🧹 Nitpick comments (2)
packages/router-core/src/new-process-route-tree.ts (2)
309-326: Sort logic is sound, but consider adding tie-breaker.The
sortDynamiccomparator correctly prioritizes longer/more-specific prefixes and suffixes, then presence of constraints. Ties return0, relying on stable sort.For deterministic behavior across JS engines, consider adding an alphabetical tie-breaker (as noted in past comments), though this is acceptable for a WIP implementation.
793-793: Note: Bitmask limits optional parameter depth to ~32 levels.The
skippedbitmask uses(1 << depth)for tracking which optional parameters were skipped. JavaScript bitwise operations are limited to 32 bits, so route trees deeper than 32 levels with optional parameters may experience incorrect behavior due to bit overflow.This is likely acceptable for practical route trees, but worth documenting as a constraint.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 162a3d75960e80379377e0b4b979699ba55212fd and 58baf3e8158874b96a05f0b8598881e35cd76124.
📒 Files selected for processing (2)
packages/router-core/src/new-process-route-tree.ts(1 hunks)packages/solid-router/src/index.tsx(0 hunks)
💤 Files with no reviewable changes (1)
- packages/solid-router/src/index.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/src/new-process-route-tree.ts
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/src/new-process-route-tree.ts
🧠 Learnings (7)
📓 Common learnings
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directoriesApplied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/src/new-process-route-tree.ts
🧬 Code graph analysis (1)
packages/router-core/src/new-process-route-tree.ts (2)
packages/router-core/src/route.ts (3)
path(1551-1553)RouteLike(1968-1979)fullPath(1555-1557)
packages/router-core/src/path.ts (1)
trimPathRight(38-40)
🔇 Additional comments (6)
packages/router-core/src/new-process-route-tree.ts (6)
29-122: Well-structured segment parser.The parseSegment function correctly handles all four segment types (static, param, wildcard, optional) with prefix/suffix support. The use of early returns and regex patterns is clean and efficient.
407-492: Type definitions are well-structured.The type hierarchy correctly models the segment tree structure with discriminated unions (
StaticSegmentNodevsDynamicSegmentNode), and theRouteLikeunion elegantly handles both tree-based and flat route representations.
611-616: Verify routesByPath collision handling is intentional.When multiple routes map to the same trimmed path, the implementation prefers routes ending with
/(line 613). This means/fooand/foo/both store under key/foo, but the trailing-slash variant wins.Verify this is the desired precedence, as it could be surprising when looking up routes by path.
842-860: Wildcard suffix logic is correct but asymmetric.The wildcard matching checks
prefixagainst the current part (line 846-848) butsuffixagainst the last part (line 850-852). This asymmetry is correct: wildcards consume all remaining segments, so the suffix constraint applies to the final segment only.The implementation is correct for wildcard semantics.
650-713: Parameter extraction logic is correct and clever.The
extractParamsfunction correctly handles all segment types, including the complex optional parameter skip detection via bitmask (line 693). String offset calculations for extracting parameter names from the route'sfullPathare accurate.The optimization to defer param name extraction until match time (rather than storing in nodes) enables sharing nodes that differ only in param names.
729-729: Path normalization silently handles consecutive slashes.parts.filter(Boolean)removes empty strings, normalizing paths like/foo//barto/foo/bar. This is likely intentional for robustness, but callers might expect strict path validation instead of silent normalization.The current behavior is reasonable for a router.
- First route
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-plugin
@coderabbitai review
✅ Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Actionable comments posted: 0
♻️ Duplicate comments (4)
packages/router-core/src/new-process-route-tree.ts (3)
170-170: Critical: Fix depth calculation when reusing existing nodes.Lines 170, 185, 222, 260, and 288 use
++depthto setnext.depth, which mutates the outerdepthvariable. When the loop encounters an existing child node,depthis incremented but never synchronized with the child's actual depth. This causes subsequent siblings to receive incorrect depth values, breakingbuildBranchandextractParamsfor routes that share prefixes (e.g.,/foo/barfollowed by/foo/baz).Apply this diff to compute depth from the parent and resync for both new and existing nodes:
if (caseSensitive) { const existingNode = node.static?.get(value) if (existingNode) { nextNode = existingNode } else { node.static ??= new Map() const next = createStaticNode<TRouteLike>( route.fullPath ?? route.from, ) next.parent = node - next.depth = ++depth + next.depth = node.depth + 1 nextNode = next node.static.set(value, next) } } else { const name = value.toLowerCase() const existingNode = node.staticInsensitive?.get(name) if (existingNode) { nextNode = existingNode } else { node.staticInsensitive ??= new Map() const next = createStaticNode<TRouteLike>( route.fullPath ?? route.from, ) next.parent = node - next.depth = ++depth + next.depth = node.depth + 1 nextNode = next node.staticInsensitive.set(name, next) } }Apply similar fixes to dynamic/optional/wildcard node creation:
) nextNode = next - next.depth = ++depth + next.depth = node.depth + 1 next.parent = nodeAnd resync depth after advancing to the next node:
node = nextNode + depth = node.depth }Also applies to: 185-185, 222-222, 260-260, 288-288
546-546: Critical: Pass caseSensitive parameter to parseSegments.Line 546 hardcodes
caseSensitiveas the first argument but then callsparseSegments(caseSensitive, ...). However, the temporary tree is always built with case-insensitive semantics because the hardcoded value should match the caller'scaseSensitiveparameter. Currently, static segments are lowercased regardless of the caller's flag, breakingrouter.matchRoute({ caseSensitive: true }).The code currently passes
caseSensitivecorrectly on line 546. If tests are failing, verify the logic insideparseSegmentsproperly honors the flag.
895-898: Critical: Fix wildcard suffix validation to use the correct segment.Lines 895-898 check the suffix for wildcards, but line 896 constructs
endfromparts.slice(index).join('/')which represents the rest of the path, not the current segment. For wildcards in the middle of a path, this reads the wrong portion and breaks suffix matching.Apply this diff:
if (suffix) { - const end = parts.slice(index).join('/').slice(-suffix.length) - const casePart = segment.caseSensitive ? end : end.toLowerCase() - if (casePart !== suffix) continue + const lastPart = parts[parts.length - 1]! + const casePart = segment.caseSensitive ? lastPart : lastPart.toLowerCase() + if (!casePart.endsWith(suffix)) continue }packages/router-core/src/path.ts (1)
194-201: Fix undefined prefix/suffix in optional param serialization.Line 200 uses template literals with
prefixandsuffixvariables that may beundefined. When either is undefined, the resulting string will contain the literal text"undefined", corrupting the path template (e.g.,"undefined{-$id}undefined").Apply this diff to normalize undefined values to empty strings:
} else { // SEGMENT_TYPE_OPTIONAL_PARAM - joined += `${prefix}{-$${value}}${suffix}` + const safePrefix = prefix ?? '' + const safeSuffix = suffix ?? '' + joined += `${safePrefix}{-$${value}}${safeSuffix}` }🧹 Nitpick comments (5)
packages/router-core/src/new-process-route-tree.ts (1)
311-328: Consider adding alphabetical fallback to sortDynamic.The
sortDynamicfunction prioritizes prefix/suffix length but doesn't provide a stable fallback when segments are identical. This can lead to non-deterministic ordering across environments or V8 versions.Add a final alphabetical comparison:
if (a.suffix && !b.suffix) return -1 if (!a.suffix && b.suffix) return 1 + // Fallback to alphabetical order for stability + const aStr = (a.prefix ?? '') + (a.suffix ?? '') + const bStr = (b.prefix ?? '') + (b.suffix ?? '') + return aStr.localeCompare(bStr) - return 0 }packages/router-core/tests/optional-path-params-clean.test.ts (1)
3-10: Fix import order and type import style.Lines 7 and 9 violate ESLint rules for import ordering and type import style. These are minor style issues but should be fixed for consistency.
Apply this diff:
import { findSingleMatch, parseSegment, processRouteTree, - SEGMENT_TYPE_OPTIONAL_PARAM, SEGMENT_TYPE_PATHNAME, - type SegmentKind, + SEGMENT_TYPE_OPTIONAL_PARAM, } from '../src/new-process-route-tree' +import type { SegmentKind } from '../src/new-process-route-tree'packages/router-core/tests/new-process-route-tree.test.ts (1)
4-4: Remove unused import or implement processFlatRouteList tests.Line 4 imports
processFlatRouteListbut it's only used in adescribe.todoblock (lines 317-329). Either implement the tests or remove the import to clean up the code.If tests aren't ready, remove the import:
import { findRouteMatch, - processFlatRouteList, processRouteTree, } from '../src/new-process-route-tree'Also applies to: 317-329
packages/router-core/tests/path.test.ts (1)
9-18: Fix import issues: remove unused import and fix style.Line 13 imports
SEGMENT_TYPE_OPTIONAL_PARAMbut it's never used. Lines 13 and 17 also violate import ordering and type import style rules.Apply this diff:
import { findSingleMatch, parseSegment, processRouteTree, - SEGMENT_TYPE_OPTIONAL_PARAM, SEGMENT_TYPE_PARAM, SEGMENT_TYPE_PATHNAME, SEGMENT_TYPE_WILDCARD, - type SegmentKind, } from '../src/new-process-route-tree' +import type { SegmentKind } from '../src/new-process-route-tree'packages/router-core/tests/optional-path-params.test.ts (1)
3-12: Fix import order and type import style.Lines 7 and 11 violate ESLint rules for import ordering and type import style, similar to other test files.
Apply this diff:
import { findSingleMatch, parseSegment, processRouteTree, - SEGMENT_TYPE_OPTIONAL_PARAM, SEGMENT_TYPE_PARAM, SEGMENT_TYPE_PATHNAME, SEGMENT_TYPE_WILDCARD, - type SegmentKind, + SEGMENT_TYPE_OPTIONAL_PARAM, } from '../src/new-process-route-tree' +import type { SegmentKind } from '../src/new-process-route-tree'📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 58baf3e8158874b96a05f0b8598881e35cd76124 and b8aead3f43c41bd624a076669bfcb132fed94adc.
📒 Files selected for processing (10)
packages/router-core/src/new-process-route-tree.ts(1 hunks)packages/router-core/src/path.ts(5 hunks)packages/router-core/src/router.ts(10 hunks)packages/router-core/tests/match-by-path.test.ts(1 hunks)packages/router-core/tests/new-process-route-tree.test.ts(1 hunks)packages/router-core/tests/optional-path-params-clean.test.ts(2 hunks)packages/router-core/tests/optional-path-params.test.ts(5 hunks)packages/router-core/tests/path.test.ts(17 hunks)packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx(0 hunks)packages/router-plugin/src/core/route-hmr-statement.ts(3 hunks)
💤 Files with no reviewable changes (1)
- packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
packages/router-core/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep framework-agnostic core router logic in packages/router-core/
Files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/**
📄 CodeRabbit inference engine (AGENTS.md)
Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directories
Files:
packages/router-plugin/src/core/route-hmr-statement.ts
packages/router-plugin/**
📄 CodeRabbit inference engine (AGENTS.md)
Use unplugin for universal bundler plugins in the router-plugin package
Files:
packages/router-plugin/src/core/route-hmr-statement.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.Applied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-core/** : Keep framework-agnostic core router logic in packages/router-core/Applied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
packages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/path.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/tests/match-by-path.test.tspackages/router-core/src/router.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/router-plugin/** : Use unplugin for universal bundler plugins in the router-plugin packageApplied to files:
packages/router-plugin/src/core/route-hmr-statement.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-cli,router-generator,router-plugin,virtual-file-routes}/** : Keep CLI, generators, bundler plugins, and virtual file routing utilities in their dedicated tooling package directoriesApplied to files:
packages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/src/path.tspackages/router-core/src/router.tspackages/router-core/tests/new-process-route-tree.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-09-23T17:36:12.598Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-09-23T17:36:12.598Z Learning: Applies to packages/{router-devtools,*-router-devtools}/** : Keep router devtools packages in packages/router-devtools/ and packages/*-router-devtools/Applied to files:
packages/router-plugin/src/core/route-hmr-statement.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/tests/path.test.ts
🪛 ESLint
packages/router-core/tests/optional-path-params-clean.test.ts
[error] 7-7: Member 'SEGMENT_TYPE_OPTIONAL_PARAM' of the import declaration should be sorted alphabetically.
(sort-imports)
[error] 9-9: Prefer using a top-level type-only import instead of inline type specifiers.
(import/consistent-type-specifier-style)
packages/router-core/tests/optional-path-params.test.ts
[error] 7-7: Member 'SEGMENT_TYPE_OPTIONAL_PARAM' of the import declaration should be sorted alphabetically.
(sort-imports)
[error] 11-11: Prefer using a top-level type-only import instead of inline type specifiers.
(import/consistent-type-specifier-style)
packages/router-core/tests/new-process-route-tree.test.ts
[error] 4-4: 'processFlatRouteList' is defined but never used.
(unused-imports/no-unused-imports)
packages/router-core/tests/path.test.ts
[error] 13-13: Member 'SEGMENT_TYPE_OPTIONAL_PARAM' of the import declaration should be sorted alphabetically.
(sort-imports)
[error] 13-13: 'SEGMENT_TYPE_OPTIONAL_PARAM' is defined but never used.
(unused-imports/no-unused-imports)
[error] 17-17: Prefer using a top-level type-only import instead of inline type specifiers.
(import/consistent-type-specifier-style)
🪛 GitHub Actions: pr
packages/router-core/tests/match-by-path.test.ts
[error] 42-42: Multiple test failures reported in match-by-path tests: expected undefined vs {} or mismatched shape in various matchByPath assertions.
packages/router-core/src/router.ts
[warning] 2094-2097: Unused eslint-disable directive (no problems were reported from '@typescript-eslint/require-await'); Async arrow function has no 'await' expression (require-await).
🔇 Additional comments (17)
packages/router-core/src/new-process-route-tree.ts (1)
502-502: Verify depth initialization consistency across processing functions.Line 502 initializes depth at
0when callingparseSegments, which is consistent withprocessRouteTree(line 596). Confirm this is correct for flat route lists and thatbuildBranchworks as expected when mixing flat and tree routes.If depth 0 is correct for the root, this is fine. Otherwise, verify against tests.
packages/router-plugin/src/core/route-hmr-statement.ts (1)
25-28: Document limitation: HMR does not handle new route additions.The TODO on line 27 indicates that adding a new route requires rebuilding the entire tree, which the current HMR logic doesn't support. This means HMR will only work for updates to existing routes, not for adding/removing routes from the tree.
Consider documenting this limitation in a comment or the PR description so users are aware that adding new routes during development will require a full reload.
packages/router-core/src/path.ts (1)
233-350: Impressive refactor: cursor-based interpolation is much cleaner.The new cursor-based approach to path interpolation is a significant improvement over the old implementation. It's more direct, easier to follow, and handles all segment types (pathname, param, wildcard, optional) in a unified way. The elimination of the intermediate segment array and direct string assembly should also improve performance.
packages/router-core/tests/match-by-path.test.ts (1)
12-24: Fix matchByPath wrapper to return undefined for non-matches.The wrapper returns
match ? match.params : undefined(line 23), but then line 24 is missing in the displayed code. Based on the pipeline failures expectingundefinedbut receiving{}, verify that the wrapper correctly returnsundefinedfor non-matching paths rather than defaulting to an empty object.Ensure the logic matches test expectations:
const matchByPath = ( from: string, options: { to: string; caseSensitive?: boolean; fuzzy?: boolean }, ) => { const match = findSingleMatch( options.to, options.caseSensitive ?? false, options.fuzzy ?? false, from, processedTree, ) return match ? match.params : undefined // Don't default to {} }⛔ Skipped due to learnings
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.packages/router-core/src/router.ts (13)
12-17: LGTM: Import changes align with the new route-tree architecture.The new imports from
./new-process-route-treeprovide the necessary utilities for the processedTree-based matching pipeline.
25-25: LGTM: LRU cache import supports performance optimization.This import enables the caching mechanism for path resolution mentioned in the PR benchmarks (~2.7× faster resolvePath).
38-38: LGTM: Type import necessary for the new architecture.
698-702: Simplified signature aligns with the new architecture.The
GetMatchRoutesFnsignature now accepts only a pathname and returns a complete match result object. This simplification is appropriate given that the processedTree encapsulates the matching logic.
905-905: Verify theanytype parameters in ProcessedTree.The
ProcessedTree<TRouteTree, any, any>usesanyfor two generic parameters. Please ensure these cannot be more specifically typed for better type safety, or confirm thatanyis intentional for this context.Based on coding guidelines for TypeScript strict mode.
1097-1109: LGTM: buildRouteTree correctly migrates to processedTree architecture.The method now properly destructures the new return value from
processRouteTreeand stores theprocessedTreeon the router instance.
1207-1208: LGTM: LRU cache initialization for path resolution performance.A cache size of 1000 entries is reasonable and aligns with the PR's performance improvements (~2.7× faster resolvePath).
1215-1215: LGTM: Cache correctly threaded through to resolvePath.
1540-1546: LGTM: getMatchedRoutes simplified to delegate to the new matching logic.The method now correctly passes
processedTreeto the standalone helper function and accepts only the pathname parameter.
1607-1607: LGTM: Correctly uses the new getMatchedRoutes signature.
1777-1793: Route masking correctly migrated to findFlatMatch.The masking logic now uses
findFlatMatchwith theprocessedTree. The flow properly extracts params and route properties from the match result.
2503-2528: matchRoute correctly uses findSingleMatch with processedTree.The method now delegates to
findSingleMatchand properly accesses theparamsproperty from the returned match. The logic for parameter and search comparison is preserved.
2621-2651: The review comment's premise is incorrect.The third parameter to
findRouteMatchisfuzzy(controls fuzzy/partial matching), notcaseSensitive. Case sensitivity is already handled during route tree construction viaprocessRouteTree(routeTree, this.options.caseSensitive, ...)at router initialization (line 1099). TheprocessedTreepassed togetMatchedRoutesalready encodes case sensitivity rules from route definitions, sofindRouteMatchdoes not need a separatecaseSensitiveparameter.Likely an incorrect or invalid review comment.
@coderabbitai review
✅ Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/router-core/src/path.ts (1)
129-129: Unusual cache key separator—confirm this is intentional.The cache key uses
\\\\as a separator between base and to paths. While this avoids conflicts with forward slashes, it's unconventional. If this choice was deliberate to prevent edge-case collisions, consider adding a brief inline comment explaining the rationale.📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 8df17ca79ddbf0f2047d21b518b60373bb000114 and bf328f36b0e3275da9fd34dc168e47e9da61ca91.
📒 Files selected for processing (1)
packages/router-core/src/path.ts(4 hunks)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/src/path.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/src/path.ts
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/router-core/src/path.ts
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/src/path.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-core/src/path.ts
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
packages/router-core/src/path.ts
🧬 Code graph analysis (1)
packages/router-core/src/path.ts (4)
packages/router-core/src/lru-cache.ts (1)
LRUCache(1-5)
packages/router-core/src/utils.ts (1)
last(191-193)
packages/router-core/src/new-process-route-tree.ts (6)
parseSegment(32-128)SegmentKind(11-15)SEGMENT_TYPE_PATHNAME(6-6)SEGMENT_TYPE_PARAM(7-7)SEGMENT_TYPE_WILDCARD(8-8)SEGMENT_TYPE_OPTIONAL_PARAM(9-9)
packages/router-generator/src/utils.ts (1)
cleanPath(38-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (3)
packages/router-core/src/path.ts (3)
316-316: The 'undefined' string fallback is intentional and tested behavior.Tests in
packages/router-core/tests/path.test.tsexplicitly verify that missing required parameters produce the literal string'undefined'(lines 279–289). The interpolation also correctly setsisMissingParams = trueto signal incomplete paths.For comparison, optional parameters fall back to empty string, and splat parameters omit the segment entirely when missing. This design allows graceful degradation while flagging via
isMissingParamsthat the path is incomplete.The current behavior appears intentional and working as designed. However, verify whether this is the intended design for the PR or if a different approach (throwing errors or omitting segments) is preferred for required parameters.
117-207: Verify test status with actual test execution before merge.Tests for URL param encoding exist in
packages/router-core/tests/path.test.ts(including URI component encoding cases withencodeURIComponentand customdecodeCharMaphandling). However, I cannot execute the test suite to confirm whether tests are currently passing or if any are actually failing.Run the unit tests locally to verify the status of URL param encoding tests:
pnpm run test:unitEnsure all path-related tests pass before merging, particularly the URI encoding tests in the
interpolatePathdescribe block.
194-201: The reported serialization issue does not exist—code is functioning correctly.Analysis of the code at lines 194-201 confirms:
prefixandsuffixderive fromsubstring()calls (lines 192-193), which always return strings, neverundefined- The optional-param template literal
${prefix}{-$${value}}${suffix}produces exactly one$character before the interpolated value: the{-$contains a literal$(not interpolation), followed by${value}interpolation, creating{-$value}at runtime—not double-$or "undefined" artifacts - Test coverage confirms correct behavior across all scenarios (100+ tests in optional-path-params.test.ts, curly-params-smoke.test.ts, and others show expected output without corruption)
No fixes needed.
Likely an incorrect or invalid review comment.
Sheraff(GitHub profile, opens in a new tab) added labelsperformance
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/router-core/src/path.ts (1)
105-205:resolvePathdrops trailing slash for wildcard + empty_splatwhentrailingSlash: 'always'For a template like
/splat/$andtrailingSlash: 'always',resolvePathcurrently:- Splits to
['', 'splat', '$', ''], - Appends
'/'unconditionally wheni > 0, even for the final empty segment, - Produces
/splat//$, whichcleanPathcollapses to/splat/$.
Later, when
_splatis missing/empty,interpolatePathremoves the wildcard segment and returns/splatwith no trailing/, contradicting the expectation that'always'yields/splat/(see the new test inpath.test.ts).You can fix this by making the join loop sensitive to leading/trailing empty segments instead of blindly inserting
'/'for every index:- let segment - let joined = '' - for (let i = 0; i < baseSegments.length; i++) { - if (i > 0) joined += '/' - const part = baseSegments[i]! - if (!part) continue - segment = parseSegment(part, 0, segment) - const kind = segment[0] - if (kind === SEGMENT_TYPE_PATHNAME) { - joined += part - continue - } - const end = segment[5] - const prefix = part.substring(0, segment[1]) - const suffix = part.substring(segment[4], end) - const value = part.substring(segment[2], segment[3]) - if (kind === SEGMENT_TYPE_PARAM) { - joined += prefix || suffix ? `${prefix}{$${value}}${suffix}` : `$${value}` - } else if (kind === SEGMENT_TYPE_WILDCARD) { - joined += prefix || suffix ? `${prefix}{$}${suffix}` : '$' - } else { - // SEGMENT_TYPE_OPTIONAL_PARAM - joined += `${prefix}{-$${value}}${suffix}` - } - } + let segment + let joined = '' + for (let i = 0; i < baseSegments.length; i++) { + const part = baseSegments[i]! + const isFirst = i === 0 + const isLast = i === baseSegments.length - 1 + + if (!part) { + // Leading empty segment -> ensure leading '/' + if (isFirst && !joined) { + joined = '/' + } else if ( + isLast && + trailingSlash === 'always' && + !joined.endsWith('/') + ) { + // Trailing empty segment encodes the requested trailing slash + joined += '/' + } + continue + } + + if (!isFirst && !joined.endsWith('/')) { + joined += '/' + } + + segment = parseSegment(part, 0, segment) + const kind = segment[0] + if (kind === SEGMENT_TYPE_PATHNAME) { + joined += part + continue + } + const end = segment[5] + const prefix = part.substring(0, segment[1]) + const suffix = part.substring(segment[4], end) + const value = part.substring(segment[2], segment[3]) + if (kind === SEGMENT_TYPE_PARAM) { + joined += prefix || suffix ? `${prefix}{$${value}}${suffix}` : `$${value}` + } else if (kind === SEGMENT_TYPE_WILDCARD) { + joined += prefix || suffix ? `${prefix}{$}${suffix}` : '$' + } else { + // SEGMENT_TYPE_OPTIONAL_PARAM + joined += `${prefix}{-$${value}}${suffix}` + } + }This preserves existing behavior for static/param segments, but for templates like
/splat/$it yields/splat/$/, and after interpolation with_splat === ''the final path becomes/splat/as intended.packages/router-core/src/router.ts (1)
2478-2533:matchRouteignores router-levelcaseSensitiveoptionIn the new implementation:
const match = findSingleMatch( next.pathname, opts?.caseSensitive ?? false, opts?.fuzzy ?? false, baseLocation.pathname, this.processedTree, )caseSensitivedefaults tofalsewhenever the caller doesn’t pass it, even if the router was configured withcaseSensitive: true. Previously, route matching (and thereforematchRoute) respected the router-levelcaseSensitivedefault.This can silently change behavior for apps that rely on case-sensitive routing but call
matchRoute/useMatchRoutewithout explicitly specifyingcaseSensitive.A minimal fix is to fall back to the router option:
- const match = findSingleMatch( - next.pathname, - opts?.caseSensitive ?? false, - opts?.fuzzy ?? false, - baseLocation.pathname, - this.processedTree, - ) + const match = findSingleMatch( + next.pathname, + opts?.caseSensitive ?? this.options.caseSensitive ?? false, + opts?.fuzzy ?? false, + baseLocation.pathname, + this.processedTree, + )Everything else in
matchRoute(deep-equality check forlocation.params, and optional search comparison) looks consistent with prior behavior.♻️ Duplicate comments (1)
packages/router-core/src/new-process-route-tree.ts (1)
353-372: Add stable tie-breaker for deterministic route ordering.The sortDynamic function returns 0 when two segments have identical prefix, suffix, and case-sensitivity properties. This creates non-deterministic ordering when multiple routes share these attributes, which can cause inconsistent matching behavior across runs or JavaScript engines.
Add a final alphabetical comparison by fullPath to ensure stable, deterministic ordering:
if (a.suffix && !b.suffix) return -1 if (!a.suffix && b.suffix) return 1 if (a.caseSensitive && !b.caseSensitive) return -1 if (!a.caseSensitive && b.caseSensitive) return 1 + // Stable tie-breaker for deterministic ordering + return a.fullPath.localeCompare(b.fullPath) - return 0 }🧹 Nitpick comments (2)
packages/router-core/tests/optional-path-params-clean.test.ts (1)
15-51: SharedparsePathname/PathSegmenthelpers could be centralizedThis
PathSegment+parsePathnamecombo is effectively identical to the one inoptional-path-params.test.ts. Consider extracting a tiny test utility (e.g.test-utils/segment-helpers.ts) to keep these helpers in sync and make future parser changes easier to roll out across tests.packages/router-core/src/new-process-route-tree.ts (1)
510-522: Remove commented code before final merge.The commented-out
intoRouteLikefunction should be removed if it's no longer needed, or uncommented and documented if it will be used.📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between bf328f36b0e3275da9fd34dc168e47e9da61ca91 and f952c876b1698cb13c16a2be358f1e8d7344f1ac.
📒 Files selected for processing (7)
packages/router-core/src/new-process-route-tree.ts(1 hunks)packages/router-core/src/path.ts(4 hunks)packages/router-core/src/router.ts(10 hunks)packages/router-core/tests/new-process-route-tree.test.ts(1 hunks)packages/router-core/tests/optional-path-params-clean.test.ts(2 hunks)packages/router-core/tests/optional-path-params.test.ts(5 hunks)packages/router-core/tests/path.test.ts(18 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/router-core/tests/new-process-route-tree.test.ts
🧰 Additional context used
🧠 Learnings (8)
📓 Common learnings
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/src/path.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
📚 Learning: 2025-09-22T00:56:49.237Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5 Timestamp: 2025-09-22T00:56:49.237Z Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/optional-path-params-clean.test.ts
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5284 File: e2e/react-start/basic/server.js:50-0 Timestamp: 2025-09-28T21:41:45.233Z Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/src/path.tspackages/router-core/tests/optional-path-params.test.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-09-22T00:56:53.426Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5182 File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172 Timestamp: 2025-09-22T00:56:53.426Z Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.Applied to files:
packages/router-core/tests/path.test.tspackages/router-core/src/path.tspackages/router-core/src/new-process-route-tree.ts
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/router-core/src/path.tspackages/router-core/tests/optional-path-params-clean.test.tspackages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61 Timestamp: 2025-10-01T18:31:35.420Z Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.Applied to files:
packages/router-core/src/new-process-route-tree.tspackages/router-core/src/router.ts
🧬 Code graph analysis (6)
packages/router-core/tests/path.test.ts (2)
packages/router-core/src/path.ts (2)
interpolatePath(247-349)resolvePath(116-206)
packages/router-core/src/new-process-route-tree.ts (7)
processRouteTree(645-702)findSingleMatch(595-615)SegmentKind(11-15)parseSegment(54-151)SEGMENT_TYPE_PATHNAME(6-6)SEGMENT_TYPE_PARAM(7-7)SEGMENT_TYPE_WILDCARD(8-8)
packages/router-core/src/path.ts (4)
packages/router-core/src/lru-cache.ts (1)
LRUCache(1-5)
packages/router-core/src/utils.ts (1)
last(191-193)
packages/router-core/src/new-process-route-tree.ts (5)
parseSegment(54-151)SEGMENT_TYPE_PATHNAME(6-6)SEGMENT_TYPE_PARAM(7-7)SEGMENT_TYPE_WILDCARD(8-8)SEGMENT_TYPE_OPTIONAL_PARAM(9-9)
packages/router-generator/src/utils.ts (1)
cleanPath(38-41)
packages/router-core/tests/optional-path-params.test.ts (1)
packages/router-core/src/new-process-route-tree.ts (8)
SegmentKind(11-15)parseSegment(54-151)SEGMENT_TYPE_PATHNAME(6-6)SEGMENT_TYPE_OPTIONAL_PARAM(9-9)SEGMENT_TYPE_PARAM(7-7)SEGMENT_TYPE_WILDCARD(8-8)processRouteTree(645-702)findSingleMatch(595-615)
packages/router-core/tests/optional-path-params-clean.test.ts (1)
packages/router-core/src/new-process-route-tree.ts (6)
SegmentKind(11-15)parseSegment(54-151)SEGMENT_TYPE_PATHNAME(6-6)SEGMENT_TYPE_OPTIONAL_PARAM(9-9)processRouteTree(645-702)findSingleMatch(595-615)
packages/router-core/src/new-process-route-tree.ts (2)
packages/router-core/src/route.ts (3)
path(1551-1553)RouteLike(1968-1979)fullPath(1555-1557)
packages/router-core/src/lru-cache.ts (2)
LRUCache(1-5)createLRUCache(7-74)
packages/router-core/src/router.ts (5)
packages/router-core/src/new-process-route-tree.ts (7)
ProcessedTree(539-554)processRouteTree(645-702)processRouteMasks(556-573)findFlatMatch(578-590)findSingleMatch(595-615)trimPathRight(637-639)findRouteMatch(617-634)
packages/router-core/src/lru-cache.ts (1)
createLRUCache(7-74)
packages/router-core/src/route.ts (2)
path(1551-1553)RouteMask(1466-1475)
packages/router-core/src/path.ts (3)
resolvePath(116-206)cleanPath(25-28)trimPathRight(38-40)
packages/router-core/src/utils.ts (1)
deepEqual(333-387)
🔇 Additional comments (15)
packages/router-core/tests/optional-path-params.test.ts (2)
15-55: LocalparsePathnamecorrectly tracksparseSegmentoutputThe helper cleanly mirrors
parseSegment’s index contract (type/value/prefix/suffix) and reuses the buffer, so these tests are exercising the new segment parser accurately without extra allocations. Looks good.
334-354:matchPathnamewrapper preserves legacymatchPathnamebehaviorWiring
findSingleMatch(options.to, …, from, processedTree)is consistent with the new function’s(from, …, path)signature and the legacy{ to }-based API. Returningundefinedonly whentois provided and no match is found also matches previous semantics.packages/router-core/tests/optional-path-params-clean.test.ts (1)
141-161:matchPathnametest harness is consistent with the new single-route matcherThe helper correctly seeds a minimal
processedTreeand delegates matching tofindSingleMatch, so these tests validate the new matcher rather than the old path helpers. No issues spotted.packages/router-core/tests/path.test.ts (1)
362-395: Trailing-slash interpolation tests align withinterpolatePathbehaviorThese new cases around required vs optional params and trailing
/give good coverage of the updated interpolation logic, including optional segments with and without values. They match the current implementation’s intent.packages/router-core/src/path.ts (1)
221-347:interpolatePath+encodeParamlogic looks soundThe new cursor-based interpolation using
parseSegmentcorrectly distinguishes pathname, param, optional param, and wildcard segments, and:- Tracks
usedParamsandisMissingParamsconsistently (including the_splatmissing cases the tests assert on), - Leaves
/unencoded for_splatviaencodeURI, while routing all other params throughencodePathParam+decodeCharMap, - Handles optional params with prefix/suffix by omitting just the param when the value is
null/undefined.
Given the existing tests around numeric params, URI encoding, missing params, and optional segments, the behavior here matches expectations.
packages/router-core/src/router.ts (4)
1212-1221:resolvePathWithBasecache wiring is straightforwardUsing a dedicated
resolvePathCacheLRU and passing it intoresolvePathis a nice way to avoid recomputing path resolutions. The cache key intentionally omitstrailingSlashbased on the assumption that a router instance uses a fixedtrailingSlashoption, which matches how this cache is used here.
1453-1551:getMatchedRoutesintegration withProcessedTreelooks correctRouterCore.getMatchedRoutesnow delegates to the exportedgetMatchedRouteshelper with{ pathname, routesById, processedTree }. The helper usesfindRouteMatch(trimPathRight(pathname), processedTree, true)and falls back to the root route when no match is found, preserving the previous fuzzy-root semantics. Param propagation intorouteParamsviaObject.assignalso guards against mutating cached match objects.
1782-1797: Route mask matching viafindFlatMatchis well-structuredUsing
findFlatMatch<RouteMask<TRouteTree>>(next.pathname, this.processedTree)and copyingmatch.paramsinto a freshparamsobject avoids mutating cached matches, and destructuring{ from: _from, ...maskProps }to buildmaskedDestkeeps the publicfromfield out of the masked navigation options. Behavior-wise this aligns with the existing route-masking model.
2626-2655:getMatchedRouteshelper correctly switches tofindRouteMatchThe exported
getMatchedRoutesnow usesfindRouteMatch(trimPathRight(pathname), processedTree, true)instead of flat-route parsing, then walksparentRoutelinks to buildmatchedRoutes, defaulting to the root route when no match is found. This is a clean adaptation to the newProcessedTreerepresentation and matches the router’s existing fuzzy-not-found behavior.packages/router-core/src/new-process-route-tree.ts (6)
1-151: Well-structured parsing foundation.The segment parsing logic is clean and efficient. The use of Uint16Array for parsed segment representation is a smart performance optimization, and the regex patterns correctly handle the braced parameter syntax. The parseSegment function properly handles all segment types with appropriate index boundary tracking.
162-351: Solid recursive tree-building logic.The parseSegments function correctly handles tree construction with proper depth tracking, node reuse, and case sensitivity. The logic to distinguish between layout routes and index routes (lines 329-337) is well thought out, and the recursive child processing maintains correct parent-child relationships.
405-455: Well-structured node creation with performance considerations.The node creation functions properly initialize all fields, and the comment about field ordering for engine optimization shows attention to performance details. The type structure using discriminated unions is clean and type-safe.
556-702: Comprehensive tree processing with proper caching.The tree processing functions correctly handle both tree-based and flat route structures. The LRU caching strategy is well-applied, and the depth initialization is consistent throughout. The routesByPath logic that prioritizes index routes (line 679) is correct for handling ambiguous cases.
724-801: Parameter extraction logic is well-structured.The extractParams and buildBranch functions correctly handle all segment types with proper decoding. The lazy initialization of nodeParts and the bitmask optimization for optional params show good attention to performance.
The URL encoding complexities (matching encoded path parts against unencoded route prefixes/suffixes) are inherently challenging and likely the source of the failing tests mentioned in the PR objectives.
803-1055: Sophisticated matching algorithm with correct priority handling.The stack-based matching approach efficiently explores all possible routes with proper priority ordering. The use of statics/dynamics/optionals counters to track match quality is elegant, and the bitmask optimization for skipped optional params is clever. The wildcard suffix check (line 919) correctly handles multi-segment remaining paths by joining and checking the trailing characters.
This is a complex but well-designed algorithm that correctly implements the intended matching semantics.
Resolvedby Sheraff(GitHub profile, opens in a new tab)@@ -1098,12 +1099,17 @@1098- routeTree: this.routeTree,1099- initRoute: (route, i) => {1099+ const { routesById, routesByPath, processedTree } = processRouteTree(1100+ this.routeTree,1101+ this.options.caseSensitive,1102+ (route, i) => {11001103 route.init({11011104 originalIndex: i,11021105 })11031106 },1104- })1107+ )1108+ if (this.options.routeMasks) {1109+ processRouteMasks(this.options.routeMasks, processedTree)1110+ }1105111111061112 this.routesById = routesById as RoutesById<TRouteTree>11071113 this.routesByPath = routesByPath as RoutesByPath<TRouteTree>1108- this.flatRoutes = flatRoutes as Array<AnyRoute>1114+ this.processedTree = processedTree11091115⚠️ Potential issue | 🟠 Major
Route masks are not reprocessed when only
routeMaskschangebuildRouteTreewiresprocessRouteTreeandprocessRouteMaskstogether, butprocessRouteMasksis only called here, conditioned onthis.options.routeMasksat build time. Later inupdate, changes torouteMasksalone (with an unchangedrouteTree) won’t triggerbuildRouteTree, so:processedTree.masksTreeandflatCachewill continue to reflect the old masks,- New or removed masks won’t take effect until the route tree itself is replaced.
If
routeMasksare intended to be mutable viarouter.update, consider re-runningprocessRouteMasks(and clearingflatCache) whenrouteMaskschange, e.g. by tracking the previous masks inupdateand invokingprocessRouteMasksthere.🤖 Prompt for AI Agents
In packages/router-core/src/router.ts around lines 1098 to 1115, buildRouteTree only calls processRouteMasks at build time so later calls to update that change only this.options.routeMasks will not reprocess masks or clear related caches; modify the update flow to detect when routeMasks have changed (store previous masks reference or perform a shallow equality check), and when they differ re-run processRouteMasks(this.options.routeMasks, this.processedTree) and invalidate/clear flatCache (and any derived masksTree) so processedTree reflects new masks without requiring the routeTree to be replaced.Resolvedby Sheraff(GitHub profile, opens in a new tab)@@ -501,0 +544,21 @@544+ const tail = trailingSlash === 'always' ? '/' : ''545+ const defaultedFromPath = '/'546+ const fromPath = resolvePath({547+ base: defaultedFromPath,548+ to: '.',549+ trailingSlash,550+ })551+ const nextTo = resolvePath({552+ base: fromPath,553+ to: '/splat/$',554+ trailingSlash,555+ })556+ const nextParams = { _splat: '' }557+ const interpolatedNextTo = interpolatePath({558+ path: nextTo,559+ params: nextParams,560+ }).interpolatedPath561+ expect(interpolatedNextTo).toBe(`/splat${tail}`)562+ },563+ )564+})⚠️ Potential issue | 🟠 Major
resolvePath+interpolatePathmismatch for_splat === ''andtrailingSlash: 'always'Given the current
resolvePathimplementation,resolvePath({ base: '/', to: '/splat/$', trailingSlash: 'always' })produces/splat/$(no final/after$). When_splatis'',interpolatePathdrops the wildcard segment and returns/splatwithout adding a trailing slash (since the original template doesn’t end with/). That means the'always'case in this test will not produce/splat/as expected untilresolvePath’s join logic is fixed (seepath.tsreview).- Splits to
Sheraff(GitHub profile, opens in a new tab) closed this
Sheraff(GitHub profile, opens in a new tab) changed the title
Sign in to join this conversation.
Walkthrough#
Replaces the legacy pathname parser and route-tree processor with a new segment-trie processor, moves parsing/matching primitives into a new module, updates path utilities to use the segment model, replaces RouterCore's flatRoutes with processedTree and simplifies getMatchedRoutes, updates HMR and tests accordingly, and marks MatchRouteOptions.caseSensitive as deprecated.
Changes#
docs/router/framework/react/api/router/MatchRouteOptionsType.md,packages/router-core/src/Matches.tscaseSensitive?: booleanannotated as deprecated in docs and JSDoc; guidance added to configure case sensitivity at route or router level.packages/router-core/src/process-route-tree.tspackages/router-core/src/new-process-route-tree.tsparseSegment, segment node types/factories, trie construction, deterministic node sorting, matching primitives, param extraction, caching and public APIs (processRouteTree,processFlatRouteList,findRouteMatch,findFlatMatch,findSingleMatch,trimPathRight, etc.).packages/router-core/src/path.tsjoinPaths,cleanPath,trimPath*,removeTrailingSlash,exactPathTest,resolvePath;interpolatePathreimplemented; legacy parse/match exports and old Segment constants removed.packages/router-core/src/router.tsflatRouteswithprocessedTree: ProcessedTree<...>;getMatchedRoutessimplified to accept onlypathnameand returnfoundRoute; internal calls migrated to new-process-route-tree APIs and caches updated.packages/router-core/src/index.ts,packages/react-router/src/index.tsx,packages/solid-router/src/index.tsxparsePathname,matchPathname,matchByPath,Segment; removed process-route-tree related exports from barrels.packages/react-router/src/useBlocker.tsx,packages/solid-router/src/useBlocker.tsx,packages/start-server-core/src/createStartHandler.tsrouter.getMatchedRoutescalls by dropping explicit second argument (now called with onlypathname).packages/router-plugin/src/core/route-hmr-statement.tsAnyRouter; replaced flatRoutes in-place swap with segment-tree walk/replace (walkReplaceSegmentTree), cleared caches, and updated processedTree nodes for HMR updates.packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsxflatRouteskey from explorerState shaping; devtools explorer no longer exposesflatRoutes.packages/router-core/tests/new-process-route-tree.test.ts,packages/router-core/tests/match-by-path.test.ts,packages/router-core/tests/optional-path-params*.test.ts,packages/router-core/tests/path.test.tsprocessedTreeviaprocessRouteTree, and to align expectations with new parsing semantics (empty root pathname segment, unprefixed param names, etc.).packages/react-router/src/index.tsx,packages/solid-router/src/index.tsxSegmenttype from framework barrels.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs#
Suggested reviewers#
Poem#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.