Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/five-otters-feel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/router-core': minor
---

restore url property on ParsedLocation objects
5 changes: 5 additions & 0 deletions docs/router/api/router/ParsedLocationType.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,10 @@ interface ParsedLocation {
hash: string
maskedLocation?: ParsedLocation
unmaskOnReload?: boolean
url: URL
}
```

> [!NOTE]
> The `url` property of a `ParsedLocation` is a getter, and the `URL` may be computed
> on demand. In hot loops, relying on this property may have a negative performance impact.
5 changes: 5 additions & 0 deletions packages/router-core/src/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,9 @@ export interface ParsedLocation<TSearchObj extends AnySchema = {}> {
* @description Whether the publicHref is external (different origin from rewrite).
*/
external: boolean
/**
* A `URL` object representation of the location. This object may be created dynamically, so
* reading this property if not "free".
*/
url: URL
}
109 changes: 67 additions & 42 deletions packages/router-core/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1302,19 +1302,22 @@ 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 augmentLocationWithUrl(
{
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),
},
this.origin!,
)
}

// Before we do any processing, we need to allow rewrites to modify the URL
Expand All @@ -1331,19 +1334,22 @@ 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 augmentLocationWithUrl(
{
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),
},
this.origin!,
)
}

const location = parse(locationToParse)
Expand All @@ -1355,13 +1361,10 @@ 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
}
Expand Down Expand Up @@ -1989,12 +1992,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) {
Expand All @@ -2011,19 +2018,24 @@ 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 augmentLocationWithUrl(
{
publicHref,
href,
pathname: nextPathname,
search: nextSearch,
searchStr,
state: nextState as any,
hash: hash ?? '',
external,
unmaskOnReload: dest.unmaskOnReload,
},
origin,
memoUrl,
)
}

const buildWithMatches = (
Expand Down Expand Up @@ -2949,6 +2961,19 @@ export class RouterCore<
}
}

function augmentLocationWithUrl<TSearchObj extends AnySchema = {}>(
location:
| ParsedLocation<TSearchObj>
| Omit<ParsedLocation<TSearchObj>, 'url'>,
origin: string,
url?: URL | null,
): ParsedLocation<TSearchObj> {
return Object.defineProperty(location, 'url', {
enumerable: false,
get: () => (url ??= new URL(location.publicHref, origin)),
}) as ParsedLocation<TSearchObj>
}

/** Error thrown when search parameter validation fails. */
export class SearchParamError extends Error {}

Expand Down
132 changes: 132 additions & 0 deletions packages/router-core/tests/rewrite.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { describe, expect, test } from 'vitest'
import { createMemoryHistory } from '@tanstack/history'
import { BaseRootRoute, BaseRoute, RouterCore } from '../src'

const createAboutRouter = (opts: {
initialEntries: Array<string>
origin: string
rewrite: NonNullable<ConstructorParameters<typeof RouterCore>[0]['rewrite']>
}) => {
const rootRoute = new BaseRootRoute({})
const indexRoute = new BaseRoute({
getParentRoute: () => rootRoute,
path: '/',
})
const aboutRoute = new BaseRoute({
getParentRoute: () => rootRoute,
path: '/about',
})

const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])

return new RouterCore({
routeTree,
history: createMemoryHistory({ initialEntries: opts.initialEntries }),
origin: opts.origin,
rewrite: opts.rewrite,
})
}

describe('rewrite origin behavior', () => {
test('parseLocation keeps a public url when input rewrite changes origin', async () => {
const router = createAboutRouter({
initialEntries: ['/docs/about?lang=en#team'],
origin: 'https://public.example.com',
rewrite: {
input: ({ url }) => {
if (url.origin === 'https://public.example.com') {
url.pathname = url.pathname.replace(/^\/docs/, '')
return new URL(
`${url.pathname}${url.search}${url.hash}`,
'https://internal.example.com',
)
}

return url
},
},
})

await router.load()

expect(router.state.location.pathname).toBe('/about')
expect(router.state.location.href).toBe('/about?lang=en#team')
expect(router.state.location.publicHref).toBe('/docs/about?lang=en#team')
expect(router.state.location.url.href).toBe(
'https://public.example.com/docs/about?lang=en#team',
)
expect(router.state.location.url.origin).toBe('https://public.example.com')
})

test('buildLocation exposes the current origin to output rewrites', async () => {
const router = createAboutRouter({
initialEntries: ['/'],
origin: 'https://internal.example.com',
rewrite: {
output: ({ url }) => {
if (url.origin === 'https://internal.example.com') {
url.pathname = `/docs${url.pathname}`
return new URL(
`${url.pathname}${url.search}${url.hash}`,
'https://public.example.com',
)
}

return url
},
},
})

await router.load()

const location = router.buildLocation({
to: '/about',
search: { lang: 'en' },
hash: 'team',
})

expect(location.href).toBe('/docs/about?lang=en#team')
expect(location.publicHref).toBe(
'https://public.example.com/docs/about?lang=en#team',
)
expect(location.external).toBe(true)
expect(location.url.href).toBe(
'https://public.example.com/docs/about?lang=en#team',
)
expect(location.url.origin).toBe('https://public.example.com')
})

test('buildAndCommitLocation uses origin-aware rewrites when href is provided', async () => {
const router = createAboutRouter({
initialEntries: ['/docs'],
origin: 'https://public.example.com',
rewrite: {
input: ({ url }) => {
if (url.origin === 'https://public.example.com') {
url.pathname = url.pathname.replace(/^\/docs/, '') || '/'
}

return url
},
output: ({ url }) => {
if (url.origin === 'https://public.example.com') {
url.pathname = `/docs${url.pathname === '/' ? '' : url.pathname}`
}

return url
},
},
})

await router.load()
await router.buildAndCommitLocation({ href: '/docs/about?lang=en#team' })

expect(router.history.location.href).toBe('/docs/about?lang=en#team')
expect(router.state.location.pathname).toBe('/about')
expect(router.state.location.href).toBe('/about?lang=en#team')
expect(router.state.location.publicHref).toBe('/docs/about?lang=en#team')
expect(router.state.location.url.href).toBe(
'https://public.example.com/docs/about?lang=en#team',
)
})
})
Loading