-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathrouter.ts
1358 lines (1246 loc) · 43.3 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
RouteRecordRaw,
Lazy,
isRouteLocation,
isRouteName,
RouteLocationOptions,
MatcherLocationRaw,
} from './types'
import type {
RouteLocation,
RouteLocationRaw,
RouteParams,
RouteLocationNormalized,
RouteLocationNormalizedLoaded,
NavigationGuardWithThis,
NavigationHookAfter,
RouteLocationResolved,
RouteLocationAsRelative,
RouteLocationAsPath,
RouteLocationAsString,
RouteRecordNameGeneric,
} from './typed-routes'
import { RouterHistory, HistoryState, NavigationType } from './history/common'
import {
ScrollPosition,
getSavedScrollPosition,
getScrollKey,
saveScrollPosition,
computeScrollPosition,
scrollToPosition,
_ScrollPositionNormalized,
} from './scrollBehavior'
import { createRouterMatcher, PathParserOptions } from './matcher'
import {
createRouterError,
ErrorTypes,
NavigationFailure,
NavigationRedirectError,
isNavigationFailure,
} from './errors'
import { applyToParams, isBrowser, assign, noop, isArray } from './utils'
import { useCallbacks } from './utils/callbacks'
import { encodeParam, decode, encodeHash } from './encoding'
import {
normalizeQuery,
parseQuery as originalParseQuery,
stringifyQuery as originalStringifyQuery,
LocationQuery,
} from './query'
import { shallowRef, Ref, nextTick, App, unref, shallowReactive } from 'vue'
import { RouteRecord, RouteRecordNormalized } from './matcher/types'
import {
parseURL,
stringifyURL,
isSameRouteLocation,
isSameRouteRecord,
START_LOCATION_NORMALIZED,
} from './location'
import { extractComponentsGuards, guardToPromiseFn } from './navigationGuards'
import { warn } from './warning'
import { RouterLink } from './RouterLink'
import { RouterView } from './RouterView'
import {
routeLocationKey,
routerKey,
routerViewLocationKey,
} from './injectionSymbols'
import { addDevtools } from './devtools'
import { _LiteralUnion } from './types/utils'
import { RouteLocationAsRelativeTyped } from './typed-routes/route-location'
import { RouteMap } from './typed-routes/route-map'
/**
* Internal type to define an ErrorHandler
*
* @param error - error thrown
* @param to - location we were navigating to when the error happened
* @param from - location we were navigating from when the error happened
* @internal
*/
export interface _ErrorListener {
(
error: any,
to: RouteLocationNormalized,
from: RouteLocationNormalizedLoaded
): any
}
// resolve, reject arguments of Promise constructor
type OnReadyCallback = [() => void, (reason?: any) => void]
type Awaitable<T> = T | Promise<T>
/**
* Type of the `scrollBehavior` option that can be passed to `createRouter`.
*/
export interface RouterScrollBehavior {
/**
* @param to - Route location where we are navigating to
* @param from - Route location where we are navigating from
* @param savedPosition - saved position if it exists, `null` otherwise
*/
(
to: RouteLocationNormalized,
from: RouteLocationNormalizedLoaded,
savedPosition: _ScrollPositionNormalized | null
): Awaitable<ScrollPosition | false | void>
}
/**
* Options to initialize a {@link Router} instance.
*/
export interface RouterOptions extends PathParserOptions {
/**
* History implementation used by the router. Most web applications should use
* `createWebHistory` but it requires the server to be properly configured.
* You can also use a _hash_ based history with `createWebHashHistory` that
* does not require any configuration on the server but isn't handled at all
* by search engines and does poorly on SEO.
*
* @example
* ```js
* createRouter({
* history: createWebHistory(),
* // other options...
* })
* ```
*/
history: RouterHistory
/**
* Initial list of routes that should be added to the router.
*/
routes: Readonly<RouteRecordRaw[]>
/**
* Function to control scrolling when navigating between pages. Can return a
* Promise to delay scrolling. Check {@link ScrollBehavior}.
*
* @example
* ```js
* function scrollBehavior(to, from, savedPosition) {
* // `to` and `from` are both route locations
* // `savedPosition` can be null if there isn't one
* }
* ```
*/
scrollBehavior?: RouterScrollBehavior
/**
* Custom implementation to parse a query. See its counterpart,
* {@link RouterOptions.stringifyQuery}.
*
* @example
* Let's say you want to use the [qs package](https://github.com/ljharb/qs)
* to parse queries, you can provide both `parseQuery` and `stringifyQuery`:
* ```js
* import qs from 'qs'
*
* createRouter({
* // other options...
* parseQuery: qs.parse,
* stringifyQuery: qs.stringify,
* })
* ```
*/
parseQuery?: typeof originalParseQuery
/**
* Custom implementation to stringify a query object. Should not prepend a leading `?`.
* {@link RouterOptions.parseQuery | parseQuery} counterpart to handle query parsing.
*/
stringifyQuery?: typeof originalStringifyQuery
/**
* Default class applied to active {@link RouterLink}. If none is provided,
* `router-link-active` will be applied.
*/
linkActiveClass?: string
/**
* Default class applied to exact active {@link RouterLink}. If none is provided,
* `router-link-exact-active` will be applied.
*/
linkExactActiveClass?: string
/**
* Default class applied to non-active {@link RouterLink}. If none is provided,
* `router-link-inactive` will be applied.
*/
// linkInactiveClass?: string
}
/**
* Router instance.
*/
export interface Router {
/**
* @internal
*/
// readonly history: RouterHistory
/**
* Current {@link RouteLocationNormalized}
*/
readonly currentRoute: Ref<RouteLocationNormalizedLoaded>
/**
* Original options object passed to create the Router
*/
readonly options: RouterOptions
/**
* Allows turning off the listening of history events. This is a low level api for micro-frontend.
*/
listening: boolean
/**
* Add a new {@link RouteRecordRaw | route record} as the child of an existing route.
*
* @param parentName - Parent Route Record where `route` should be appended at
* @param route - Route Record to add
*/
addRoute(
// NOTE: it could be `keyof RouteMap` but the point of dynamic routes is not knowing the routes at build
parentName: NonNullable<RouteRecordNameGeneric>,
route: RouteRecordRaw
): () => void
/**
* Add a new {@link RouteRecordRaw | route record} to the router.
*
* @param route - Route Record to add
*/
addRoute(route: RouteRecordRaw): () => void
/**
* Remove an existing route by its name.
*
* @param name - Name of the route to remove
*/
removeRoute(name: NonNullable<RouteRecordNameGeneric>): void
/**
* Checks if a route with a given name exists
*
* @param name - Name of the route to check
*/
hasRoute(name: NonNullable<RouteRecordNameGeneric>): boolean
/**
* Get a full list of all the {@link RouteRecord | route records}.
*/
getRoutes(): RouteRecord[]
/**
* Delete all routes from the router matcher.
*/
clearRoutes(): void
/**
* Returns the {@link RouteLocation | normalized version} of a
* {@link RouteLocationRaw | route location}. Also includes an `href` property
* that includes any existing `base`. By default, the `currentLocation` used is
* `router.currentRoute` and should only be overridden in advanced use cases.
*
* @param to - Raw route location to resolve
* @param currentLocation - Optional current location to resolve against
*/
resolve<Name extends keyof RouteMap = keyof RouteMap>(
to: RouteLocationAsRelativeTyped<RouteMap, Name>,
// NOTE: This version doesn't work probably because it infers the type too early
// | RouteLocationAsRelative<Name>
currentLocation?: RouteLocationNormalizedLoaded
): RouteLocationResolved<Name>
resolve(
// not having the overload produces errors in RouterLink calls to router.resolve()
to: RouteLocationAsString | RouteLocationAsRelative | RouteLocationAsPath,
currentLocation?: RouteLocationNormalizedLoaded
): RouteLocationResolved
/**
* Programmatically navigate to a new URL by pushing an entry in the history
* stack.
*
* @param to - Route location to navigate to
*/
push(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>
/**
* Programmatically navigate to a new URL by replacing the current entry in
* the history stack.
*
* @param to - Route location to navigate to
*/
replace(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>
/**
* Go back in history if possible by calling `history.back()`. Equivalent to
* `router.go(-1)`.
*/
back(): ReturnType<Router['go']>
/**
* Go forward in history if possible by calling `history.forward()`.
* Equivalent to `router.go(1)`.
*/
forward(): ReturnType<Router['go']>
/**
* Allows you to move forward or backward through the history. Calls
* `history.go()`.
*
* @param delta - The position in the history to which you want to move,
* relative to the current page
*/
go(delta: number): void
/**
* Add a navigation guard that executes before any navigation. Returns a
* function that removes the registered guard.
*
* @param guard - navigation guard to add
*/
beforeEach(guard: NavigationGuardWithThis<undefined>): () => void
/**
* Add a navigation guard that executes before navigation is about to be
* resolved. At this state all component have been fetched and other
* navigation guards have been successful. Returns a function that removes the
* registered guard.
*
* @param guard - navigation guard to add
* @returns a function that removes the registered guard
*
* @example
* ```js
* router.beforeResolve(to => {
* if (to.meta.requiresAuth && !isAuthenticated) return false
* })
* ```
*
*/
beforeResolve(guard: NavigationGuardWithThis<undefined>): () => void
/**
* Add a navigation hook that is executed after every navigation. Returns a
* function that removes the registered hook.
*
* @param guard - navigation hook to add
* @returns a function that removes the registered hook
*
* @example
* ```js
* router.afterEach((to, from, failure) => {
* if (isNavigationFailure(failure)) {
* console.log('failed navigation', failure)
* }
* })
* ```
*/
afterEach(guard: NavigationHookAfter): () => void
/**
* Adds an error handler that is called every time a non caught error happens
* during navigation. This includes errors thrown synchronously and
* asynchronously, errors returned or passed to `next` in any navigation
* guard, and errors occurred when trying to resolve an async component that
* is required to render a route.
*
* @param handler - error handler to register
*/
onError(handler: _ErrorListener): () => void
/**
* Returns a Promise that resolves when the router has completed the initial
* navigation, which means it has resolved all async enter hooks and async
* components that are associated with the initial route. If the initial
* navigation already happened, the promise resolves immediately.
*
* This is useful in server-side rendering to ensure consistent output on both
* the server and the client. Note that on server side, you need to manually
* push the initial location while on client side, the router automatically
* picks it up from the URL.
*/
isReady(): Promise<void>
/**
* Called automatically by `app.use(router)`. Should not be called manually by
* the user. This will trigger the initial navigation when on client side.
*
* @internal
* @param app - Application that uses the router
*/
install(app: App): void
}
/**
* Creates a Router instance that can be used by a Vue app.
*
* @param options - {@link RouterOptions}
*/
export function createRouter(options: RouterOptions): Router {
const matcher = createRouterMatcher(options.routes, options)
const parseQuery = options.parseQuery || originalParseQuery
const stringifyQuery = options.stringifyQuery || originalStringifyQuery
const routerHistory = options.history
if (__DEV__ && !routerHistory)
throw new Error(
'Provide the "history" option when calling "createRouter()":' +
' https://router.vuejs.org/api/interfaces/RouterOptions.html#history'
)
const beforeGuards = useCallbacks<NavigationGuardWithThis<undefined>>()
const beforeResolveGuards = useCallbacks<NavigationGuardWithThis<undefined>>()
const afterGuards = useCallbacks<NavigationHookAfter>()
const currentRoute = shallowRef<RouteLocationNormalizedLoaded>(
START_LOCATION_NORMALIZED
)
let pendingLocation: RouteLocation = START_LOCATION_NORMALIZED
// leave the scrollRestoration if no scrollBehavior is provided
if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) {
history.scrollRestoration = 'manual'
}
const normalizeParams = applyToParams.bind(
null,
paramValue => '' + paramValue
)
const encodeParams = applyToParams.bind(null, encodeParam)
const decodeParams: (params: RouteParams | undefined) => RouteParams =
// @ts-expect-error: intentionally avoid the type check
applyToParams.bind(null, decode)
function addRoute(
parentOrRoute: NonNullable<RouteRecordNameGeneric> | RouteRecordRaw,
route?: RouteRecordRaw
) {
let parent: Parameters<(typeof matcher)['addRoute']>[1] | undefined
let record: RouteRecordRaw
if (isRouteName(parentOrRoute)) {
parent = matcher.getRecordMatcher(parentOrRoute)
if (__DEV__ && !parent) {
warn(
`Parent route "${String(
parentOrRoute
)}" not found when adding child route`,
route
)
}
record = route!
} else {
record = parentOrRoute
}
return matcher.addRoute(record, parent)
}
function removeRoute(name: NonNullable<RouteRecordNameGeneric>) {
const recordMatcher = matcher.getRecordMatcher(name)
if (recordMatcher) {
matcher.removeRoute(recordMatcher)
} else if (__DEV__) {
warn(`Cannot remove non-existent route "${String(name)}"`)
}
}
function getRoutes() {
return matcher.getRoutes().map(routeMatcher => routeMatcher.record)
}
function hasRoute(name: NonNullable<RouteRecordNameGeneric>): boolean {
return !!matcher.getRecordMatcher(name)
}
function resolve(
rawLocation: RouteLocationRaw,
currentLocation?: RouteLocationNormalizedLoaded
): RouteLocationResolved {
// const resolve: Router['resolve'] = (rawLocation: RouteLocationRaw, currentLocation) => {
// const objectLocation = routerLocationAsObject(rawLocation)
// we create a copy to modify it later
currentLocation = assign({}, currentLocation || currentRoute.value)
if (typeof rawLocation === 'string') {
const locationNormalized = parseURL(
parseQuery,
rawLocation,
currentLocation.path
)
const matchedRoute = matcher.resolve(
{ path: locationNormalized.path },
currentLocation
)
const href = routerHistory.createHref(locationNormalized.fullPath)
if (__DEV__) {
if (href.startsWith('//'))
warn(
`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`
)
else if (!matchedRoute.matched.length) {
warn(`No match found for location with path "${rawLocation}"`)
}
}
// locationNormalized is always a new object
return assign(locationNormalized, matchedRoute, {
params: decodeParams(matchedRoute.params),
hash: decode(locationNormalized.hash),
redirectedFrom: undefined,
href,
})
}
if (__DEV__ && !isRouteLocation(rawLocation)) {
warn(
`router.resolve() was passed an invalid location. This will fail in production.\n- Location:`,
rawLocation
)
return resolve({})
}
let matcherLocation: MatcherLocationRaw
// path could be relative in object as well
if (rawLocation.path != null) {
if (
__DEV__ &&
'params' in rawLocation &&
!('name' in rawLocation) &&
// @ts-expect-error: the type is never
Object.keys(rawLocation.params).length
) {
warn(
`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`
)
}
matcherLocation = assign({}, rawLocation, {
path: parseURL(parseQuery, rawLocation.path, currentLocation.path).path,
})
} else {
// remove any nullish param
const targetParams = assign({}, rawLocation.params)
for (const key in targetParams) {
if (targetParams[key] == null) {
delete targetParams[key]
}
}
// pass encoded values to the matcher, so it can produce encoded path and fullPath
matcherLocation = assign({}, rawLocation, {
params: encodeParams(targetParams),
})
// current location params are decoded, we need to encode them in case the
// matcher merges the params
currentLocation.params = encodeParams(currentLocation.params)
}
const matchedRoute = matcher.resolve(matcherLocation, currentLocation)
const hash = rawLocation.hash || ''
if (__DEV__ && hash && !hash.startsWith('#')) {
warn(
`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`
)
}
// the matcher might have merged current location params, so
// we need to run the decoding again
matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params))
const fullPath = stringifyURL(
stringifyQuery,
assign({}, rawLocation, {
hash: encodeHash(hash),
path: matchedRoute.path,
})
)
const href = routerHistory.createHref(fullPath)
if (__DEV__) {
if (href.startsWith('//')) {
warn(
`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`
)
} else if (!matchedRoute.matched.length) {
warn(
`No match found for location with path "${
rawLocation.path != null ? rawLocation.path : rawLocation
}"`
)
}
}
return assign(
{
fullPath,
// keep the hash encoded so fullPath is effectively path + encodedQuery +
// hash
hash,
query:
// if the user is using a custom query lib like qs, we might have
// nested objects, so we keep the query as is, meaning it can contain
// numbers at `$route.query`, but at the point, the user will have to
// use their own type anyway.
// https://github.com/vuejs/router/issues/328#issuecomment-649481567
stringifyQuery === originalStringifyQuery
? normalizeQuery(rawLocation.query)
: ((rawLocation.query || {}) as LocationQuery),
},
matchedRoute,
{
redirectedFrom: undefined,
href,
}
)
}
function locationAsObject(
to: RouteLocationRaw | RouteLocationNormalized
): Exclude<RouteLocationRaw, string> | RouteLocationNormalized {
return typeof to === 'string'
? parseURL(parseQuery, to, currentRoute.value.path)
: assign({}, to)
}
function checkCanceledNavigation(
to: RouteLocationNormalized,
from: RouteLocationNormalized
): NavigationFailure | void {
if (pendingLocation !== to) {
return createRouterError<NavigationFailure>(
ErrorTypes.NAVIGATION_CANCELLED,
{
from,
to,
}
)
}
}
function push(to: RouteLocationRaw) {
return pushWithRedirect(to)
}
function replace(to: RouteLocationRaw) {
return push(assign(locationAsObject(to), { replace: true }))
}
function handleRedirectRecord(to: RouteLocation): RouteLocationRaw | void {
const lastMatched = to.matched[to.matched.length - 1]
if (lastMatched && lastMatched.redirect) {
const { redirect } = lastMatched
let newTargetLocation =
typeof redirect === 'function' ? redirect(to) : redirect
if (typeof newTargetLocation === 'string') {
newTargetLocation =
newTargetLocation.includes('?') || newTargetLocation.includes('#')
? (newTargetLocation = locationAsObject(newTargetLocation))
: // force empty params
{ path: newTargetLocation }
// @ts-expect-error: force empty params when a string is passed to let
// the router parse them again
newTargetLocation.params = {}
}
if (
__DEV__ &&
newTargetLocation.path == null &&
!('name' in newTargetLocation)
) {
warn(
`Invalid redirect found:\n${JSON.stringify(
newTargetLocation,
null,
2
)}\n when navigating to "${
to.fullPath
}". A redirect must contain a name or path. This will break in production.`
)
throw new Error('Invalid redirect')
}
return assign(
{
query: to.query,
hash: to.hash,
// avoid transferring params if the redirect has a path
params: newTargetLocation.path != null ? {} : to.params,
},
newTargetLocation
)
}
}
function pushWithRedirect(
to: RouteLocationRaw | RouteLocation,
redirectedFrom?: RouteLocation
): Promise<NavigationFailure | void | undefined> {
const targetLocation: RouteLocation = (pendingLocation = resolve(to))
const from = currentRoute.value
const data: HistoryState | undefined = (to as RouteLocationOptions).state
const force: boolean | undefined = (to as RouteLocationOptions).force
// to could be a string where `replace` is a function
const replace = (to as RouteLocationOptions).replace === true
const shouldRedirect = handleRedirectRecord(targetLocation)
if (shouldRedirect)
return pushWithRedirect(
assign(locationAsObject(shouldRedirect), {
state:
typeof shouldRedirect === 'object'
? assign({}, data, shouldRedirect.state)
: data,
force,
replace,
}),
// keep original redirectedFrom if it exists
redirectedFrom || targetLocation
)
// if it was a redirect we already called `pushWithRedirect` above
const toLocation = targetLocation as RouteLocationNormalized
toLocation.redirectedFrom = redirectedFrom
let failure: NavigationFailure | void | undefined
if (!force && isSameRouteLocation(stringifyQuery, from, targetLocation)) {
failure = createRouterError<NavigationFailure>(
ErrorTypes.NAVIGATION_DUPLICATED,
{ to: toLocation, from }
)
// trigger scroll to allow scrolling to the same anchor
handleScroll(
from,
from,
// this is a push, the only way for it to be triggered from a
// history.listen is with a redirect, which makes it become a push
true,
// This cannot be the first navigation because the initial location
// cannot be manually navigated to
false
)
}
return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
.catch((error: NavigationFailure | NavigationRedirectError) =>
isNavigationFailure(error)
? // navigation redirects still mark the router as ready
isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT)
? error
: markAsReady(error) // also returns the error
: // reject any unknown error
triggerError(error, toLocation, from)
)
.then((failure: NavigationFailure | NavigationRedirectError | void) => {
if (failure) {
if (
isNavigationFailure(failure, ErrorTypes.NAVIGATION_GUARD_REDIRECT)
) {
if (
__DEV__ &&
// we are redirecting to the same location we were already at
isSameRouteLocation(
stringifyQuery,
resolve(failure.to),
toLocation
) &&
// and we have done it a couple of times
redirectedFrom &&
// @ts-expect-error: added only in dev
(redirectedFrom._count = redirectedFrom._count
? // @ts-expect-error
redirectedFrom._count + 1
: 1) > 30
) {
warn(
`Detected a possibly infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow.\n Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.`
)
return Promise.reject(
new Error('Infinite redirect in navigation guard')
)
}
return pushWithRedirect(
// keep options
assign(
{
// preserve an existing replacement but allow the redirect to override it
replace,
},
locationAsObject(failure.to),
{
state:
typeof failure.to === 'object'
? assign({}, data, failure.to.state)
: data,
force,
}
),
// preserve the original redirectedFrom if any
redirectedFrom || toLocation
)
}
} else {
// if we fail we don't finalize the navigation
failure = finalizeNavigation(
toLocation as RouteLocationNormalizedLoaded,
from,
true,
replace,
data
)
}
triggerAfterEach(
toLocation as RouteLocationNormalizedLoaded,
from,
failure
)
return failure
})
}
/**
* Helper to reject and skip all navigation guards if a new navigation happened
* @param to
* @param from
*/
function checkCanceledNavigationAndReject(
to: RouteLocationNormalized,
from: RouteLocationNormalized
): Promise<void> {
const error = checkCanceledNavigation(to, from)
return error ? Promise.reject(error) : Promise.resolve()
}
function runWithContext<T>(fn: () => T): T {
const app: App | undefined = installedApps.values().next().value
// support Vue < 3.3
return app && typeof app.runWithContext === 'function'
? app.runWithContext(fn)
: fn()
}
// TODO: refactor the whole before guards by internally using router.beforeEach
function navigate(
to: RouteLocationNormalized,
from: RouteLocationNormalizedLoaded
): Promise<any> {
let guards: Lazy<any>[]
const [leavingRecords, updatingRecords, enteringRecords] =
extractChangingRecords(to, from)
// all components here have been resolved once because we are leaving
guards = extractComponentsGuards(
leavingRecords.reverse(),
'beforeRouteLeave',
to,
from
)
// leavingRecords is already reversed
for (const record of leavingRecords) {
record.leaveGuards.forEach(guard => {
guards.push(guardToPromiseFn(guard, to, from))
})
}
const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(
null,
to,
from
)
guards.push(canceledNavigationCheck)
// run the queue of per route beforeRouteLeave guards
return (
runGuardQueue(guards)
.then(() => {
// check global guards beforeEach
guards = []
for (const guard of beforeGuards.list()) {
guards.push(guardToPromiseFn(guard, to, from))
}
guards.push(canceledNavigationCheck)
return runGuardQueue(guards)
})
.then(() => {
// check in components beforeRouteUpdate
guards = extractComponentsGuards(
updatingRecords,
'beforeRouteUpdate',
to,
from
)
for (const record of updatingRecords) {
record.updateGuards.forEach(guard => {
guards.push(guardToPromiseFn(guard, to, from))
})
}
guards.push(canceledNavigationCheck)
// run the queue of per route beforeEnter guards
return runGuardQueue(guards)
})
.then(() => {
// check the route beforeEnter
guards = []
for (const record of enteringRecords) {
// do not trigger beforeEnter on reused views
if (record.beforeEnter) {
if (isArray(record.beforeEnter)) {
for (const beforeEnter of record.beforeEnter)
guards.push(guardToPromiseFn(beforeEnter, to, from))
} else {
guards.push(guardToPromiseFn(record.beforeEnter, to, from))
}
}
}
guards.push(canceledNavigationCheck)
// run the queue of per route beforeEnter guards
return runGuardQueue(guards)
})
.then(() => {
// NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
// clear existing enterCallbacks, these are added by extractComponentsGuards
to.matched.forEach(record => (record.enterCallbacks = {}))
// check in-component beforeRouteEnter
guards = extractComponentsGuards(
enteringRecords,
'beforeRouteEnter',
to,
from,
runWithContext
)
guards.push(canceledNavigationCheck)
// run the queue of per route beforeEnter guards
return runGuardQueue(guards)
})
.then(() => {
// check global guards beforeResolve
guards = []
for (const guard of beforeResolveGuards.list()) {
guards.push(guardToPromiseFn(guard, to, from))
}
guards.push(canceledNavigationCheck)
return runGuardQueue(guards)
})
// catch any navigation canceled
.catch(err =>
isNavigationFailure(err, ErrorTypes.NAVIGATION_CANCELLED)
? err
: Promise.reject(err)
)
)
}
function triggerAfterEach(
to: RouteLocationNormalizedLoaded,
from: RouteLocationNormalizedLoaded,
failure?: NavigationFailure | void
): void {
// navigation is confirmed, call afterGuards
// TODO: wrap with error handlers
afterGuards
.list()
.forEach(guard => runWithContext(() => guard(to, from, failure)))
}
/**
* - Cleans up any navigation guards
* - Changes the url if necessary
* - Calls the scrollBehavior
*/
function finalizeNavigation(
toLocation: RouteLocationNormalizedLoaded,
from: RouteLocationNormalizedLoaded,
isPush: boolean,
replace?: boolean,
data?: HistoryState
): NavigationFailure | void {
// a more recent navigation took place
const error = checkCanceledNavigation(toLocation, from)
if (error) return error
// only consider as push if it's not the first navigation
const isFirstNavigation = from === START_LOCATION_NORMALIZED
const state: Partial<HistoryState> | null = !isBrowser ? {} : history.state
// change URL only if the user did a push/replace and if it's not the initial navigation because
// it's just reflecting the url
if (isPush) {
// on the initial navigation, we want to reuse the scroll position from
// history state if it exists
if (replace || isFirstNavigation)
routerHistory.replace(
toLocation.fullPath,
assign(
{
scroll: isFirstNavigation && state && state.scroll,
},
data
)
)
else routerHistory.push(toLocation.fullPath, data)
}