From b51a2d60ab80f43a2670f9400d08df9980f9cf9e Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 22 Mar 2026 19:36:41 +0100 Subject: [PATCH] fix(router-core): avoid per-location url accessor overhead --- packages/router-core/src/location.ts | 5 + packages/router-core/src/router.ts | 146 +++++++++++++----- .../router-core/tests/build-location.test.ts | 52 +++++++ packages/router-core/tests/mask.test.ts | 2 + 4 files changed, 164 insertions(+), 41 deletions(-) diff --git a/packages/router-core/src/location.ts b/packages/router-core/src/location.ts index 956b88a80a..577487ac6d 100644 --- a/packages/router-core/src/location.ts +++ b/packages/router-core/src/location.ts @@ -48,4 +48,9 @@ export interface ParsedLocation { * @description Whether the publicHref is external (different origin from rewrite). */ external: boolean + /** + * A `URL` object representation of the location. This object is created lazily, + * so reading this property is not free. + */ + url: URL } diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 965fefda33..b32544386f 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1277,19 +1277,23 @@ export class RouterCore< const parsedSearch = this.options.parseSearch(search) const searchStr = this.options.stringifySearch(parsedSearch) - return { - href: pathname + searchStr + hash, - publicHref: href, - pathname: decodePath(pathname).path, - external: false, - searchStr, - search: nullReplaceEqualDeep( - previousLocation?.search, - parsedSearch, - ) as any, - hash: decodePath(hash.slice(1)).path, - state: replaceEqualDeep(previousLocation?.state, state), - } + return initializeParsedLocation( + { + __proto__: parsedLocationPrototype, + href: pathname + searchStr + hash, + publicHref: href, + pathname: decodePath(pathname).path, + external: false, + searchStr, + search: nullReplaceEqualDeep( + previousLocation?.search, + parsedSearch, + ) as any, + hash: decodePath(hash.slice(1)).path, + state: replaceEqualDeep(previousLocation?.state, state), + } as ParsedLocationWithoutUrl>, + this.origin!, + ) } // Before we do any processing, we need to allow rewrites to modify the URL @@ -1306,19 +1310,24 @@ export class RouterCore< const fullPath = url.href.replace(url.origin, '') - return { - href: fullPath, - publicHref: href, - pathname: decodePath(url.pathname).path, - external: !!this.rewrite && url.origin !== this.origin, - searchStr, - search: nullReplaceEqualDeep( - previousLocation?.search, - parsedSearch, - ) as any, - hash: decodePath(url.hash.slice(1)).path, - state: replaceEqualDeep(previousLocation?.state, state), - } + return initializeParsedLocation( + { + __proto__: parsedLocationPrototype, + href: fullPath, + publicHref: href, + pathname: decodePath(url.pathname).path, + external: !!this.rewrite && url.origin !== this.origin, + searchStr, + search: nullReplaceEqualDeep( + previousLocation?.search, + parsedSearch, + ) as any, + hash: decodePath(url.hash.slice(1)).path, + state: replaceEqualDeep(previousLocation?.state, state), + } as ParsedLocationWithoutUrl>, + this.origin!, + fullUrl, + ) } const location = parse(locationToParse) @@ -1330,13 +1339,11 @@ export class RouterCore< const parsedTempLocation = parse(__tempLocation) as any parsedTempLocation.state.key = location.state.key // TODO: Remove in v2 - use __TSR_key instead parsedTempLocation.state.__TSR_key = location.state.__TSR_key + parsedTempLocation.maskedLocation = location delete parsedTempLocation.state.__tempLocation - return { - ...parsedTempLocation, - maskedLocation: location, - } + return parsedTempLocation } return location } @@ -1975,12 +1982,16 @@ export class RouterCore< let href: string let publicHref: string let external = false + let memoUrl: URL | null = null + let origin: string if (this.rewrite) { // With rewrite, we need to construct URL to apply the rewrite const url = new URL(fullPath, this.origin) const rewrittenUrl = executeRewriteOutput(this.rewrite, url) + memoUrl = rewrittenUrl href = url.href.replace(url.origin, '') + origin = rewrittenUrl.origin // If rewrite changed the origin, publicHref needs full URL // Otherwise just use the path components if (rewrittenUrl.origin !== this.origin) { @@ -1997,19 +2008,25 @@ export class RouterCore< // since decodePath decoded them from the interpolated path href = encodePathLikeUrl(fullPath) publicHref = href + origin = this.origin! } - return { - publicHref, - href, - pathname: nextPathname, - search: nextSearch, - searchStr, - state: nextState as any, - hash: hash ?? '', - external, - unmaskOnReload: dest.unmaskOnReload, - } + return initializeParsedLocation( + { + __proto__: parsedLocationPrototype, + publicHref, + href, + pathname: nextPathname, + search: nextSearch, + searchStr, + state: nextState as any, + hash: hash ?? '', + external, + unmaskOnReload: dest.unmaskOnReload, + } as ParsedLocationWithoutUrl, + origin, + memoUrl, + ) } const buildWithMatches = ( @@ -2949,6 +2966,53 @@ function comparePaths(a: string, b: string) { return normalize(a) === normalize(b) } +type ParsedLocationWithoutUrl = Omit< + ParsedLocation, + 'url' +> + +const parsedLocationOrigins = new WeakMap, string>() +const parsedLocationUrls = new WeakMap, URL>() + +function getParsedLocationUrl(location: ParsedLocation) { + let url = parsedLocationUrls.get(location) + + if (!url) { + const origin = parsedLocationOrigins.get(location) + + if (!origin) { + throw new Error('ParsedLocation origin is missing') + } + + url = new URL(location.publicHref, origin) + parsedLocationUrls.set(location, url) + } + + return url +} + +const parsedLocationPrototype = { + get url() { + return getParsedLocationUrl(this as ParsedLocation) + }, +} + +function initializeParsedLocation( + location: ParsedLocationWithoutUrl, + origin: string, + url?: URL | null, +): ParsedLocation { + const parsedLocation = location as ParsedLocation + + parsedLocationOrigins.set(parsedLocation, origin) + + if (url) { + parsedLocationUrls.set(parsedLocation, url) + } + + return parsedLocation +} + /** * Lazily import a module function and forward arguments to it, retaining * parameter and return types for the selected export key. diff --git a/packages/router-core/tests/build-location.test.ts b/packages/router-core/tests/build-location.test.ts index 6aca9b3b6a..3810a64795 100644 --- a/packages/router-core/tests/build-location.test.ts +++ b/packages/router-core/tests/build-location.test.ts @@ -1246,6 +1246,58 @@ describe('buildLocation - location output structure', () => { expect(location.searchStr).toBe('') expect(location.href).toBe('/posts') }) + + test('location should expose a memoized lazy url', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: { page: 1 }, + hash: 'section', + }) + + expect(Object.keys(location)).not.toContain('url') + expect(location.url).toBe(location.url) + expect(location.url.pathname).toBe('/posts') + expect(location.url.search).toBe('?page=1') + expect(location.url.hash).toBe('#section') + }) + + test('router state location should expose url after parsing history', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/posts?page=1#section'], + }), + }) + + await router.load() + + expect(router.state.location.url.pathname).toBe('/posts') + expect(router.state.location.url.search).toBe('?page=1') + expect(router.state.location.url.hash).toBe('#section') + }) }) describe('buildLocation - optional params', () => { diff --git a/packages/router-core/tests/mask.test.ts b/packages/router-core/tests/mask.test.ts index 7e46303787..9305cc8730 100644 --- a/packages/router-core/tests/mask.test.ts +++ b/packages/router-core/tests/mask.test.ts @@ -90,6 +90,8 @@ describe('buildLocation - route masks', () => { expect(location.maskedLocation).toBeDefined() expect(location.maskedLocation!.pathname).toBe('/photos/123') expect(location.pathname).toBe('/photos/123/modal') + expect(location.maskedLocation!.url.pathname).toBe('/photos/123') + expect(location.url.pathname).toBe('/photos/123/modal') }) test('should set params to {} when maskParams is false', () => {