Skip to content

Commit ad70a67

Browse files
authored
fix(experimental): resolve relative object locations against the current route (#2890)
* fix(experimental): resolve relative object locations against the current route * test(experimental): resolve relative objects without a current location argument Without the fix, these calls crash in production (TypeError reading 'name' of undefined). Written by an AI agent (Claude Code). Not reviewed by a human. * refactor(experimental): inline relative base in resolve to save bytes Experimental size check: +1 B min, +1 B gzip, +4 B brotli vs main (was +34/+12/+8 with the helper function). Written by an AI agent (Claude Code). Not reviewed by a human. * feat(experimental): add dev diagnostic for relative locations without a current location Replace the dev warning with VUE_ROUTER_R0127, which states how to fix the call. Production is unchanged: the diagnostic is dev-only (0 B). Written by an AI agent (Claude Code). Not reviewed by a human. * refactor(experimental): detect relative locations without a current route in dev only The router now passes the current route for every relative location and no longer checks START_LOCATION. The dev-only check in the resolver reports VUE_ROUTER_R0127 when the current location is missing or has no route (START_LOCATION, or a no-match current route), instead of throwing 'Record not found'. Experimental size check: -33 B min, -7 B gzip, -4 B brotli vs the previous commit. Smaller than main by 32 B min. Written by an AI agent (Claude Code). Not reviewed by a human. * fix(experimental): use free diagnostic code VUE_ROUTER_R0129 main now uses VUE_ROUTER_R0127 and R0128 for history diagnostics. Written by an AI agent (Claude Code). Not reviewed by a human. * fix: remove query params in relative navigations * fix: keep aliases
1 parent 7e75407 commit ad70a67

6 files changed

Lines changed: 210 additions & 25 deletions

File tree

‎packages/docs/experimental/router-resolver.md‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -78,21 +78,34 @@ An empty array is the same as a missing key: `{ tag: [] }` and `{}` give the sam
7878

7979
## Navigation and redirects
8080

81-
Relative string locations passed to `router.push()`, `router.replace()`, or `router.resolve()` use the current route as their base:
81+
Relative locations passed to `router.push()`, `router.replace()`, `router.resolve()`, or `<RouterLink>` use the current route as their base. A relative location is a string that does not start with `/`, or an object without a `name` and without an absolute `path`:
8282

8383
```ts
8484
// Current route: /users/posva
8585
router.push('add') // /users/add
86+
router.push({ path: 'add' }) // /users/add
8687
```
8788

88-
Relative object locations need an explicit current location. Resolve them first, then navigate:
89+
An object without a `name` or `path` keeps the current params, query, and hash unless the object overrides them. The `query` object is merged with the current query. It does not replace it:
8990

9091
```ts
91-
const target = router.resolve(
92-
{ query: { page: ['2'] } },
93-
router.currentRoute.value
94-
)
95-
router.push(target)
92+
// Each call starts from /search?q=vue#results
93+
router.push({ query: { page: ['2'] } }) // /search?q=vue&page=2#results
94+
router.push({ hash: '#top' }) // /search?q=vue#top
95+
```
96+
97+
To use a different base, pass it as the second argument of `router.resolve()`:
98+
99+
```ts
100+
router.push(router.resolve({ query: { page: ['2'] } }, otherRoute))
101+
```
102+
103+
Named locations do not inherit params, query, or hash from the current route. Use a named location to replace the whole query:
104+
105+
```ts
106+
const route = router.currentRoute.value
107+
router.push({ name: route.name, params: route.params, query: { page: ['2'] } })
108+
// /search?page=2
96109
```
97110

98111
### Navigation guard redirects

‎packages/router/src/diagnostics.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ export const diagnostics = /*#__PURE__*/ defineDiagnostics({
4949
`An error was thrown while matching "${p.path}" against the route "${p.name}". The route is skipped.`,
5050
fix: 'Return null from match() to skip a route, or call miss() in a param parser. Fix the thrown error if it is a bug.',
5151
},
52+
VUE_ROUTER_R0129: {
53+
why: (p: { location: string }) =>
54+
`Cannot resolve relative location ${p.location} without a "name": there is no current location, or the current location has no route. This crashes in production.`,
55+
fix: 'Pass the location it is relative to as the second argument of resolve(), or use a location with a "name" or an absolute "path".',
56+
},
5257
VUE_ROUTER_R0125: {
5358
why: (p: { name: string }) =>
5459
`The params, query, or hash do not match the route "${p.name}".`,

‎packages/router/src/experimental/route-resolver/resolver-fixed.spec.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,15 @@ describe('fixed resolver', () => {
504504
params: { page: 5, q: undefined },
505505
})
506506
})
507+
508+
it('from the query', () => {
509+
expect(
510+
resolver.resolve({ query: { other: undefined } }, current)
511+
).toMatchObject({
512+
fullPath: '/?page=5&q=a#h',
513+
query: { page: ['5'], q: ['a'] },
514+
})
515+
})
507516
})
508517
})
509518

@@ -1522,6 +1531,45 @@ describe('fixed resolver', () => {
15221531
})
15231532
})
15241533

1534+
it('keeps the alias record for relative locations', () => {
1535+
const original = {
1536+
name: 'users',
1537+
path: new MatcherPatternPathStatic('/users'),
1538+
}
1539+
const alias = {
1540+
name: 'users',
1541+
path: new MatcherPatternPathStatic('/people'),
1542+
aliasOf: original,
1543+
}
1544+
const resolver = createFixedResolver([original, alias])
1545+
const current = resolver.resolve('/people')
1546+
1547+
const result = resolver.resolve({ query: { a: ['1'] } }, current)
1548+
expect(result).toMatchObject({
1549+
name: 'users',
1550+
fullPath: '/people?a=1',
1551+
})
1552+
expect(result.matched[0]).toBe(alias)
1553+
})
1554+
1555+
it('uses the original record for named locations from an alias', () => {
1556+
const original = {
1557+
name: 'users',
1558+
path: new MatcherPatternPathStatic('/users'),
1559+
}
1560+
const alias = {
1561+
name: 'users',
1562+
path: new MatcherPatternPathStatic('/people'),
1563+
aliasOf: original,
1564+
}
1565+
const resolver = createFixedResolver([original, alias])
1566+
const current = resolver.resolve('/people')
1567+
1568+
const result = resolver.resolve({ name: 'users', params: {} }, current)
1569+
expect(result.fullPath).toBe('/users')
1570+
expect(result.matched[0]).toBe(original)
1571+
})
1572+
15251573
it('child alias resolves with parent in matched', () => {
15261574
const parent: EXPERIMENTAL_ResolverRecord_Matchable = {
15271575
name: 'parent',

‎packages/router/src/experimental/route-resolver/resolver-fixed.ts‎

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -233,22 +233,20 @@ export function createFixedResolver<
233233
// or relative location (second argument is current location)
234234
if (typeof to === 'object' && (to.name || to.path == null)) {
235235
// relative location by path or by name
236-
if (__DEV__ && to.name == null && currentLocation == null) {
237-
warn(
238-
`Cannot resolve relative location "${JSON.stringify(to)}"without a "name" or a current location. This will crash in production.`,
239-
to
240-
)
236+
// also catches START_LOCATION and no-match current locations
237+
if (
238+
__DEV__ &&
239+
to.name == null &&
240+
!(currentLocation && recordMap.has(currentLocation.name))
241+
) {
242+
diagnostics.VUE_ROUTER_R0129({ location: JSON.stringify(to) })
241243
// NOTE: normally there is no query, hash or path but this helps debug
242244
// what kind of object location was passed
243-
// @ts-expect-error: to is never
244245
const query = normalizeQuery(to.query)
245-
// @ts-expect-error: to is never
246246
const hash = encodeHash(to.hash ?? '')
247-
// @ts-expect-error: to is never
248247
const path = to.path ?? '/'
249248
return {
250-
// type is never
251-
...(to as any),
249+
...to,
252250
...NO_MATCH_LOCATION,
253251
fullPath: stringifyURL(stringifyQuery, path, query, hash),
254252
path,
@@ -257,9 +255,11 @@ export function createFixedResolver<
257255
}
258256
}
259257

260-
// either one of them must be defined and is caught by the dev only warn above
261258
const name = to.name ?? currentLocation!.name
262-
const record = recordMap.get(name)!
259+
// relative locations keep the current (possibly alias) record
260+
const record = to.name
261+
? recordMap.get(name)!
262+
: currentLocation!.matched.at(-1)!
263263

264264
if (__DEV__) {
265265
if (!record || !name) {
@@ -285,11 +285,12 @@ export function createFixedResolver<
285285
)
286286
let matched = buildMatched(record)
287287
// parser.set() can return non array values
288+
// raw `to.query` so an `undefined` value removes the inherited key
288289
const query = normalizeQuery(
289290
assign(
290291
{
291292
...currentLocation?.query,
292-
...normalizeQuery(to.query),
293+
...to.query,
293294
},
294295
...matched.flatMap(record =>
295296
record.query?.map(query => query.build(params))

‎packages/router/src/experimental/router.spec.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,124 @@ describe('Experimental Router', () => {
890890
expect(router.currentRoute.value.path).toBe('/users/add')
891891
})
892892

893+
describe('relative object locations', () => {
894+
// without a current location, these crash in production
895+
it('resolves query, params and hash without a current location argument', async () => {
896+
const { router } = await newRouter()
897+
await router.push('/p/1?a=1#h')
898+
expect(router.resolve({ query: { b: ['2'] } })).toMatchObject({
899+
name: 'Param',
900+
fullPath: '/p/1?a=1&b=2#h',
901+
})
902+
expect(router.resolve({ params: { p: '2' } })).toMatchObject({
903+
name: 'Param',
904+
fullPath: '/p/2?a=1#h',
905+
})
906+
expect(router.resolve({ hash: '#x' })).toMatchObject({
907+
name: 'Param',
908+
fullPath: '/p/1?a=1#x',
909+
})
910+
expect('Cannot resolve relative location').not.toHaveBeenWarned()
911+
})
912+
913+
it('pushes a query against the current route', async () => {
914+
const { router, history } = await newRouter()
915+
await router.push('/search?q=vue#results')
916+
await router.push({ query: { page: ['2'] } })
917+
expect(router.currentRoute.value).toMatchObject({
918+
name: 'search',
919+
fullPath: '/search?q=vue&page=2#results',
920+
})
921+
expect(history.location).toBe('/search?q=vue&page=2#results')
922+
expect('Cannot resolve relative location').not.toHaveBeenWarned()
923+
})
924+
925+
it('replaces with params against the current route', async () => {
926+
const { router, history } = await newRouter()
927+
await router.push('/p/1?a=1')
928+
await router.replace({ params: { p: '2' } })
929+
expect(router.currentRoute.value).toMatchObject({
930+
name: 'Param',
931+
params: { p: '2' },
932+
fullPath: '/p/2?a=1',
933+
})
934+
expect(history.location).toBe('/p/2?a=1')
935+
expect('Cannot resolve relative location').not.toHaveBeenWarned()
936+
})
937+
938+
it('pushes a hash against the current route', async () => {
939+
const { router } = await newRouter()
940+
await router.push('/foo?a=1#old')
941+
await router.push({ hash: '#new' })
942+
expect(router.currentRoute.value.fullPath).toBe('/foo?a=1#new')
943+
expect('Cannot resolve relative location').not.toHaveBeenWarned()
944+
})
945+
946+
it('replaces the whole query with a named location', async () => {
947+
const { router } = await newRouter()
948+
await router.push('/search?q=vue#results')
949+
const route = router.currentRoute.value
950+
await router.push({
951+
name: route.name,
952+
params: route.params,
953+
query: { page: ['2'] },
954+
})
955+
expect(router.currentRoute.value.fullPath).toBe('/search?page=2')
956+
})
957+
958+
it('resolves a relative path against the current route', async () => {
959+
const { router } = await newRouter()
960+
await router.push('/users/posva')
961+
expect(router.resolve({ path: 'add' }).path).toBe('/users/add')
962+
expect(router.resolve({ path: '../add' }).path).toBe('/add')
963+
})
964+
965+
it('uses a passed currentLocation over the current route', async () => {
966+
const { router } = await newRouter()
967+
const current = await loadRouteLocation(router.resolve('/p/1?a=1'))
968+
await router.push('/foo')
969+
expect(router.resolve({ query: { b: ['2'] } }, current).fullPath).toBe(
970+
'/p/1?a=1&b=2'
971+
)
972+
})
973+
974+
it('re-runs a computed on navigation', async () => {
975+
const { router } = await newRouter()
976+
const scope = effectScope()
977+
const route = scope.run(() =>
978+
computed(() => router.resolve({ query: { page: ['2'] } }))
979+
)!
980+
expect(route.value.fullPath).toBe('/?page=2')
981+
await router.push('/search?q=vue')
982+
expect(route.value.fullPath).toBe('/search?q=vue&page=2')
983+
scope.stop()
984+
})
985+
986+
it('warns before the initial navigation', () => {
987+
const router = experimental_createRouter({
988+
history: createMemoryHistory(),
989+
resolver: createFixedResolver(experimentalRoutes),
990+
})
991+
expect(router.resolve({ query: { page: ['2'] } }).matched).toEqual([])
992+
expect('VUE_ROUTER_R0129').toHaveBeenWarnedTimes(1)
993+
expect('Cannot resolve relative location').toHaveBeenWarned()
994+
expect('No match found').toHaveBeenWarned()
995+
})
996+
997+
it('warns when the current route does not match', async () => {
998+
const { router } = await newRouter({
999+
resolver: createFixedResolver(
1000+
experimentalRoutes.filter(record => record.name !== 'catch-all')
1001+
),
1002+
})
1003+
await router.push('/does-not-exist')
1004+
expect(router.currentRoute.value.matched).toEqual([])
1005+
expect(router.resolve({ query: { page: ['2'] } }).matched).toEqual([])
1006+
expect('VUE_ROUTER_R0129').toHaveBeenWarnedTimes(1)
1007+
expect('No match found').toHaveBeenWarned()
1008+
})
1009+
})
1010+
8931011
it('resolves parent relative string locations', async () => {
8941012
const { router } = await newRouter()
8951013
await router.push('/users/posva')

‎packages/router/src/experimental/router.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ import type {
7777
} from './route-resolver/resolver-fixed'
7878
import { isAbsoluteLocation } from './route-resolver/resolver-abstract'
7979
import type {
80+
MatcherLocationRaw,
8081
ResolverLocationAsNamed,
8182
ResolverLocationAsPathRelative,
8283
ResolverLocationAsRelative,
@@ -735,11 +736,10 @@ export function experimental_createRouter(
735736
to,
736737
// FIXME: incompatible `matched` requires casting
737738
currentLocation ??
738-
// relative string locations are always valid
739-
// so this is more of a convenience default
740-
(typeof to === 'string' && !to.startsWith('/')
741-
? currentRoute.value
742-
: undefined)
739+
// absolute locations skip currentRoute to not track it
740+
(isAbsoluteLocation(to as MatcherLocationRaw)
741+
? undefined
742+
: currentRoute.value)
743743
)
744744
const href = routerHistory.createHref(matchedRoute.fullPath)
745745

0 commit comments

Comments
 (0)