@histoire/vendors 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3465 @@
1
+ import { I as onUnmounted, N as onDeactivated, O as onActivated, y as getCurrentInstance, z as inject, K as computed, B as unref, P as watchEffect, d as defineComponent, L as reactive, x as h, Q as provide, u as ref, A as watch, R as shallowRef, a as nextTick } from './vue.runtime.esm-bundler.js';
2
+ import { s as setupDevtoolsPlugin } from './index2.js';
3
+
4
+ /*!
5
+ * vue-router v4.0.15
6
+ * (c) 2022 Eduardo San Martin Morote
7
+ * @license MIT
8
+ */
9
+
10
+ const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
11
+ const PolySymbol = (name) =>
12
+ // vr = vue router
13
+ hasSymbol
14
+ ? Symbol((process.env.NODE_ENV !== 'production') ? '[vue-router]: ' + name : name)
15
+ : ((process.env.NODE_ENV !== 'production') ? '[vue-router]: ' : '_vr_') + name;
16
+ // rvlm = Router View Location Matched
17
+ /**
18
+ * RouteRecord being rendered by the closest ancestor Router View. Used for
19
+ * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View
20
+ * Location Matched
21
+ *
22
+ * @internal
23
+ */
24
+ const matchedRouteKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view location matched' : 'rvlm');
25
+ /**
26
+ * Allows overriding the router view depth to control which component in
27
+ * `matched` is rendered. rvd stands for Router View Depth
28
+ *
29
+ * @internal
30
+ */
31
+ const viewDepthKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view depth' : 'rvd');
32
+ /**
33
+ * Allows overriding the router instance returned by `useRouter` in tests. r
34
+ * stands for router
35
+ *
36
+ * @internal
37
+ */
38
+ const routerKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router' : 'r');
39
+ /**
40
+ * Allows overriding the current route returned by `useRoute` in tests. rl
41
+ * stands for route location
42
+ *
43
+ * @internal
44
+ */
45
+ const routeLocationKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'route location' : 'rl');
46
+ /**
47
+ * Allows overriding the current route used by router-view. Internally this is
48
+ * used when the `route` prop is passed.
49
+ *
50
+ * @internal
51
+ */
52
+ const routerViewLocationKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view location' : 'rvl');
53
+
54
+ const isBrowser = typeof window !== 'undefined';
55
+
56
+ function isESModule(obj) {
57
+ return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module');
58
+ }
59
+ const assign = Object.assign;
60
+ function applyToParams(fn, params) {
61
+ const newParams = {};
62
+ for (const key in params) {
63
+ const value = params[key];
64
+ newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value);
65
+ }
66
+ return newParams;
67
+ }
68
+ const noop = () => { };
69
+
70
+ function warn(msg) {
71
+ // avoid using ...args as it breaks in older Edge builds
72
+ const args = Array.from(arguments).slice(1);
73
+ console.warn.apply(console, ['[Vue Router warn]: ' + msg].concat(args));
74
+ }
75
+
76
+ const TRAILING_SLASH_RE = /\/$/;
77
+ const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, '');
78
+ /**
79
+ * Transforms an URI into a normalized history location
80
+ *
81
+ * @param parseQuery
82
+ * @param location - URI to normalize
83
+ * @param currentLocation - current absolute location. Allows resolving relative
84
+ * paths. Must start with `/`. Defaults to `/`
85
+ * @returns a normalized history location
86
+ */
87
+ function parseURL(parseQuery, location, currentLocation = '/') {
88
+ let path, query = {}, searchString = '', hash = '';
89
+ // Could use URL and URLSearchParams but IE 11 doesn't support it
90
+ const searchPos = location.indexOf('?');
91
+ const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0);
92
+ if (searchPos > -1) {
93
+ path = location.slice(0, searchPos);
94
+ searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length);
95
+ query = parseQuery(searchString);
96
+ }
97
+ if (hashPos > -1) {
98
+ path = path || location.slice(0, hashPos);
99
+ // keep the # character
100
+ hash = location.slice(hashPos, location.length);
101
+ }
102
+ // no search and no query
103
+ path = resolveRelativePath(path != null ? path : location, currentLocation);
104
+ // empty path means a relative query or hash `?foo=f`, `#thing`
105
+ return {
106
+ fullPath: path + (searchString && '?') + searchString + hash,
107
+ path,
108
+ query,
109
+ hash,
110
+ };
111
+ }
112
+ /**
113
+ * Stringifies a URL object
114
+ *
115
+ * @param stringifyQuery
116
+ * @param location
117
+ */
118
+ function stringifyURL(stringifyQuery, location) {
119
+ const query = location.query ? stringifyQuery(location.query) : '';
120
+ return location.path + (query && '?') + query + (location.hash || '');
121
+ }
122
+ /**
123
+ * Strips off the base from the beginning of a location.pathname in a non
124
+ * case-sensitive way.
125
+ *
126
+ * @param pathname - location.pathname
127
+ * @param base - base to strip off
128
+ */
129
+ function stripBase(pathname, base) {
130
+ // no base or base is not found at the beginning
131
+ if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase()))
132
+ return pathname;
133
+ return pathname.slice(base.length) || '/';
134
+ }
135
+ /**
136
+ * Checks if two RouteLocation are equal. This means that both locations are
137
+ * pointing towards the same {@link RouteRecord} and that all `params`, `query`
138
+ * parameters and `hash` are the same
139
+ *
140
+ * @param a - first {@link RouteLocation}
141
+ * @param b - second {@link RouteLocation}
142
+ */
143
+ function isSameRouteLocation(stringifyQuery, a, b) {
144
+ const aLastIndex = a.matched.length - 1;
145
+ const bLastIndex = b.matched.length - 1;
146
+ return (aLastIndex > -1 &&
147
+ aLastIndex === bLastIndex &&
148
+ isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) &&
149
+ isSameRouteLocationParams(a.params, b.params) &&
150
+ stringifyQuery(a.query) === stringifyQuery(b.query) &&
151
+ a.hash === b.hash);
152
+ }
153
+ /**
154
+ * Check if two `RouteRecords` are equal. Takes into account aliases: they are
155
+ * considered equal to the `RouteRecord` they are aliasing.
156
+ *
157
+ * @param a - first {@link RouteRecord}
158
+ * @param b - second {@link RouteRecord}
159
+ */
160
+ function isSameRouteRecord(a, b) {
161
+ // since the original record has an undefined value for aliasOf
162
+ // but all aliases point to the original record, this will always compare
163
+ // the original record
164
+ return (a.aliasOf || a) === (b.aliasOf || b);
165
+ }
166
+ function isSameRouteLocationParams(a, b) {
167
+ if (Object.keys(a).length !== Object.keys(b).length)
168
+ return false;
169
+ for (const key in a) {
170
+ if (!isSameRouteLocationParamsValue(a[key], b[key]))
171
+ return false;
172
+ }
173
+ return true;
174
+ }
175
+ function isSameRouteLocationParamsValue(a, b) {
176
+ return Array.isArray(a)
177
+ ? isEquivalentArray(a, b)
178
+ : Array.isArray(b)
179
+ ? isEquivalentArray(b, a)
180
+ : a === b;
181
+ }
182
+ /**
183
+ * Check if two arrays are the same or if an array with one single entry is the
184
+ * same as another primitive value. Used to check query and parameters
185
+ *
186
+ * @param a - array of values
187
+ * @param b - array of values or a single value
188
+ */
189
+ function isEquivalentArray(a, b) {
190
+ return Array.isArray(b)
191
+ ? a.length === b.length && a.every((value, i) => value === b[i])
192
+ : a.length === 1 && a[0] === b;
193
+ }
194
+ /**
195
+ * Resolves a relative path that starts with `.`.
196
+ *
197
+ * @param to - path location we are resolving
198
+ * @param from - currentLocation.path, should start with `/`
199
+ */
200
+ function resolveRelativePath(to, from) {
201
+ if (to.startsWith('/'))
202
+ return to;
203
+ if ((process.env.NODE_ENV !== 'production') && !from.startsWith('/')) {
204
+ warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
205
+ return to;
206
+ }
207
+ if (!to)
208
+ return from;
209
+ const fromSegments = from.split('/');
210
+ const toSegments = to.split('/');
211
+ let position = fromSegments.length - 1;
212
+ let toPosition;
213
+ let segment;
214
+ for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
215
+ segment = toSegments[toPosition];
216
+ // can't go below zero
217
+ if (position === 1 || segment === '.')
218
+ continue;
219
+ if (segment === '..')
220
+ position--;
221
+ // found something that is not relative path
222
+ else
223
+ break;
224
+ }
225
+ return (fromSegments.slice(0, position).join('/') +
226
+ '/' +
227
+ toSegments
228
+ .slice(toPosition - (toPosition === toSegments.length ? 1 : 0))
229
+ .join('/'));
230
+ }
231
+
232
+ var NavigationType;
233
+ (function (NavigationType) {
234
+ NavigationType["pop"] = "pop";
235
+ NavigationType["push"] = "push";
236
+ })(NavigationType || (NavigationType = {}));
237
+ var NavigationDirection;
238
+ (function (NavigationDirection) {
239
+ NavigationDirection["back"] = "back";
240
+ NavigationDirection["forward"] = "forward";
241
+ NavigationDirection["unknown"] = "";
242
+ })(NavigationDirection || (NavigationDirection = {}));
243
+ /**
244
+ * Starting location for Histories
245
+ */
246
+ const START = '';
247
+ // Generic utils
248
+ /**
249
+ * Normalizes a base by removing any trailing slash and reading the base tag if
250
+ * present.
251
+ *
252
+ * @param base - base to normalize
253
+ */
254
+ function normalizeBase(base) {
255
+ if (!base) {
256
+ if (isBrowser) {
257
+ // respect <base> tag
258
+ const baseEl = document.querySelector('base');
259
+ base = (baseEl && baseEl.getAttribute('href')) || '/';
260
+ // strip full URL origin
261
+ base = base.replace(/^\w+:\/\/[^\/]+/, '');
262
+ }
263
+ else {
264
+ base = '/';
265
+ }
266
+ }
267
+ // ensure leading slash when it was removed by the regex above avoid leading
268
+ // slash with hash because the file could be read from the disk like file://
269
+ // and the leading slash would cause problems
270
+ if (base[0] !== '/' && base[0] !== '#')
271
+ base = '/' + base;
272
+ // remove the trailing slash so all other method can just do `base + fullPath`
273
+ // to build an href
274
+ return removeTrailingSlash(base);
275
+ }
276
+ // remove any character before the hash
277
+ const BEFORE_HASH_RE = /^[^#]+#/;
278
+ function createHref(base, location) {
279
+ return base.replace(BEFORE_HASH_RE, '#') + location;
280
+ }
281
+
282
+ function getElementPosition(el, offset) {
283
+ const docRect = document.documentElement.getBoundingClientRect();
284
+ const elRect = el.getBoundingClientRect();
285
+ return {
286
+ behavior: offset.behavior,
287
+ left: elRect.left - docRect.left - (offset.left || 0),
288
+ top: elRect.top - docRect.top - (offset.top || 0),
289
+ };
290
+ }
291
+ const computeScrollPosition = () => ({
292
+ left: window.pageXOffset,
293
+ top: window.pageYOffset,
294
+ });
295
+ function scrollToPosition(position) {
296
+ let scrollToOptions;
297
+ if ('el' in position) {
298
+ const positionEl = position.el;
299
+ const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#');
300
+ /**
301
+ * `id`s can accept pretty much any characters, including CSS combinators
302
+ * like `>` or `~`. It's still possible to retrieve elements using
303
+ * `document.getElementById('~')` but it needs to be escaped when using
304
+ * `document.querySelector('#\\~')` for it to be valid. The only
305
+ * requirements for `id`s are them to be unique on the page and to not be
306
+ * empty (`id=""`). Because of that, when passing an id selector, it should
307
+ * be properly escaped for it to work with `querySelector`. We could check
308
+ * for the id selector to be simple (no CSS combinators `+ >~`) but that
309
+ * would make things inconsistent since they are valid characters for an
310
+ * `id` but would need to be escaped when using `querySelector`, breaking
311
+ * their usage and ending up in no selector returned. Selectors need to be
312
+ * escaped:
313
+ *
314
+ * - `#1-thing` becomes `#\31 -thing`
315
+ * - `#with~symbols` becomes `#with\\~symbols`
316
+ *
317
+ * - More information about the topic can be found at
318
+ * https://mathiasbynens.be/notes/html5-id-class.
319
+ * - Practical example: https://mathiasbynens.be/demo/html5-id
320
+ */
321
+ if ((process.env.NODE_ENV !== 'production') && typeof position.el === 'string') {
322
+ if (!isIdSelector || !document.getElementById(position.el.slice(1))) {
323
+ try {
324
+ const foundEl = document.querySelector(position.el);
325
+ if (isIdSelector && foundEl) {
326
+ warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
327
+ // return to avoid other warnings
328
+ return;
329
+ }
330
+ }
331
+ catch (err) {
332
+ warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`);
333
+ // return to avoid other warnings
334
+ return;
335
+ }
336
+ }
337
+ }
338
+ const el = typeof positionEl === 'string'
339
+ ? isIdSelector
340
+ ? document.getElementById(positionEl.slice(1))
341
+ : document.querySelector(positionEl)
342
+ : positionEl;
343
+ if (!el) {
344
+ (process.env.NODE_ENV !== 'production') &&
345
+ warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`);
346
+ return;
347
+ }
348
+ scrollToOptions = getElementPosition(el, position);
349
+ }
350
+ else {
351
+ scrollToOptions = position;
352
+ }
353
+ if ('scrollBehavior' in document.documentElement.style)
354
+ window.scrollTo(scrollToOptions);
355
+ else {
356
+ window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset);
357
+ }
358
+ }
359
+ function getScrollKey(path, delta) {
360
+ const position = history.state ? history.state.position - delta : -1;
361
+ return position + path;
362
+ }
363
+ const scrollPositions = new Map();
364
+ function saveScrollPosition(key, scrollPosition) {
365
+ scrollPositions.set(key, scrollPosition);
366
+ }
367
+ function getSavedScrollPosition(key) {
368
+ const scroll = scrollPositions.get(key);
369
+ // consume it so it's not used again
370
+ scrollPositions.delete(key);
371
+ return scroll;
372
+ }
373
+ // TODO: RFC about how to save scroll position
374
+ /**
375
+ * ScrollBehavior instance used by the router to compute and restore the scroll
376
+ * position when navigating.
377
+ */
378
+ // export interface ScrollHandler<ScrollPositionEntry extends HistoryStateValue, ScrollPosition extends ScrollPositionEntry> {
379
+ // // returns a scroll position that can be saved in history
380
+ // compute(): ScrollPositionEntry
381
+ // // can take an extended ScrollPositionEntry
382
+ // scroll(position: ScrollPosition): void
383
+ // }
384
+ // export const scrollHandler: ScrollHandler<ScrollPosition> = {
385
+ // compute: computeScroll,
386
+ // scroll: scrollToPosition,
387
+ // }
388
+
389
+ let createBaseLocation = () => location.protocol + '//' + location.host;
390
+ /**
391
+ * Creates a normalized history location from a window.location object
392
+ * @param location -
393
+ */
394
+ function createCurrentLocation(base, location) {
395
+ const { pathname, search, hash } = location;
396
+ // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end
397
+ const hashPos = base.indexOf('#');
398
+ if (hashPos > -1) {
399
+ let slicePos = hash.includes(base.slice(hashPos))
400
+ ? base.slice(hashPos).length
401
+ : 1;
402
+ let pathFromHash = hash.slice(slicePos);
403
+ // prepend the starting slash to hash so the url starts with /#
404
+ if (pathFromHash[0] !== '/')
405
+ pathFromHash = '/' + pathFromHash;
406
+ return stripBase(pathFromHash, '');
407
+ }
408
+ const path = stripBase(pathname, base);
409
+ return path + search + hash;
410
+ }
411
+ function useHistoryListeners(base, historyState, currentLocation, replace) {
412
+ let listeners = [];
413
+ let teardowns = [];
414
+ // TODO: should it be a stack? a Dict. Check if the popstate listener
415
+ // can trigger twice
416
+ let pauseState = null;
417
+ const popStateHandler = ({ state, }) => {
418
+ const to = createCurrentLocation(base, location);
419
+ const from = currentLocation.value;
420
+ const fromState = historyState.value;
421
+ let delta = 0;
422
+ if (state) {
423
+ currentLocation.value = to;
424
+ historyState.value = state;
425
+ // ignore the popstate and reset the pauseState
426
+ if (pauseState && pauseState === from) {
427
+ pauseState = null;
428
+ return;
429
+ }
430
+ delta = fromState ? state.position - fromState.position : 0;
431
+ }
432
+ else {
433
+ replace(to);
434
+ }
435
+ // console.log({ deltaFromCurrent })
436
+ // Here we could also revert the navigation by calling history.go(-delta)
437
+ // this listener will have to be adapted to not trigger again and to wait for the url
438
+ // to be updated before triggering the listeners. Some kind of validation function would also
439
+ // need to be passed to the listeners so the navigation can be accepted
440
+ // call all listeners
441
+ listeners.forEach(listener => {
442
+ listener(currentLocation.value, from, {
443
+ delta,
444
+ type: NavigationType.pop,
445
+ direction: delta
446
+ ? delta > 0
447
+ ? NavigationDirection.forward
448
+ : NavigationDirection.back
449
+ : NavigationDirection.unknown,
450
+ });
451
+ });
452
+ };
453
+ function pauseListeners() {
454
+ pauseState = currentLocation.value;
455
+ }
456
+ function listen(callback) {
457
+ // setup the listener and prepare teardown callbacks
458
+ listeners.push(callback);
459
+ const teardown = () => {
460
+ const index = listeners.indexOf(callback);
461
+ if (index > -1)
462
+ listeners.splice(index, 1);
463
+ };
464
+ teardowns.push(teardown);
465
+ return teardown;
466
+ }
467
+ function beforeUnloadListener() {
468
+ const { history } = window;
469
+ if (!history.state)
470
+ return;
471
+ history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), '');
472
+ }
473
+ function destroy() {
474
+ for (const teardown of teardowns)
475
+ teardown();
476
+ teardowns = [];
477
+ window.removeEventListener('popstate', popStateHandler);
478
+ window.removeEventListener('beforeunload', beforeUnloadListener);
479
+ }
480
+ // setup the listeners and prepare teardown callbacks
481
+ window.addEventListener('popstate', popStateHandler);
482
+ window.addEventListener('beforeunload', beforeUnloadListener);
483
+ return {
484
+ pauseListeners,
485
+ listen,
486
+ destroy,
487
+ };
488
+ }
489
+ /**
490
+ * Creates a state object
491
+ */
492
+ function buildState(back, current, forward, replaced = false, computeScroll = false) {
493
+ return {
494
+ back,
495
+ current,
496
+ forward,
497
+ replaced,
498
+ position: window.history.length,
499
+ scroll: computeScroll ? computeScrollPosition() : null,
500
+ };
501
+ }
502
+ function useHistoryStateNavigation(base) {
503
+ const { history, location } = window;
504
+ // private variables
505
+ const currentLocation = {
506
+ value: createCurrentLocation(base, location),
507
+ };
508
+ const historyState = { value: history.state };
509
+ // build current history entry as this is a fresh navigation
510
+ if (!historyState.value) {
511
+ changeLocation(currentLocation.value, {
512
+ back: null,
513
+ current: currentLocation.value,
514
+ forward: null,
515
+ // the length is off by one, we need to decrease it
516
+ position: history.length - 1,
517
+ replaced: true,
518
+ // don't add a scroll as the user may have an anchor and we want
519
+ // scrollBehavior to be triggered without a saved position
520
+ scroll: null,
521
+ }, true);
522
+ }
523
+ function changeLocation(to, state, replace) {
524
+ /**
525
+ * if a base tag is provided and we are on a normal domain, we have to
526
+ * respect the provided `base` attribute because pushState() will use it and
527
+ * potentially erase anything before the `#` like at
528
+ * https://github.com/vuejs/router/issues/685 where a base of
529
+ * `/folder/#` but a base of `/` would erase the `/folder/` section. If
530
+ * there is no host, the `<base>` tag makes no sense and if there isn't a
531
+ * base tag we can just use everything after the `#`.
532
+ */
533
+ const hashIndex = base.indexOf('#');
534
+ const url = hashIndex > -1
535
+ ? (location.host && document.querySelector('base')
536
+ ? base
537
+ : base.slice(hashIndex)) + to
538
+ : createBaseLocation() + base + to;
539
+ try {
540
+ // BROWSER QUIRK
541
+ // NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds
542
+ history[replace ? 'replaceState' : 'pushState'](state, '', url);
543
+ historyState.value = state;
544
+ }
545
+ catch (err) {
546
+ if ((process.env.NODE_ENV !== 'production')) {
547
+ warn('Error with push/replace State', err);
548
+ }
549
+ else {
550
+ console.error(err);
551
+ }
552
+ // Force the navigation, this also resets the call count
553
+ location[replace ? 'replace' : 'assign'](url);
554
+ }
555
+ }
556
+ function replace(to, data) {
557
+ const state = assign({}, history.state, buildState(historyState.value.back,
558
+ // keep back and forward entries but override current position
559
+ to, historyState.value.forward, true), data, { position: historyState.value.position });
560
+ changeLocation(to, state, true);
561
+ currentLocation.value = to;
562
+ }
563
+ function push(to, data) {
564
+ // Add to current entry the information of where we are going
565
+ // as well as saving the current position
566
+ const currentState = assign({},
567
+ // use current history state to gracefully handle a wrong call to
568
+ // history.replaceState
569
+ // https://github.com/vuejs/router/issues/366
570
+ historyState.value, history.state, {
571
+ forward: to,
572
+ scroll: computeScrollPosition(),
573
+ });
574
+ if ((process.env.NODE_ENV !== 'production') && !history.state) {
575
+ warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` +
576
+ `history.replaceState(history.state, '', url)\n\n` +
577
+ `You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.`);
578
+ }
579
+ changeLocation(currentState.current, currentState, true);
580
+ const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data);
581
+ changeLocation(to, state, false);
582
+ currentLocation.value = to;
583
+ }
584
+ return {
585
+ location: currentLocation,
586
+ state: historyState,
587
+ push,
588
+ replace,
589
+ };
590
+ }
591
+ /**
592
+ * Creates an HTML5 history. Most common history for single page applications.
593
+ *
594
+ * @param base -
595
+ */
596
+ function createWebHistory(base) {
597
+ base = normalizeBase(base);
598
+ const historyNavigation = useHistoryStateNavigation(base);
599
+ const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
600
+ function go(delta, triggerListeners = true) {
601
+ if (!triggerListeners)
602
+ historyListeners.pauseListeners();
603
+ history.go(delta);
604
+ }
605
+ const routerHistory = assign({
606
+ // it's overridden right after
607
+ location: '',
608
+ base,
609
+ go,
610
+ createHref: createHref.bind(null, base),
611
+ }, historyNavigation, historyListeners);
612
+ Object.defineProperty(routerHistory, 'location', {
613
+ enumerable: true,
614
+ get: () => historyNavigation.location.value,
615
+ });
616
+ Object.defineProperty(routerHistory, 'state', {
617
+ enumerable: true,
618
+ get: () => historyNavigation.state.value,
619
+ });
620
+ return routerHistory;
621
+ }
622
+
623
+ /**
624
+ * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere.
625
+ * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`.
626
+ *
627
+ * @param base - Base applied to all urls, defaults to '/'
628
+ * @returns a history object that can be passed to the router constructor
629
+ */
630
+ function createMemoryHistory(base = '') {
631
+ let listeners = [];
632
+ let queue = [START];
633
+ let position = 0;
634
+ base = normalizeBase(base);
635
+ function setLocation(location) {
636
+ position++;
637
+ if (position === queue.length) {
638
+ // we are at the end, we can simply append a new entry
639
+ queue.push(location);
640
+ }
641
+ else {
642
+ // we are in the middle, we remove everything from here in the queue
643
+ queue.splice(position);
644
+ queue.push(location);
645
+ }
646
+ }
647
+ function triggerListeners(to, from, { direction, delta }) {
648
+ const info = {
649
+ direction,
650
+ delta,
651
+ type: NavigationType.pop,
652
+ };
653
+ for (const callback of listeners) {
654
+ callback(to, from, info);
655
+ }
656
+ }
657
+ const routerHistory = {
658
+ // rewritten by Object.defineProperty
659
+ location: START,
660
+ // TODO: should be kept in queue
661
+ state: {},
662
+ base,
663
+ createHref: createHref.bind(null, base),
664
+ replace(to) {
665
+ // remove current entry and decrement position
666
+ queue.splice(position--, 1);
667
+ setLocation(to);
668
+ },
669
+ push(to, data) {
670
+ setLocation(to);
671
+ },
672
+ listen(callback) {
673
+ listeners.push(callback);
674
+ return () => {
675
+ const index = listeners.indexOf(callback);
676
+ if (index > -1)
677
+ listeners.splice(index, 1);
678
+ };
679
+ },
680
+ destroy() {
681
+ listeners = [];
682
+ queue = [START];
683
+ position = 0;
684
+ },
685
+ go(delta, shouldTrigger = true) {
686
+ const from = this.location;
687
+ const direction =
688
+ // we are considering delta === 0 going forward, but in abstract mode
689
+ // using 0 for the delta doesn't make sense like it does in html5 where
690
+ // it reloads the page
691
+ delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
692
+ position = Math.max(0, Math.min(position + delta, queue.length - 1));
693
+ if (shouldTrigger) {
694
+ triggerListeners(this.location, from, {
695
+ direction,
696
+ delta,
697
+ });
698
+ }
699
+ },
700
+ };
701
+ Object.defineProperty(routerHistory, 'location', {
702
+ enumerable: true,
703
+ get: () => queue[position],
704
+ });
705
+ return routerHistory;
706
+ }
707
+
708
+ /**
709
+ * Creates a hash history. Useful for web applications with no host (e.g.
710
+ * `file://`) or when configuring a server to handle any URL is not possible.
711
+ *
712
+ * @param base - optional base to provide. Defaults to `location.pathname +
713
+ * location.search` If there is a `<base>` tag in the `head`, its value will be
714
+ * ignored in favor of this parameter **but note it affects all the
715
+ * history.pushState() calls**, meaning that if you use a `<base>` tag, it's
716
+ * `href` value **has to match this parameter** (ignoring anything after the
717
+ * `#`).
718
+ *
719
+ * @example
720
+ * ```js
721
+ * // at https://example.com/folder
722
+ * createWebHashHistory() // gives a url of `https://example.com/folder#`
723
+ * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
724
+ * // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
725
+ * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
726
+ * // you should avoid doing this because it changes the original url and breaks copying urls
727
+ * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
728
+ *
729
+ * // at file:///usr/etc/folder/index.html
730
+ * // for locations with no `host`, the base is ignored
731
+ * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
732
+ * ```
733
+ */
734
+ function createWebHashHistory(base) {
735
+ // Make sure this implementation is fine in terms of encoding, specially for IE11
736
+ // for `file://`, directly use the pathname and ignore the base
737
+ // location.pathname contains an initial `/` even at the root: `https://example.com`
738
+ base = location.host ? base || location.pathname + location.search : '';
739
+ // allow the user to provide a `#` in the middle: `/base/#/app`
740
+ if (!base.includes('#'))
741
+ base += '#';
742
+ if ((process.env.NODE_ENV !== 'production') && !base.endsWith('#/') && !base.endsWith('#')) {
743
+ warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`);
744
+ }
745
+ return createWebHistory(base);
746
+ }
747
+
748
+ function isRouteLocation(route) {
749
+ return typeof route === 'string' || (route && typeof route === 'object');
750
+ }
751
+ function isRouteName(name) {
752
+ return typeof name === 'string' || typeof name === 'symbol';
753
+ }
754
+
755
+ /**
756
+ * Initial route location where the router is. Can be used in navigation guards
757
+ * to differentiate the initial navigation.
758
+ *
759
+ * @example
760
+ * ```js
761
+ * import { START_LOCATION } from 'vue-router'
762
+ *
763
+ * router.beforeEach((to, from) => {
764
+ * if (from === START_LOCATION) {
765
+ * // initial navigation
766
+ * }
767
+ * })
768
+ * ```
769
+ */
770
+ const START_LOCATION_NORMALIZED = {
771
+ path: '/',
772
+ name: undefined,
773
+ params: {},
774
+ query: {},
775
+ hash: '',
776
+ fullPath: '/',
777
+ matched: [],
778
+ meta: {},
779
+ redirectedFrom: undefined,
780
+ };
781
+
782
+ const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'navigation failure' : 'nf');
783
+ /**
784
+ * Enumeration with all possible types for navigation failures. Can be passed to
785
+ * {@link isNavigationFailure} to check for specific failures.
786
+ */
787
+ var NavigationFailureType;
788
+ (function (NavigationFailureType) {
789
+ /**
790
+ * An aborted navigation is a navigation that failed because a navigation
791
+ * guard returned `false` or called `next(false)`
792
+ */
793
+ NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted";
794
+ /**
795
+ * A cancelled navigation is a navigation that failed because a more recent
796
+ * navigation finished started (not necessarily finished).
797
+ */
798
+ NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled";
799
+ /**
800
+ * A duplicated navigation is a navigation that failed because it was
801
+ * initiated while already being at the exact same location.
802
+ */
803
+ NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated";
804
+ })(NavigationFailureType || (NavigationFailureType = {}));
805
+ // DEV only debug messages
806
+ const ErrorTypeMessages = {
807
+ [1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) {
808
+ return `No match for\n ${JSON.stringify(location)}${currentLocation
809
+ ? '\nwhile being at\n' + JSON.stringify(currentLocation)
810
+ : ''}`;
811
+ },
812
+ [2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) {
813
+ return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
814
+ },
815
+ [4 /* NAVIGATION_ABORTED */]({ from, to }) {
816
+ return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
817
+ },
818
+ [8 /* NAVIGATION_CANCELLED */]({ from, to }) {
819
+ return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
820
+ },
821
+ [16 /* NAVIGATION_DUPLICATED */]({ from, to }) {
822
+ return `Avoided redundant navigation to current location: "${from.fullPath}".`;
823
+ },
824
+ };
825
+ function createRouterError(type, params) {
826
+ // keep full error messages in cjs versions
827
+ if ((process.env.NODE_ENV !== 'production') || !true) {
828
+ return assign(new Error(ErrorTypeMessages[type](params)), {
829
+ type,
830
+ [NavigationFailureSymbol]: true,
831
+ }, params);
832
+ }
833
+ else {
834
+ return assign(new Error(), {
835
+ type,
836
+ [NavigationFailureSymbol]: true,
837
+ }, params);
838
+ }
839
+ }
840
+ function isNavigationFailure(error, type) {
841
+ return (error instanceof Error &&
842
+ NavigationFailureSymbol in error &&
843
+ (type == null || !!(error.type & type)));
844
+ }
845
+ const propertiesToLog = ['params', 'query', 'hash'];
846
+ function stringifyRoute(to) {
847
+ if (typeof to === 'string')
848
+ return to;
849
+ if ('path' in to)
850
+ return to.path;
851
+ const location = {};
852
+ for (const key of propertiesToLog) {
853
+ if (key in to)
854
+ location[key] = to[key];
855
+ }
856
+ return JSON.stringify(location, null, 2);
857
+ }
858
+
859
+ // default pattern for a param: non greedy everything but /
860
+ const BASE_PARAM_PATTERN = '[^/]+?';
861
+ const BASE_PATH_PARSER_OPTIONS = {
862
+ sensitive: false,
863
+ strict: false,
864
+ start: true,
865
+ end: true,
866
+ };
867
+ // Special Regex characters that must be escaped in static tokens
868
+ const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
869
+ /**
870
+ * Creates a path parser from an array of Segments (a segment is an array of Tokens)
871
+ *
872
+ * @param segments - array of segments returned by tokenizePath
873
+ * @param extraOptions - optional options for the regexp
874
+ * @returns a PathParser
875
+ */
876
+ function tokensToParser(segments, extraOptions) {
877
+ const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
878
+ // the amount of scores is the same as the length of segments except for the root segment "/"
879
+ const score = [];
880
+ // the regexp as a string
881
+ let pattern = options.start ? '^' : '';
882
+ // extracted keys
883
+ const keys = [];
884
+ for (const segment of segments) {
885
+ // the root segment needs special treatment
886
+ const segmentScores = segment.length ? [] : [90 /* Root */];
887
+ // allow trailing slash
888
+ if (options.strict && !segment.length)
889
+ pattern += '/';
890
+ for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
891
+ const token = segment[tokenIndex];
892
+ // resets the score if we are inside a sub segment /:a-other-:b
893
+ let subSegmentScore = 40 /* Segment */ +
894
+ (options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0);
895
+ if (token.type === 0 /* Static */) {
896
+ // prepend the slash if we are starting a new segment
897
+ if (!tokenIndex)
898
+ pattern += '/';
899
+ pattern += token.value.replace(REGEX_CHARS_RE, '\\$&');
900
+ subSegmentScore += 40 /* Static */;
901
+ }
902
+ else if (token.type === 1 /* Param */) {
903
+ const { value, repeatable, optional, regexp } = token;
904
+ keys.push({
905
+ name: value,
906
+ repeatable,
907
+ optional,
908
+ });
909
+ const re = regexp ? regexp : BASE_PARAM_PATTERN;
910
+ // the user provided a custom regexp /:id(\\d+)
911
+ if (re !== BASE_PARAM_PATTERN) {
912
+ subSegmentScore += 10 /* BonusCustomRegExp */;
913
+ // make sure the regexp is valid before using it
914
+ try {
915
+ new RegExp(`(${re})`);
916
+ }
917
+ catch (err) {
918
+ throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` +
919
+ err.message);
920
+ }
921
+ }
922
+ // when we repeat we must take care of the repeating leading slash
923
+ let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`;
924
+ // prepend the slash if we are starting a new segment
925
+ if (!tokenIndex)
926
+ subPattern =
927
+ // avoid an optional / if there are more segments e.g. /:p?-static
928
+ // or /:p?-:p2
929
+ optional && segment.length < 2
930
+ ? `(?:/${subPattern})`
931
+ : '/' + subPattern;
932
+ if (optional)
933
+ subPattern += '?';
934
+ pattern += subPattern;
935
+ subSegmentScore += 20 /* Dynamic */;
936
+ if (optional)
937
+ subSegmentScore += -8 /* BonusOptional */;
938
+ if (repeatable)
939
+ subSegmentScore += -20 /* BonusRepeatable */;
940
+ if (re === '.*')
941
+ subSegmentScore += -50 /* BonusWildcard */;
942
+ }
943
+ segmentScores.push(subSegmentScore);
944
+ }
945
+ // an empty array like /home/ -> [[{home}], []]
946
+ // if (!segment.length) pattern += '/'
947
+ score.push(segmentScores);
948
+ }
949
+ // only apply the strict bonus to the last score
950
+ if (options.strict && options.end) {
951
+ const i = score.length - 1;
952
+ score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */;
953
+ }
954
+ // TODO: dev only warn double trailing slash
955
+ if (!options.strict)
956
+ pattern += '/?';
957
+ if (options.end)
958
+ pattern += '$';
959
+ // allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else
960
+ else if (options.strict)
961
+ pattern += '(?:/|$)';
962
+ const re = new RegExp(pattern, options.sensitive ? '' : 'i');
963
+ function parse(path) {
964
+ const match = path.match(re);
965
+ const params = {};
966
+ if (!match)
967
+ return null;
968
+ for (let i = 1; i < match.length; i++) {
969
+ const value = match[i] || '';
970
+ const key = keys[i - 1];
971
+ params[key.name] = value && key.repeatable ? value.split('/') : value;
972
+ }
973
+ return params;
974
+ }
975
+ function stringify(params) {
976
+ let path = '';
977
+ // for optional parameters to allow to be empty
978
+ let avoidDuplicatedSlash = false;
979
+ for (const segment of segments) {
980
+ if (!avoidDuplicatedSlash || !path.endsWith('/'))
981
+ path += '/';
982
+ avoidDuplicatedSlash = false;
983
+ for (const token of segment) {
984
+ if (token.type === 0 /* Static */) {
985
+ path += token.value;
986
+ }
987
+ else if (token.type === 1 /* Param */) {
988
+ const { value, repeatable, optional } = token;
989
+ const param = value in params ? params[value] : '';
990
+ if (Array.isArray(param) && !repeatable)
991
+ throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
992
+ const text = Array.isArray(param) ? param.join('/') : param;
993
+ if (!text) {
994
+ if (optional) {
995
+ // if we have more than one optional param like /:a?-static and there are more segments, we don't need to
996
+ // care about the optional param
997
+ if (segment.length < 2 && segments.length > 1) {
998
+ // remove the last slash as we could be at the end
999
+ if (path.endsWith('/'))
1000
+ path = path.slice(0, -1);
1001
+ // do not append a slash on the next iteration
1002
+ else
1003
+ avoidDuplicatedSlash = true;
1004
+ }
1005
+ }
1006
+ else
1007
+ throw new Error(`Missing required param "${value}"`);
1008
+ }
1009
+ path += text;
1010
+ }
1011
+ }
1012
+ }
1013
+ return path;
1014
+ }
1015
+ return {
1016
+ re,
1017
+ score,
1018
+ keys,
1019
+ parse,
1020
+ stringify,
1021
+ };
1022
+ }
1023
+ /**
1024
+ * Compares an array of numbers as used in PathParser.score and returns a
1025
+ * number. This function can be used to `sort` an array
1026
+ *
1027
+ * @param a - first array of numbers
1028
+ * @param b - second array of numbers
1029
+ * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
1030
+ * should be sorted first
1031
+ */
1032
+ function compareScoreArray(a, b) {
1033
+ let i = 0;
1034
+ while (i < a.length && i < b.length) {
1035
+ const diff = b[i] - a[i];
1036
+ // only keep going if diff === 0
1037
+ if (diff)
1038
+ return diff;
1039
+ i++;
1040
+ }
1041
+ // if the last subsegment was Static, the shorter segments should be sorted first
1042
+ // otherwise sort the longest segment first
1043
+ if (a.length < b.length) {
1044
+ return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */
1045
+ ? -1
1046
+ : 1;
1047
+ }
1048
+ else if (a.length > b.length) {
1049
+ return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */
1050
+ ? 1
1051
+ : -1;
1052
+ }
1053
+ return 0;
1054
+ }
1055
+ /**
1056
+ * Compare function that can be used with `sort` to sort an array of PathParser
1057
+ *
1058
+ * @param a - first PathParser
1059
+ * @param b - second PathParser
1060
+ * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
1061
+ */
1062
+ function comparePathParserScore(a, b) {
1063
+ let i = 0;
1064
+ const aScore = a.score;
1065
+ const bScore = b.score;
1066
+ while (i < aScore.length && i < bScore.length) {
1067
+ const comp = compareScoreArray(aScore[i], bScore[i]);
1068
+ // do not return if both are equal
1069
+ if (comp)
1070
+ return comp;
1071
+ i++;
1072
+ }
1073
+ // if a and b share the same score entries but b has more, sort b first
1074
+ return bScore.length - aScore.length;
1075
+ // this is the ternary version
1076
+ // return aScore.length < bScore.length
1077
+ // ? 1
1078
+ // : aScore.length > bScore.length
1079
+ // ? -1
1080
+ // : 0
1081
+ }
1082
+
1083
+ const ROOT_TOKEN = {
1084
+ type: 0 /* Static */,
1085
+ value: '',
1086
+ };
1087
+ const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
1088
+ // After some profiling, the cache seems to be unnecessary because tokenizePath
1089
+ // (the slowest part of adding a route) is very fast
1090
+ // const tokenCache = new Map<string, Token[][]>()
1091
+ function tokenizePath(path) {
1092
+ if (!path)
1093
+ return [[]];
1094
+ if (path === '/')
1095
+ return [[ROOT_TOKEN]];
1096
+ if (!path.startsWith('/')) {
1097
+ throw new Error((process.env.NODE_ENV !== 'production')
1098
+ ? `Route paths should start with a "/": "${path}" should be "/${path}".`
1099
+ : `Invalid path "${path}"`);
1100
+ }
1101
+ // if (tokenCache.has(path)) return tokenCache.get(path)!
1102
+ function crash(message) {
1103
+ throw new Error(`ERR (${state})/"${buffer}": ${message}`);
1104
+ }
1105
+ let state = 0 /* Static */;
1106
+ let previousState = state;
1107
+ const tokens = [];
1108
+ // the segment will always be valid because we get into the initial state
1109
+ // with the leading /
1110
+ let segment;
1111
+ function finalizeSegment() {
1112
+ if (segment)
1113
+ tokens.push(segment);
1114
+ segment = [];
1115
+ }
1116
+ // index on the path
1117
+ let i = 0;
1118
+ // char at index
1119
+ let char;
1120
+ // buffer of the value read
1121
+ let buffer = '';
1122
+ // custom regexp for a param
1123
+ let customRe = '';
1124
+ function consumeBuffer() {
1125
+ if (!buffer)
1126
+ return;
1127
+ if (state === 0 /* Static */) {
1128
+ segment.push({
1129
+ type: 0 /* Static */,
1130
+ value: buffer,
1131
+ });
1132
+ }
1133
+ else if (state === 1 /* Param */ ||
1134
+ state === 2 /* ParamRegExp */ ||
1135
+ state === 3 /* ParamRegExpEnd */) {
1136
+ if (segment.length > 1 && (char === '*' || char === '+'))
1137
+ crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
1138
+ segment.push({
1139
+ type: 1 /* Param */,
1140
+ value: buffer,
1141
+ regexp: customRe,
1142
+ repeatable: char === '*' || char === '+',
1143
+ optional: char === '*' || char === '?',
1144
+ });
1145
+ }
1146
+ else {
1147
+ crash('Invalid state to consume buffer');
1148
+ }
1149
+ buffer = '';
1150
+ }
1151
+ function addCharToBuffer() {
1152
+ buffer += char;
1153
+ }
1154
+ while (i < path.length) {
1155
+ char = path[i++];
1156
+ if (char === '\\' && state !== 2 /* ParamRegExp */) {
1157
+ previousState = state;
1158
+ state = 4 /* EscapeNext */;
1159
+ continue;
1160
+ }
1161
+ switch (state) {
1162
+ case 0 /* Static */:
1163
+ if (char === '/') {
1164
+ if (buffer) {
1165
+ consumeBuffer();
1166
+ }
1167
+ finalizeSegment();
1168
+ }
1169
+ else if (char === ':') {
1170
+ consumeBuffer();
1171
+ state = 1 /* Param */;
1172
+ }
1173
+ else {
1174
+ addCharToBuffer();
1175
+ }
1176
+ break;
1177
+ case 4 /* EscapeNext */:
1178
+ addCharToBuffer();
1179
+ state = previousState;
1180
+ break;
1181
+ case 1 /* Param */:
1182
+ if (char === '(') {
1183
+ state = 2 /* ParamRegExp */;
1184
+ }
1185
+ else if (VALID_PARAM_RE.test(char)) {
1186
+ addCharToBuffer();
1187
+ }
1188
+ else {
1189
+ consumeBuffer();
1190
+ state = 0 /* Static */;
1191
+ // go back one character if we were not modifying
1192
+ if (char !== '*' && char !== '?' && char !== '+')
1193
+ i--;
1194
+ }
1195
+ break;
1196
+ case 2 /* ParamRegExp */:
1197
+ // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix)
1198
+ // it already works by escaping the closing )
1199
+ // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB#
1200
+ // is this really something people need since you can also write
1201
+ // /prefix_:p()_suffix
1202
+ if (char === ')') {
1203
+ // handle the escaped )
1204
+ if (customRe[customRe.length - 1] == '\\')
1205
+ customRe = customRe.slice(0, -1) + char;
1206
+ else
1207
+ state = 3 /* ParamRegExpEnd */;
1208
+ }
1209
+ else {
1210
+ customRe += char;
1211
+ }
1212
+ break;
1213
+ case 3 /* ParamRegExpEnd */:
1214
+ // same as finalizing a param
1215
+ consumeBuffer();
1216
+ state = 0 /* Static */;
1217
+ // go back one character if we were not modifying
1218
+ if (char !== '*' && char !== '?' && char !== '+')
1219
+ i--;
1220
+ customRe = '';
1221
+ break;
1222
+ default:
1223
+ crash('Unknown state');
1224
+ break;
1225
+ }
1226
+ }
1227
+ if (state === 2 /* ParamRegExp */)
1228
+ crash(`Unfinished custom RegExp for param "${buffer}"`);
1229
+ consumeBuffer();
1230
+ finalizeSegment();
1231
+ // tokenCache.set(path, tokens)
1232
+ return tokens;
1233
+ }
1234
+
1235
+ function createRouteRecordMatcher(record, parent, options) {
1236
+ const parser = tokensToParser(tokenizePath(record.path), options);
1237
+ // warn against params with the same name
1238
+ if ((process.env.NODE_ENV !== 'production')) {
1239
+ const existingKeys = new Set();
1240
+ for (const key of parser.keys) {
1241
+ if (existingKeys.has(key.name))
1242
+ warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
1243
+ existingKeys.add(key.name);
1244
+ }
1245
+ }
1246
+ const matcher = assign(parser, {
1247
+ record,
1248
+ parent,
1249
+ // these needs to be populated by the parent
1250
+ children: [],
1251
+ alias: [],
1252
+ });
1253
+ if (parent) {
1254
+ // both are aliases or both are not aliases
1255
+ // we don't want to mix them because the order is used when
1256
+ // passing originalRecord in Matcher.addRoute
1257
+ if (!matcher.record.aliasOf === !parent.record.aliasOf)
1258
+ parent.children.push(matcher);
1259
+ }
1260
+ return matcher;
1261
+ }
1262
+
1263
+ /**
1264
+ * Creates a Router Matcher.
1265
+ *
1266
+ * @internal
1267
+ * @param routes - array of initial routes
1268
+ * @param globalOptions - global route options
1269
+ */
1270
+ function createRouterMatcher(routes, globalOptions) {
1271
+ // normalized ordered array of matchers
1272
+ const matchers = [];
1273
+ const matcherMap = new Map();
1274
+ globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions);
1275
+ function getRecordMatcher(name) {
1276
+ return matcherMap.get(name);
1277
+ }
1278
+ function addRoute(record, parent, originalRecord) {
1279
+ // used later on to remove by name
1280
+ const isRootAdd = !originalRecord;
1281
+ const mainNormalizedRecord = normalizeRouteRecord(record);
1282
+ // we might be the child of an alias
1283
+ mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
1284
+ const options = mergeOptions(globalOptions, record);
1285
+ // generate an array of records to correctly handle aliases
1286
+ const normalizedRecords = [
1287
+ mainNormalizedRecord,
1288
+ ];
1289
+ if ('alias' in record) {
1290
+ const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias;
1291
+ for (const alias of aliases) {
1292
+ normalizedRecords.push(assign({}, mainNormalizedRecord, {
1293
+ // this allows us to hold a copy of the `components` option
1294
+ // so that async components cache is hold on the original record
1295
+ components: originalRecord
1296
+ ? originalRecord.record.components
1297
+ : mainNormalizedRecord.components,
1298
+ path: alias,
1299
+ // we might be the child of an alias
1300
+ aliasOf: originalRecord
1301
+ ? originalRecord.record
1302
+ : mainNormalizedRecord,
1303
+ // the aliases are always of the same kind as the original since they
1304
+ // are defined on the same record
1305
+ }));
1306
+ }
1307
+ }
1308
+ let matcher;
1309
+ let originalMatcher;
1310
+ for (const normalizedRecord of normalizedRecords) {
1311
+ const { path } = normalizedRecord;
1312
+ // Build up the path for nested routes if the child isn't an absolute
1313
+ // route. Only add the / delimiter if the child path isn't empty and if the
1314
+ // parent path doesn't have a trailing slash
1315
+ if (parent && path[0] !== '/') {
1316
+ const parentPath = parent.record.path;
1317
+ const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/';
1318
+ normalizedRecord.path =
1319
+ parent.record.path + (path && connectingSlash + path);
1320
+ }
1321
+ if ((process.env.NODE_ENV !== 'production') && normalizedRecord.path === '*') {
1322
+ throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' +
1323
+ 'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.');
1324
+ }
1325
+ // create the object before hand so it can be passed to children
1326
+ matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
1327
+ if ((process.env.NODE_ENV !== 'production') && parent && path[0] === '/')
1328
+ checkMissingParamsInAbsolutePath(matcher, parent);
1329
+ // if we are an alias we must tell the original record that we exist
1330
+ // so we can be removed
1331
+ if (originalRecord) {
1332
+ originalRecord.alias.push(matcher);
1333
+ if ((process.env.NODE_ENV !== 'production')) {
1334
+ checkSameParams(originalRecord, matcher);
1335
+ }
1336
+ }
1337
+ else {
1338
+ // otherwise, the first record is the original and others are aliases
1339
+ originalMatcher = originalMatcher || matcher;
1340
+ if (originalMatcher !== matcher)
1341
+ originalMatcher.alias.push(matcher);
1342
+ // remove the route if named and only for the top record (avoid in nested calls)
1343
+ // this works because the original record is the first one
1344
+ if (isRootAdd && record.name && !isAliasRecord(matcher))
1345
+ removeRoute(record.name);
1346
+ }
1347
+ if ('children' in mainNormalizedRecord) {
1348
+ const children = mainNormalizedRecord.children;
1349
+ for (let i = 0; i < children.length; i++) {
1350
+ addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
1351
+ }
1352
+ }
1353
+ // if there was no original record, then the first one was not an alias and all
1354
+ // other alias (if any) need to reference this record when adding children
1355
+ originalRecord = originalRecord || matcher;
1356
+ // TODO: add normalized records for more flexibility
1357
+ // if (parent && isAliasRecord(originalRecord)) {
1358
+ // parent.children.push(originalRecord)
1359
+ // }
1360
+ insertMatcher(matcher);
1361
+ }
1362
+ return originalMatcher
1363
+ ? () => {
1364
+ // since other matchers are aliases, they should be removed by the original matcher
1365
+ removeRoute(originalMatcher);
1366
+ }
1367
+ : noop;
1368
+ }
1369
+ function removeRoute(matcherRef) {
1370
+ if (isRouteName(matcherRef)) {
1371
+ const matcher = matcherMap.get(matcherRef);
1372
+ if (matcher) {
1373
+ matcherMap.delete(matcherRef);
1374
+ matchers.splice(matchers.indexOf(matcher), 1);
1375
+ matcher.children.forEach(removeRoute);
1376
+ matcher.alias.forEach(removeRoute);
1377
+ }
1378
+ }
1379
+ else {
1380
+ const index = matchers.indexOf(matcherRef);
1381
+ if (index > -1) {
1382
+ matchers.splice(index, 1);
1383
+ if (matcherRef.record.name)
1384
+ matcherMap.delete(matcherRef.record.name);
1385
+ matcherRef.children.forEach(removeRoute);
1386
+ matcherRef.alias.forEach(removeRoute);
1387
+ }
1388
+ }
1389
+ }
1390
+ function getRoutes() {
1391
+ return matchers;
1392
+ }
1393
+ function insertMatcher(matcher) {
1394
+ let i = 0;
1395
+ while (i < matchers.length &&
1396
+ comparePathParserScore(matcher, matchers[i]) >= 0 &&
1397
+ // Adding children with empty path should still appear before the parent
1398
+ // https://github.com/vuejs/router/issues/1124
1399
+ (matcher.record.path !== matchers[i].record.path ||
1400
+ !isRecordChildOf(matcher, matchers[i])))
1401
+ i++;
1402
+ matchers.splice(i, 0, matcher);
1403
+ // only add the original record to the name map
1404
+ if (matcher.record.name && !isAliasRecord(matcher))
1405
+ matcherMap.set(matcher.record.name, matcher);
1406
+ }
1407
+ function resolve(location, currentLocation) {
1408
+ let matcher;
1409
+ let params = {};
1410
+ let path;
1411
+ let name;
1412
+ if ('name' in location && location.name) {
1413
+ matcher = matcherMap.get(location.name);
1414
+ if (!matcher)
1415
+ throw createRouterError(1 /* MATCHER_NOT_FOUND */, {
1416
+ location,
1417
+ });
1418
+ name = matcher.record.name;
1419
+ params = assign(
1420
+ // paramsFromLocation is a new object
1421
+ paramsFromLocation(currentLocation.params,
1422
+ // only keep params that exist in the resolved location
1423
+ // TODO: only keep optional params coming from a parent record
1424
+ matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params);
1425
+ // throws if cannot be stringified
1426
+ path = matcher.stringify(params);
1427
+ }
1428
+ else if ('path' in location) {
1429
+ // no need to resolve the path with the matcher as it was provided
1430
+ // this also allows the user to control the encoding
1431
+ path = location.path;
1432
+ if ((process.env.NODE_ENV !== 'production') && !path.startsWith('/')) {
1433
+ warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/router.`);
1434
+ }
1435
+ matcher = matchers.find(m => m.re.test(path));
1436
+ // matcher should have a value after the loop
1437
+ if (matcher) {
1438
+ // TODO: dev warning of unused params if provided
1439
+ // we know the matcher works because we tested the regexp
1440
+ params = matcher.parse(path);
1441
+ name = matcher.record.name;
1442
+ }
1443
+ // location is a relative path
1444
+ }
1445
+ else {
1446
+ // match by name or path of current route
1447
+ matcher = currentLocation.name
1448
+ ? matcherMap.get(currentLocation.name)
1449
+ : matchers.find(m => m.re.test(currentLocation.path));
1450
+ if (!matcher)
1451
+ throw createRouterError(1 /* MATCHER_NOT_FOUND */, {
1452
+ location,
1453
+ currentLocation,
1454
+ });
1455
+ name = matcher.record.name;
1456
+ // since we are navigating to the same location, we don't need to pick the
1457
+ // params like when `name` is provided
1458
+ params = assign({}, currentLocation.params, location.params);
1459
+ path = matcher.stringify(params);
1460
+ }
1461
+ const matched = [];
1462
+ let parentMatcher = matcher;
1463
+ while (parentMatcher) {
1464
+ // reversed order so parents are at the beginning
1465
+ matched.unshift(parentMatcher.record);
1466
+ parentMatcher = parentMatcher.parent;
1467
+ }
1468
+ return {
1469
+ name,
1470
+ path,
1471
+ params,
1472
+ matched,
1473
+ meta: mergeMetaFields(matched),
1474
+ };
1475
+ }
1476
+ // add initial routes
1477
+ routes.forEach(route => addRoute(route));
1478
+ return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher };
1479
+ }
1480
+ function paramsFromLocation(params, keys) {
1481
+ const newParams = {};
1482
+ for (const key of keys) {
1483
+ if (key in params)
1484
+ newParams[key] = params[key];
1485
+ }
1486
+ return newParams;
1487
+ }
1488
+ /**
1489
+ * Normalizes a RouteRecordRaw. Creates a copy
1490
+ *
1491
+ * @param record
1492
+ * @returns the normalized version
1493
+ */
1494
+ function normalizeRouteRecord(record) {
1495
+ return {
1496
+ path: record.path,
1497
+ redirect: record.redirect,
1498
+ name: record.name,
1499
+ meta: record.meta || {},
1500
+ aliasOf: undefined,
1501
+ beforeEnter: record.beforeEnter,
1502
+ props: normalizeRecordProps(record),
1503
+ children: record.children || [],
1504
+ instances: {},
1505
+ leaveGuards: new Set(),
1506
+ updateGuards: new Set(),
1507
+ enterCallbacks: {},
1508
+ components: 'components' in record
1509
+ ? record.components || {}
1510
+ : { default: record.component },
1511
+ };
1512
+ }
1513
+ /**
1514
+ * Normalize the optional `props` in a record to always be an object similar to
1515
+ * components. Also accept a boolean for components.
1516
+ * @param record
1517
+ */
1518
+ function normalizeRecordProps(record) {
1519
+ const propsObject = {};
1520
+ // props does not exist on redirect records but we can set false directly
1521
+ const props = record.props || false;
1522
+ if ('component' in record) {
1523
+ propsObject.default = props;
1524
+ }
1525
+ else {
1526
+ // NOTE: we could also allow a function to be applied to every component.
1527
+ // Would need user feedback for use cases
1528
+ for (const name in record.components)
1529
+ propsObject[name] = typeof props === 'boolean' ? props : props[name];
1530
+ }
1531
+ return propsObject;
1532
+ }
1533
+ /**
1534
+ * Checks if a record or any of its parent is an alias
1535
+ * @param record
1536
+ */
1537
+ function isAliasRecord(record) {
1538
+ while (record) {
1539
+ if (record.record.aliasOf)
1540
+ return true;
1541
+ record = record.parent;
1542
+ }
1543
+ return false;
1544
+ }
1545
+ /**
1546
+ * Merge meta fields of an array of records
1547
+ *
1548
+ * @param matched - array of matched records
1549
+ */
1550
+ function mergeMetaFields(matched) {
1551
+ return matched.reduce((meta, record) => assign(meta, record.meta), {});
1552
+ }
1553
+ function mergeOptions(defaults, partialOptions) {
1554
+ const options = {};
1555
+ for (const key in defaults) {
1556
+ options[key] = key in partialOptions ? partialOptions[key] : defaults[key];
1557
+ }
1558
+ return options;
1559
+ }
1560
+ function isSameParam(a, b) {
1561
+ return (a.name === b.name &&
1562
+ a.optional === b.optional &&
1563
+ a.repeatable === b.repeatable);
1564
+ }
1565
+ /**
1566
+ * Check if a path and its alias have the same required params
1567
+ *
1568
+ * @param a - original record
1569
+ * @param b - alias record
1570
+ */
1571
+ function checkSameParams(a, b) {
1572
+ for (const key of a.keys) {
1573
+ if (!key.optional && !b.keys.find(isSameParam.bind(null, key)))
1574
+ return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
1575
+ }
1576
+ for (const key of b.keys) {
1577
+ if (!key.optional && !a.keys.find(isSameParam.bind(null, key)))
1578
+ return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
1579
+ }
1580
+ }
1581
+ function checkMissingParamsInAbsolutePath(record, parent) {
1582
+ for (const key of parent.keys) {
1583
+ if (!record.keys.find(isSameParam.bind(null, key)))
1584
+ return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
1585
+ }
1586
+ }
1587
+ function isRecordChildOf(record, parent) {
1588
+ return parent.children.some(child => child === record || isRecordChildOf(record, child));
1589
+ }
1590
+
1591
+ /**
1592
+ * Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ "
1593
+ * < > `
1594
+ *
1595
+ * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
1596
+ * defines some extra characters to be encoded. Most browsers do not encode them
1597
+ * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to
1598
+ * also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`)
1599
+ * plus `-._~`. This extra safety should be applied to query by patching the
1600
+ * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\`
1601
+ * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\`
1602
+ * into a `/` if directly typed in. The _backtick_ (`````) should also be
1603
+ * encoded everywhere because some browsers like FF encode it when directly
1604
+ * written while others don't. Safari and IE don't encode ``"<>{}``` in hash.
1605
+ */
1606
+ // const EXTRA_RESERVED_RE = /[!'()*]/g
1607
+ // const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16)
1608
+ const HASH_RE = /#/g; // %23
1609
+ const AMPERSAND_RE = /&/g; // %26
1610
+ const SLASH_RE = /\//g; // %2F
1611
+ const EQUAL_RE = /=/g; // %3D
1612
+ const IM_RE = /\?/g; // %3F
1613
+ const PLUS_RE = /\+/g; // %2B
1614
+ /**
1615
+ * NOTE: It's not clear to me if we should encode the + symbol in queries, it
1616
+ * seems to be less flexible than not doing so and I can't find out the legacy
1617
+ * systems requiring this for regular requests like text/html. In the standard,
1618
+ * the encoding of the plus character is only mentioned for
1619
+ * application/x-www-form-urlencoded
1620
+ * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo
1621
+ * leave the plus character as is in queries. To be more flexible, we allow the
1622
+ * plus character on the query but it can also be manually encoded by the user.
1623
+ *
1624
+ * Resources:
1625
+ * - https://url.spec.whatwg.org/#urlencoded-parsing
1626
+ * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20
1627
+ */
1628
+ const ENC_BRACKET_OPEN_RE = /%5B/g; // [
1629
+ const ENC_BRACKET_CLOSE_RE = /%5D/g; // ]
1630
+ const ENC_CARET_RE = /%5E/g; // ^
1631
+ const ENC_BACKTICK_RE = /%60/g; // `
1632
+ const ENC_CURLY_OPEN_RE = /%7B/g; // {
1633
+ const ENC_PIPE_RE = /%7C/g; // |
1634
+ const ENC_CURLY_CLOSE_RE = /%7D/g; // }
1635
+ const ENC_SPACE_RE = /%20/g; // }
1636
+ /**
1637
+ * Encode characters that need to be encoded on the path, search and hash
1638
+ * sections of the URL.
1639
+ *
1640
+ * @internal
1641
+ * @param text - string to encode
1642
+ * @returns encoded string
1643
+ */
1644
+ function commonEncode(text) {
1645
+ return encodeURI('' + text)
1646
+ .replace(ENC_PIPE_RE, '|')
1647
+ .replace(ENC_BRACKET_OPEN_RE, '[')
1648
+ .replace(ENC_BRACKET_CLOSE_RE, ']');
1649
+ }
1650
+ /**
1651
+ * Encode characters that need to be encoded on the hash section of the URL.
1652
+ *
1653
+ * @param text - string to encode
1654
+ * @returns encoded string
1655
+ */
1656
+ function encodeHash(text) {
1657
+ return commonEncode(text)
1658
+ .replace(ENC_CURLY_OPEN_RE, '{')
1659
+ .replace(ENC_CURLY_CLOSE_RE, '}')
1660
+ .replace(ENC_CARET_RE, '^');
1661
+ }
1662
+ /**
1663
+ * Encode characters that need to be encoded query values on the query
1664
+ * section of the URL.
1665
+ *
1666
+ * @param text - string to encode
1667
+ * @returns encoded string
1668
+ */
1669
+ function encodeQueryValue(text) {
1670
+ return (commonEncode(text)
1671
+ // Encode the space as +, encode the + to differentiate it from the space
1672
+ .replace(PLUS_RE, '%2B')
1673
+ .replace(ENC_SPACE_RE, '+')
1674
+ .replace(HASH_RE, '%23')
1675
+ .replace(AMPERSAND_RE, '%26')
1676
+ .replace(ENC_BACKTICK_RE, '`')
1677
+ .replace(ENC_CURLY_OPEN_RE, '{')
1678
+ .replace(ENC_CURLY_CLOSE_RE, '}')
1679
+ .replace(ENC_CARET_RE, '^'));
1680
+ }
1681
+ /**
1682
+ * Like `encodeQueryValue` but also encodes the `=` character.
1683
+ *
1684
+ * @param text - string to encode
1685
+ */
1686
+ function encodeQueryKey(text) {
1687
+ return encodeQueryValue(text).replace(EQUAL_RE, '%3D');
1688
+ }
1689
+ /**
1690
+ * Encode characters that need to be encoded on the path section of the URL.
1691
+ *
1692
+ * @param text - string to encode
1693
+ * @returns encoded string
1694
+ */
1695
+ function encodePath(text) {
1696
+ return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F');
1697
+ }
1698
+ /**
1699
+ * Encode characters that need to be encoded on the path section of the URL as a
1700
+ * param. This function encodes everything {@link encodePath} does plus the
1701
+ * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty
1702
+ * string instead.
1703
+ *
1704
+ * @param text - string to encode
1705
+ * @returns encoded string
1706
+ */
1707
+ function encodeParam(text) {
1708
+ return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F');
1709
+ }
1710
+ /**
1711
+ * Decode text using `decodeURIComponent`. Returns the original text if it
1712
+ * fails.
1713
+ *
1714
+ * @param text - string to decode
1715
+ * @returns decoded string
1716
+ */
1717
+ function decode(text) {
1718
+ try {
1719
+ return decodeURIComponent('' + text);
1720
+ }
1721
+ catch (err) {
1722
+ (process.env.NODE_ENV !== 'production') && warn(`Error decoding "${text}". Using original value`);
1723
+ }
1724
+ return '' + text;
1725
+ }
1726
+
1727
+ /**
1728
+ * Transforms a queryString into a {@link LocationQuery} object. Accept both, a
1729
+ * version with the leading `?` and without Should work as URLSearchParams
1730
+
1731
+ * @internal
1732
+ *
1733
+ * @param search - search string to parse
1734
+ * @returns a query object
1735
+ */
1736
+ function parseQuery(search) {
1737
+ const query = {};
1738
+ // avoid creating an object with an empty key and empty value
1739
+ // because of split('&')
1740
+ if (search === '' || search === '?')
1741
+ return query;
1742
+ const hasLeadingIM = search[0] === '?';
1743
+ const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
1744
+ for (let i = 0; i < searchParams.length; ++i) {
1745
+ // pre decode the + into space
1746
+ const searchParam = searchParams[i].replace(PLUS_RE, ' ');
1747
+ // allow the = character
1748
+ const eqPos = searchParam.indexOf('=');
1749
+ const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
1750
+ const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
1751
+ if (key in query) {
1752
+ // an extra variable for ts types
1753
+ let currentValue = query[key];
1754
+ if (!Array.isArray(currentValue)) {
1755
+ currentValue = query[key] = [currentValue];
1756
+ }
1757
+ currentValue.push(value);
1758
+ }
1759
+ else {
1760
+ query[key] = value;
1761
+ }
1762
+ }
1763
+ return query;
1764
+ }
1765
+ /**
1766
+ * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it
1767
+ * doesn't prepend a `?`
1768
+ *
1769
+ * @internal
1770
+ *
1771
+ * @param query - query object to stringify
1772
+ * @returns string version of the query without the leading `?`
1773
+ */
1774
+ function stringifyQuery(query) {
1775
+ let search = '';
1776
+ for (let key in query) {
1777
+ const value = query[key];
1778
+ key = encodeQueryKey(key);
1779
+ if (value == null) {
1780
+ // only null adds the value
1781
+ if (value !== undefined) {
1782
+ search += (search.length ? '&' : '') + key;
1783
+ }
1784
+ continue;
1785
+ }
1786
+ // keep null values
1787
+ const values = Array.isArray(value)
1788
+ ? value.map(v => v && encodeQueryValue(v))
1789
+ : [value && encodeQueryValue(value)];
1790
+ values.forEach(value => {
1791
+ // skip undefined values in arrays as if they were not present
1792
+ // smaller code than using filter
1793
+ if (value !== undefined) {
1794
+ // only append & with non-empty search
1795
+ search += (search.length ? '&' : '') + key;
1796
+ if (value != null)
1797
+ search += '=' + value;
1798
+ }
1799
+ });
1800
+ }
1801
+ return search;
1802
+ }
1803
+ /**
1804
+ * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting
1805
+ * numbers into strings, removing keys with an undefined value and replacing
1806
+ * undefined with null in arrays
1807
+ *
1808
+ * @param query - query object to normalize
1809
+ * @returns a normalized query object
1810
+ */
1811
+ function normalizeQuery(query) {
1812
+ const normalizedQuery = {};
1813
+ for (const key in query) {
1814
+ const value = query[key];
1815
+ if (value !== undefined) {
1816
+ normalizedQuery[key] = Array.isArray(value)
1817
+ ? value.map(v => (v == null ? null : '' + v))
1818
+ : value == null
1819
+ ? value
1820
+ : '' + value;
1821
+ }
1822
+ }
1823
+ return normalizedQuery;
1824
+ }
1825
+
1826
+ /**
1827
+ * Create a list of callbacks that can be reset. Used to create before and after navigation guards list
1828
+ */
1829
+ function useCallbacks() {
1830
+ let handlers = [];
1831
+ function add(handler) {
1832
+ handlers.push(handler);
1833
+ return () => {
1834
+ const i = handlers.indexOf(handler);
1835
+ if (i > -1)
1836
+ handlers.splice(i, 1);
1837
+ };
1838
+ }
1839
+ function reset() {
1840
+ handlers = [];
1841
+ }
1842
+ return {
1843
+ add,
1844
+ list: () => handlers,
1845
+ reset,
1846
+ };
1847
+ }
1848
+
1849
+ function registerGuard(record, name, guard) {
1850
+ const removeFromList = () => {
1851
+ record[name].delete(guard);
1852
+ };
1853
+ onUnmounted(removeFromList);
1854
+ onDeactivated(removeFromList);
1855
+ onActivated(() => {
1856
+ record[name].add(guard);
1857
+ });
1858
+ record[name].add(guard);
1859
+ }
1860
+ /**
1861
+ * Add a navigation guard that triggers whenever the component for the current
1862
+ * location is about to be left. Similar to {@link beforeRouteLeave} but can be
1863
+ * used in any component. The guard is removed when the component is unmounted.
1864
+ *
1865
+ * @param leaveGuard - {@link NavigationGuard}
1866
+ */
1867
+ function onBeforeRouteLeave(leaveGuard) {
1868
+ if ((process.env.NODE_ENV !== 'production') && !getCurrentInstance()) {
1869
+ warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function');
1870
+ return;
1871
+ }
1872
+ const activeRecord = inject(matchedRouteKey,
1873
+ // to avoid warning
1874
+ {}).value;
1875
+ if (!activeRecord) {
1876
+ (process.env.NODE_ENV !== 'production') &&
1877
+ warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside of a component child of <router-view>. Maybe you called it inside of App.vue?');
1878
+ return;
1879
+ }
1880
+ registerGuard(activeRecord, 'leaveGuards', leaveGuard);
1881
+ }
1882
+ /**
1883
+ * Add a navigation guard that triggers whenever the current location is about
1884
+ * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
1885
+ * component. The guard is removed when the component is unmounted.
1886
+ *
1887
+ * @param updateGuard - {@link NavigationGuard}
1888
+ */
1889
+ function onBeforeRouteUpdate(updateGuard) {
1890
+ if ((process.env.NODE_ENV !== 'production') && !getCurrentInstance()) {
1891
+ warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function');
1892
+ return;
1893
+ }
1894
+ const activeRecord = inject(matchedRouteKey,
1895
+ // to avoid warning
1896
+ {}).value;
1897
+ if (!activeRecord) {
1898
+ (process.env.NODE_ENV !== 'production') &&
1899
+ warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside of a component child of <router-view>. Maybe you called it inside of App.vue?');
1900
+ return;
1901
+ }
1902
+ registerGuard(activeRecord, 'updateGuards', updateGuard);
1903
+ }
1904
+ function guardToPromiseFn(guard, to, from, record, name) {
1905
+ // keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place
1906
+ const enterCallbackArray = record &&
1907
+ // name is defined if record is because of the function overload
1908
+ (record.enterCallbacks[name] = record.enterCallbacks[name] || []);
1909
+ return () => new Promise((resolve, reject) => {
1910
+ const next = (valid) => {
1911
+ if (valid === false)
1912
+ reject(createRouterError(4 /* NAVIGATION_ABORTED */, {
1913
+ from,
1914
+ to,
1915
+ }));
1916
+ else if (valid instanceof Error) {
1917
+ reject(valid);
1918
+ }
1919
+ else if (isRouteLocation(valid)) {
1920
+ reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, {
1921
+ from: to,
1922
+ to: valid,
1923
+ }));
1924
+ }
1925
+ else {
1926
+ if (enterCallbackArray &&
1927
+ // since enterCallbackArray is truthy, both record and name also are
1928
+ record.enterCallbacks[name] === enterCallbackArray &&
1929
+ typeof valid === 'function')
1930
+ enterCallbackArray.push(valid);
1931
+ resolve();
1932
+ }
1933
+ };
1934
+ // wrapping with Promise.resolve allows it to work with both async and sync guards
1935
+ const guardReturn = guard.call(record && record.instances[name], to, from, (process.env.NODE_ENV !== 'production') ? canOnlyBeCalledOnce(next, to, from) : next);
1936
+ let guardCall = Promise.resolve(guardReturn);
1937
+ if (guard.length < 3)
1938
+ guardCall = guardCall.then(next);
1939
+ if ((process.env.NODE_ENV !== 'production') && guard.length > 2) {
1940
+ const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
1941
+ if (typeof guardReturn === 'object' && 'then' in guardReturn) {
1942
+ guardCall = guardCall.then(resolvedValue => {
1943
+ // @ts-expect-error: _called is added at canOnlyBeCalledOnce
1944
+ if (!next._called) {
1945
+ warn(message);
1946
+ return Promise.reject(new Error('Invalid navigation guard'));
1947
+ }
1948
+ return resolvedValue;
1949
+ });
1950
+ // TODO: test me!
1951
+ }
1952
+ else if (guardReturn !== undefined) {
1953
+ // @ts-expect-error: _called is added at canOnlyBeCalledOnce
1954
+ if (!next._called) {
1955
+ warn(message);
1956
+ reject(new Error('Invalid navigation guard'));
1957
+ return;
1958
+ }
1959
+ }
1960
+ }
1961
+ guardCall.catch(err => reject(err));
1962
+ });
1963
+ }
1964
+ function canOnlyBeCalledOnce(next, to, from) {
1965
+ let called = 0;
1966
+ return function () {
1967
+ if (called++ === 1)
1968
+ warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`);
1969
+ // @ts-expect-error: we put it in the original one because it's easier to check
1970
+ next._called = true;
1971
+ if (called === 1)
1972
+ next.apply(null, arguments);
1973
+ };
1974
+ }
1975
+ function extractComponentsGuards(matched, guardType, to, from) {
1976
+ const guards = [];
1977
+ for (const record of matched) {
1978
+ for (const name in record.components) {
1979
+ let rawComponent = record.components[name];
1980
+ if ((process.env.NODE_ENV !== 'production')) {
1981
+ if (!rawComponent ||
1982
+ (typeof rawComponent !== 'object' &&
1983
+ typeof rawComponent !== 'function')) {
1984
+ warn(`Component "${name}" in record with path "${record.path}" is not` +
1985
+ ` a valid component. Received "${String(rawComponent)}".`);
1986
+ // throw to ensure we stop here but warn to ensure the message isn't
1987
+ // missed by the user
1988
+ throw new Error('Invalid route component');
1989
+ }
1990
+ else if ('then' in rawComponent) {
1991
+ // warn if user wrote import('/component.vue') instead of () =>
1992
+ // import('./component.vue')
1993
+ warn(`Component "${name}" in record with path "${record.path}" is a ` +
1994
+ `Promise instead of a function that returns a Promise. Did you ` +
1995
+ `write "import('./MyPage.vue')" instead of ` +
1996
+ `"() => import('./MyPage.vue')" ? This will break in ` +
1997
+ `production if not fixed.`);
1998
+ const promise = rawComponent;
1999
+ rawComponent = () => promise;
2000
+ }
2001
+ else if (rawComponent.__asyncLoader &&
2002
+ // warn only once per component
2003
+ !rawComponent.__warnedDefineAsync) {
2004
+ rawComponent.__warnedDefineAsync = true;
2005
+ warn(`Component "${name}" in record with path "${record.path}" is defined ` +
2006
+ `using "defineAsyncComponent()". ` +
2007
+ `Write "() => import('./MyPage.vue')" instead of ` +
2008
+ `"defineAsyncComponent(() => import('./MyPage.vue'))".`);
2009
+ }
2010
+ }
2011
+ // skip update and leave guards if the route component is not mounted
2012
+ if (guardType !== 'beforeRouteEnter' && !record.instances[name])
2013
+ continue;
2014
+ if (isRouteComponent(rawComponent)) {
2015
+ // __vccOpts is added by vue-class-component and contain the regular options
2016
+ const options = rawComponent.__vccOpts || rawComponent;
2017
+ const guard = options[guardType];
2018
+ guard && guards.push(guardToPromiseFn(guard, to, from, record, name));
2019
+ }
2020
+ else {
2021
+ // start requesting the chunk already
2022
+ let componentPromise = rawComponent();
2023
+ if ((process.env.NODE_ENV !== 'production') && !('catch' in componentPromise)) {
2024
+ warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`);
2025
+ componentPromise = Promise.resolve(componentPromise);
2026
+ }
2027
+ guards.push(() => componentPromise.then(resolved => {
2028
+ if (!resolved)
2029
+ return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`));
2030
+ const resolvedComponent = isESModule(resolved)
2031
+ ? resolved.default
2032
+ : resolved;
2033
+ // replace the function with the resolved component
2034
+ record.components[name] = resolvedComponent;
2035
+ // __vccOpts is added by vue-class-component and contain the regular options
2036
+ const options = resolvedComponent.__vccOpts || resolvedComponent;
2037
+ const guard = options[guardType];
2038
+ return guard && guardToPromiseFn(guard, to, from, record, name)();
2039
+ }));
2040
+ }
2041
+ }
2042
+ }
2043
+ return guards;
2044
+ }
2045
+ /**
2046
+ * Allows differentiating lazy components from functional components and vue-class-component
2047
+ *
2048
+ * @param component
2049
+ */
2050
+ function isRouteComponent(component) {
2051
+ return (typeof component === 'object' ||
2052
+ 'displayName' in component ||
2053
+ 'props' in component ||
2054
+ '__vccOpts' in component);
2055
+ }
2056
+
2057
+ // TODO: we could allow currentRoute as a prop to expose `isActive` and
2058
+ // `isExactActive` behavior should go through an RFC
2059
+ function useLink(props) {
2060
+ const router = inject(routerKey);
2061
+ const currentRoute = inject(routeLocationKey);
2062
+ const route = computed(() => router.resolve(unref(props.to)));
2063
+ const activeRecordIndex = computed(() => {
2064
+ const { matched } = route.value;
2065
+ const { length } = matched;
2066
+ const routeMatched = matched[length - 1];
2067
+ const currentMatched = currentRoute.matched;
2068
+ if (!routeMatched || !currentMatched.length)
2069
+ return -1;
2070
+ const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
2071
+ if (index > -1)
2072
+ return index;
2073
+ // possible parent record
2074
+ const parentRecordPath = getOriginalPath(matched[length - 2]);
2075
+ return (
2076
+ // we are dealing with nested routes
2077
+ length > 1 &&
2078
+ // if the parent and matched route have the same path, this link is
2079
+ // referring to the empty child. Or we currently are on a different
2080
+ // child of the same parent
2081
+ getOriginalPath(routeMatched) === parentRecordPath &&
2082
+ // avoid comparing the child with its parent
2083
+ currentMatched[currentMatched.length - 1].path !== parentRecordPath
2084
+ ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2]))
2085
+ : index);
2086
+ });
2087
+ const isActive = computed(() => activeRecordIndex.value > -1 &&
2088
+ includesParams(currentRoute.params, route.value.params));
2089
+ const isExactActive = computed(() => activeRecordIndex.value > -1 &&
2090
+ activeRecordIndex.value === currentRoute.matched.length - 1 &&
2091
+ isSameRouteLocationParams(currentRoute.params, route.value.params));
2092
+ function navigate(e = {}) {
2093
+ if (guardEvent(e)) {
2094
+ return router[unref(props.replace) ? 'replace' : 'push'](unref(props.to)
2095
+ // avoid uncaught errors are they are logged anyway
2096
+ ).catch(noop);
2097
+ }
2098
+ return Promise.resolve();
2099
+ }
2100
+ // devtools only
2101
+ if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && isBrowser) {
2102
+ const instance = getCurrentInstance();
2103
+ if (instance) {
2104
+ const linkContextDevtools = {
2105
+ route: route.value,
2106
+ isActive: isActive.value,
2107
+ isExactActive: isExactActive.value,
2108
+ };
2109
+ // @ts-expect-error: this is internal
2110
+ instance.__vrl_devtools = instance.__vrl_devtools || [];
2111
+ // @ts-expect-error: this is internal
2112
+ instance.__vrl_devtools.push(linkContextDevtools);
2113
+ watchEffect(() => {
2114
+ linkContextDevtools.route = route.value;
2115
+ linkContextDevtools.isActive = isActive.value;
2116
+ linkContextDevtools.isExactActive = isExactActive.value;
2117
+ }, { flush: 'post' });
2118
+ }
2119
+ }
2120
+ return {
2121
+ route,
2122
+ href: computed(() => route.value.href),
2123
+ isActive,
2124
+ isExactActive,
2125
+ navigate,
2126
+ };
2127
+ }
2128
+ const RouterLinkImpl = /*#__PURE__*/ defineComponent({
2129
+ name: 'RouterLink',
2130
+ props: {
2131
+ to: {
2132
+ type: [String, Object],
2133
+ required: true,
2134
+ },
2135
+ replace: Boolean,
2136
+ activeClass: String,
2137
+ // inactiveClass: String,
2138
+ exactActiveClass: String,
2139
+ custom: Boolean,
2140
+ ariaCurrentValue: {
2141
+ type: String,
2142
+ default: 'page',
2143
+ },
2144
+ },
2145
+ useLink,
2146
+ setup(props, { slots }) {
2147
+ const link = reactive(useLink(props));
2148
+ const { options } = inject(routerKey);
2149
+ const elClass = computed(() => ({
2150
+ [getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive,
2151
+ // [getLinkClass(
2152
+ // props.inactiveClass,
2153
+ // options.linkInactiveClass,
2154
+ // 'router-link-inactive'
2155
+ // )]: !link.isExactActive,
2156
+ [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive,
2157
+ }));
2158
+ return () => {
2159
+ const children = slots.default && slots.default(link);
2160
+ return props.custom
2161
+ ? children
2162
+ : h('a', {
2163
+ 'aria-current': link.isExactActive
2164
+ ? props.ariaCurrentValue
2165
+ : null,
2166
+ href: link.href,
2167
+ // this would override user added attrs but Vue will still add
2168
+ // the listener so we end up triggering both
2169
+ onClick: link.navigate,
2170
+ class: elClass.value,
2171
+ }, children);
2172
+ };
2173
+ },
2174
+ });
2175
+ // export the public type for h/tsx inference
2176
+ // also to avoid inline import() in generated d.ts files
2177
+ /**
2178
+ * Component to render a link that triggers a navigation on click.
2179
+ */
2180
+ const RouterLink = RouterLinkImpl;
2181
+ function guardEvent(e) {
2182
+ // don't redirect with control keys
2183
+ if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
2184
+ return;
2185
+ // don't redirect when preventDefault called
2186
+ if (e.defaultPrevented)
2187
+ return;
2188
+ // don't redirect on right click
2189
+ if (e.button !== undefined && e.button !== 0)
2190
+ return;
2191
+ // don't redirect if `target="_blank"`
2192
+ // @ts-expect-error getAttribute does exist
2193
+ if (e.currentTarget && e.currentTarget.getAttribute) {
2194
+ // @ts-expect-error getAttribute exists
2195
+ const target = e.currentTarget.getAttribute('target');
2196
+ if (/\b_blank\b/i.test(target))
2197
+ return;
2198
+ }
2199
+ // this may be a Weex event which doesn't have this method
2200
+ if (e.preventDefault)
2201
+ e.preventDefault();
2202
+ return true;
2203
+ }
2204
+ function includesParams(outer, inner) {
2205
+ for (const key in inner) {
2206
+ const innerValue = inner[key];
2207
+ const outerValue = outer[key];
2208
+ if (typeof innerValue === 'string') {
2209
+ if (innerValue !== outerValue)
2210
+ return false;
2211
+ }
2212
+ else {
2213
+ if (!Array.isArray(outerValue) ||
2214
+ outerValue.length !== innerValue.length ||
2215
+ innerValue.some((value, i) => value !== outerValue[i]))
2216
+ return false;
2217
+ }
2218
+ }
2219
+ return true;
2220
+ }
2221
+ /**
2222
+ * Get the original path value of a record by following its aliasOf
2223
+ * @param record
2224
+ */
2225
+ function getOriginalPath(record) {
2226
+ return record ? (record.aliasOf ? record.aliasOf.path : record.path) : '';
2227
+ }
2228
+ /**
2229
+ * Utility class to get the active class based on defaults.
2230
+ * @param propClass
2231
+ * @param globalClass
2232
+ * @param defaultClass
2233
+ */
2234
+ const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null
2235
+ ? propClass
2236
+ : globalClass != null
2237
+ ? globalClass
2238
+ : defaultClass;
2239
+
2240
+ const RouterViewImpl = /*#__PURE__*/ defineComponent({
2241
+ name: 'RouterView',
2242
+ // #674 we manually inherit them
2243
+ inheritAttrs: false,
2244
+ props: {
2245
+ name: {
2246
+ type: String,
2247
+ default: 'default',
2248
+ },
2249
+ route: Object,
2250
+ },
2251
+ // Better compat for @vue/compat users
2252
+ // https://github.com/vuejs/router/issues/1315
2253
+ compatConfig: { MODE: 3 },
2254
+ setup(props, { attrs, slots }) {
2255
+ (process.env.NODE_ENV !== 'production') && warnDeprecatedUsage();
2256
+ const injectedRoute = inject(routerViewLocationKey);
2257
+ const routeToDisplay = computed(() => props.route || injectedRoute.value);
2258
+ const depth = inject(viewDepthKey, 0);
2259
+ const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth]);
2260
+ provide(viewDepthKey, depth + 1);
2261
+ provide(matchedRouteKey, matchedRouteRef);
2262
+ provide(routerViewLocationKey, routeToDisplay);
2263
+ const viewRef = ref();
2264
+ // watch at the same time the component instance, the route record we are
2265
+ // rendering, and the name
2266
+ watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => {
2267
+ // copy reused instances
2268
+ if (to) {
2269
+ // this will update the instance for new instances as well as reused
2270
+ // instances when navigating to a new route
2271
+ to.instances[name] = instance;
2272
+ // the component instance is reused for a different route or name so
2273
+ // we copy any saved update or leave guards. With async setup, the
2274
+ // mounting component will mount before the matchedRoute changes,
2275
+ // making instance === oldInstance, so we check if guards have been
2276
+ // added before. This works because we remove guards when
2277
+ // unmounting/deactivating components
2278
+ if (from && from !== to && instance && instance === oldInstance) {
2279
+ if (!to.leaveGuards.size) {
2280
+ to.leaveGuards = from.leaveGuards;
2281
+ }
2282
+ if (!to.updateGuards.size) {
2283
+ to.updateGuards = from.updateGuards;
2284
+ }
2285
+ }
2286
+ }
2287
+ // trigger beforeRouteEnter next callbacks
2288
+ if (instance &&
2289
+ to &&
2290
+ // if there is no instance but to and from are the same this might be
2291
+ // the first visit
2292
+ (!from || !isSameRouteRecord(to, from) || !oldInstance)) {
2293
+ (to.enterCallbacks[name] || []).forEach(callback => callback(instance));
2294
+ }
2295
+ }, { flush: 'post' });
2296
+ return () => {
2297
+ const route = routeToDisplay.value;
2298
+ const matchedRoute = matchedRouteRef.value;
2299
+ const ViewComponent = matchedRoute && matchedRoute.components[props.name];
2300
+ // we need the value at the time we render because when we unmount, we
2301
+ // navigated to a different location so the value is different
2302
+ const currentName = props.name;
2303
+ if (!ViewComponent) {
2304
+ return normalizeSlot(slots.default, { Component: ViewComponent, route });
2305
+ }
2306
+ // props from route configuration
2307
+ const routePropsOption = matchedRoute.props[props.name];
2308
+ const routeProps = routePropsOption
2309
+ ? routePropsOption === true
2310
+ ? route.params
2311
+ : typeof routePropsOption === 'function'
2312
+ ? routePropsOption(route)
2313
+ : routePropsOption
2314
+ : null;
2315
+ const onVnodeUnmounted = vnode => {
2316
+ // remove the instance reference to prevent leak
2317
+ if (vnode.component.isUnmounted) {
2318
+ matchedRoute.instances[currentName] = null;
2319
+ }
2320
+ };
2321
+ const component = h(ViewComponent, assign({}, routeProps, attrs, {
2322
+ onVnodeUnmounted,
2323
+ ref: viewRef,
2324
+ }));
2325
+ if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&
2326
+ isBrowser &&
2327
+ component.ref) {
2328
+ // TODO: can display if it's an alias, its props
2329
+ const info = {
2330
+ depth,
2331
+ name: matchedRoute.name,
2332
+ path: matchedRoute.path,
2333
+ meta: matchedRoute.meta,
2334
+ };
2335
+ const internalInstances = Array.isArray(component.ref)
2336
+ ? component.ref.map(r => r.i)
2337
+ : [component.ref.i];
2338
+ internalInstances.forEach(instance => {
2339
+ // @ts-expect-error
2340
+ instance.__vrv_devtools = info;
2341
+ });
2342
+ }
2343
+ return (
2344
+ // pass the vnode to the slot as a prop.
2345
+ // h and <component :is="..."> both accept vnodes
2346
+ normalizeSlot(slots.default, { Component: component, route }) ||
2347
+ component);
2348
+ };
2349
+ },
2350
+ });
2351
+ function normalizeSlot(slot, data) {
2352
+ if (!slot)
2353
+ return null;
2354
+ const slotContent = slot(data);
2355
+ return slotContent.length === 1 ? slotContent[0] : slotContent;
2356
+ }
2357
+ // export the public type for h/tsx inference
2358
+ // also to avoid inline import() in generated d.ts files
2359
+ /**
2360
+ * Component to display the current route the user is at.
2361
+ */
2362
+ const RouterView = RouterViewImpl;
2363
+ // warn against deprecated usage with <transition> & <keep-alive>
2364
+ // due to functional component being no longer eager in Vue 3
2365
+ function warnDeprecatedUsage() {
2366
+ const instance = getCurrentInstance();
2367
+ const parentName = instance.parent && instance.parent.type.name;
2368
+ if (parentName &&
2369
+ (parentName === 'KeepAlive' || parentName.includes('Transition'))) {
2370
+ const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition';
2371
+ warn(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.\n` +
2372
+ `Use slot props instead:\n\n` +
2373
+ `<router-view v-slot="{ Component }">\n` +
2374
+ ` <${comp}>\n` +
2375
+ ` <component :is="Component" />\n` +
2376
+ ` </${comp}>\n` +
2377
+ `</router-view>`);
2378
+ }
2379
+ }
2380
+
2381
+ function formatRouteLocation(routeLocation, tooltip) {
2382
+ const copy = assign({}, routeLocation, {
2383
+ // remove variables that can contain vue instances
2384
+ matched: routeLocation.matched.map(matched => omit(matched, ['instances', 'children', 'aliasOf'])),
2385
+ });
2386
+ return {
2387
+ _custom: {
2388
+ type: null,
2389
+ readOnly: true,
2390
+ display: routeLocation.fullPath,
2391
+ tooltip,
2392
+ value: copy,
2393
+ },
2394
+ };
2395
+ }
2396
+ function formatDisplay(display) {
2397
+ return {
2398
+ _custom: {
2399
+ display,
2400
+ },
2401
+ };
2402
+ }
2403
+ // to support multiple router instances
2404
+ let routerId = 0;
2405
+ function addDevtools(app, router, matcher) {
2406
+ // Take over router.beforeEach and afterEach
2407
+ // make sure we are not registering the devtool twice
2408
+ if (router.__hasDevtools)
2409
+ return;
2410
+ router.__hasDevtools = true;
2411
+ // increment to support multiple router instances
2412
+ const id = routerId++;
2413
+ setupDevtoolsPlugin({
2414
+ id: 'org.vuejs.router' + (id ? '.' + id : ''),
2415
+ label: 'Vue Router',
2416
+ packageName: 'vue-router',
2417
+ homepage: 'https://router.vuejs.org',
2418
+ logo: 'https://router.vuejs.org/logo.png',
2419
+ componentStateTypes: ['Routing'],
2420
+ app,
2421
+ }, api => {
2422
+ // display state added by the router
2423
+ api.on.inspectComponent((payload, ctx) => {
2424
+ if (payload.instanceData) {
2425
+ payload.instanceData.state.push({
2426
+ type: 'Routing',
2427
+ key: '$route',
2428
+ editable: false,
2429
+ value: formatRouteLocation(router.currentRoute.value, 'Current Route'),
2430
+ });
2431
+ }
2432
+ });
2433
+ // mark router-link as active and display tags on router views
2434
+ api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
2435
+ if (componentInstance.__vrv_devtools) {
2436
+ const info = componentInstance.__vrv_devtools;
2437
+ node.tags.push({
2438
+ label: (info.name ? `${info.name.toString()}: ` : '') + info.path,
2439
+ textColor: 0,
2440
+ tooltip: 'This component is rendered by &lt;router-view&gt;',
2441
+ backgroundColor: PINK_500,
2442
+ });
2443
+ }
2444
+ // if multiple useLink are used
2445
+ if (Array.isArray(componentInstance.__vrl_devtools)) {
2446
+ componentInstance.__devtoolsApi = api;
2447
+ componentInstance.__vrl_devtools.forEach(devtoolsData => {
2448
+ let backgroundColor = ORANGE_400;
2449
+ let tooltip = '';
2450
+ if (devtoolsData.isExactActive) {
2451
+ backgroundColor = LIME_500;
2452
+ tooltip = 'This is exactly active';
2453
+ }
2454
+ else if (devtoolsData.isActive) {
2455
+ backgroundColor = BLUE_600;
2456
+ tooltip = 'This link is active';
2457
+ }
2458
+ node.tags.push({
2459
+ label: devtoolsData.route.path,
2460
+ textColor: 0,
2461
+ tooltip,
2462
+ backgroundColor,
2463
+ });
2464
+ });
2465
+ }
2466
+ });
2467
+ watch(router.currentRoute, () => {
2468
+ // refresh active state
2469
+ refreshRoutesView();
2470
+ api.notifyComponentUpdate();
2471
+ api.sendInspectorTree(routerInspectorId);
2472
+ api.sendInspectorState(routerInspectorId);
2473
+ });
2474
+ const navigationsLayerId = 'router:navigations:' + id;
2475
+ api.addTimelineLayer({
2476
+ id: navigationsLayerId,
2477
+ label: `Router${id ? ' ' + id : ''} Navigations`,
2478
+ color: 0x40a8c4,
2479
+ });
2480
+ // const errorsLayerId = 'router:errors'
2481
+ // api.addTimelineLayer({
2482
+ // id: errorsLayerId,
2483
+ // label: 'Router Errors',
2484
+ // color: 0xea5455,
2485
+ // })
2486
+ router.onError((error, to) => {
2487
+ api.addTimelineEvent({
2488
+ layerId: navigationsLayerId,
2489
+ event: {
2490
+ title: 'Error during Navigation',
2491
+ subtitle: to.fullPath,
2492
+ logType: 'error',
2493
+ time: api.now(),
2494
+ data: { error },
2495
+ groupId: to.meta.__navigationId,
2496
+ },
2497
+ });
2498
+ });
2499
+ // attached to `meta` and used to group events
2500
+ let navigationId = 0;
2501
+ router.beforeEach((to, from) => {
2502
+ const data = {
2503
+ guard: formatDisplay('beforeEach'),
2504
+ from: formatRouteLocation(from, 'Current Location during this navigation'),
2505
+ to: formatRouteLocation(to, 'Target location'),
2506
+ };
2507
+ // Used to group navigations together, hide from devtools
2508
+ Object.defineProperty(to.meta, '__navigationId', {
2509
+ value: navigationId++,
2510
+ });
2511
+ api.addTimelineEvent({
2512
+ layerId: navigationsLayerId,
2513
+ event: {
2514
+ time: api.now(),
2515
+ title: 'Start of navigation',
2516
+ subtitle: to.fullPath,
2517
+ data,
2518
+ groupId: to.meta.__navigationId,
2519
+ },
2520
+ });
2521
+ });
2522
+ router.afterEach((to, from, failure) => {
2523
+ const data = {
2524
+ guard: formatDisplay('afterEach'),
2525
+ };
2526
+ if (failure) {
2527
+ data.failure = {
2528
+ _custom: {
2529
+ type: Error,
2530
+ readOnly: true,
2531
+ display: failure ? failure.message : '',
2532
+ tooltip: 'Navigation Failure',
2533
+ value: failure,
2534
+ },
2535
+ };
2536
+ data.status = formatDisplay('❌');
2537
+ }
2538
+ else {
2539
+ data.status = formatDisplay('✅');
2540
+ }
2541
+ // we set here to have the right order
2542
+ data.from = formatRouteLocation(from, 'Current Location during this navigation');
2543
+ data.to = formatRouteLocation(to, 'Target location');
2544
+ api.addTimelineEvent({
2545
+ layerId: navigationsLayerId,
2546
+ event: {
2547
+ title: 'End of navigation',
2548
+ subtitle: to.fullPath,
2549
+ time: api.now(),
2550
+ data,
2551
+ logType: failure ? 'warning' : 'default',
2552
+ groupId: to.meta.__navigationId,
2553
+ },
2554
+ });
2555
+ });
2556
+ /**
2557
+ * Inspector of Existing routes
2558
+ */
2559
+ const routerInspectorId = 'router-inspector:' + id;
2560
+ api.addInspector({
2561
+ id: routerInspectorId,
2562
+ label: 'Routes' + (id ? ' ' + id : ''),
2563
+ icon: 'book',
2564
+ treeFilterPlaceholder: 'Search routes',
2565
+ });
2566
+ function refreshRoutesView() {
2567
+ // the routes view isn't active
2568
+ if (!activeRoutesPayload)
2569
+ return;
2570
+ const payload = activeRoutesPayload;
2571
+ // children routes will appear as nested
2572
+ let routes = matcher.getRoutes().filter(route => !route.parent);
2573
+ // reset match state to false
2574
+ routes.forEach(resetMatchStateOnRouteRecord);
2575
+ // apply a match state if there is a payload
2576
+ if (payload.filter) {
2577
+ routes = routes.filter(route =>
2578
+ // save matches state based on the payload
2579
+ isRouteMatching(route, payload.filter.toLowerCase()));
2580
+ }
2581
+ // mark active routes
2582
+ routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value));
2583
+ payload.rootNodes = routes.map(formatRouteRecordForInspector);
2584
+ }
2585
+ let activeRoutesPayload;
2586
+ api.on.getInspectorTree(payload => {
2587
+ activeRoutesPayload = payload;
2588
+ if (payload.app === app && payload.inspectorId === routerInspectorId) {
2589
+ refreshRoutesView();
2590
+ }
2591
+ });
2592
+ /**
2593
+ * Display information about the currently selected route record
2594
+ */
2595
+ api.on.getInspectorState(payload => {
2596
+ if (payload.app === app && payload.inspectorId === routerInspectorId) {
2597
+ const routes = matcher.getRoutes();
2598
+ const route = routes.find(route => route.record.__vd_id === payload.nodeId);
2599
+ if (route) {
2600
+ payload.state = {
2601
+ options: formatRouteRecordMatcherForStateInspector(route),
2602
+ };
2603
+ }
2604
+ }
2605
+ });
2606
+ api.sendInspectorTree(routerInspectorId);
2607
+ api.sendInspectorState(routerInspectorId);
2608
+ });
2609
+ }
2610
+ function modifierForKey(key) {
2611
+ if (key.optional) {
2612
+ return key.repeatable ? '*' : '?';
2613
+ }
2614
+ else {
2615
+ return key.repeatable ? '+' : '';
2616
+ }
2617
+ }
2618
+ function formatRouteRecordMatcherForStateInspector(route) {
2619
+ const { record } = route;
2620
+ const fields = [
2621
+ { editable: false, key: 'path', value: record.path },
2622
+ ];
2623
+ if (record.name != null) {
2624
+ fields.push({
2625
+ editable: false,
2626
+ key: 'name',
2627
+ value: record.name,
2628
+ });
2629
+ }
2630
+ fields.push({ editable: false, key: 'regexp', value: route.re });
2631
+ if (route.keys.length) {
2632
+ fields.push({
2633
+ editable: false,
2634
+ key: 'keys',
2635
+ value: {
2636
+ _custom: {
2637
+ type: null,
2638
+ readOnly: true,
2639
+ display: route.keys
2640
+ .map(key => `${key.name}${modifierForKey(key)}`)
2641
+ .join(' '),
2642
+ tooltip: 'Param keys',
2643
+ value: route.keys,
2644
+ },
2645
+ },
2646
+ });
2647
+ }
2648
+ if (record.redirect != null) {
2649
+ fields.push({
2650
+ editable: false,
2651
+ key: 'redirect',
2652
+ value: record.redirect,
2653
+ });
2654
+ }
2655
+ if (route.alias.length) {
2656
+ fields.push({
2657
+ editable: false,
2658
+ key: 'aliases',
2659
+ value: route.alias.map(alias => alias.record.path),
2660
+ });
2661
+ }
2662
+ fields.push({
2663
+ key: 'score',
2664
+ editable: false,
2665
+ value: {
2666
+ _custom: {
2667
+ type: null,
2668
+ readOnly: true,
2669
+ display: route.score.map(score => score.join(', ')).join(' | '),
2670
+ tooltip: 'Score used to sort routes',
2671
+ value: route.score,
2672
+ },
2673
+ },
2674
+ });
2675
+ return fields;
2676
+ }
2677
+ /**
2678
+ * Extracted from tailwind palette
2679
+ */
2680
+ const PINK_500 = 0xec4899;
2681
+ const BLUE_600 = 0x2563eb;
2682
+ const LIME_500 = 0x84cc16;
2683
+ const CYAN_400 = 0x22d3ee;
2684
+ const ORANGE_400 = 0xfb923c;
2685
+ // const GRAY_100 = 0xf4f4f5
2686
+ const DARK = 0x666666;
2687
+ function formatRouteRecordForInspector(route) {
2688
+ const tags = [];
2689
+ const { record } = route;
2690
+ if (record.name != null) {
2691
+ tags.push({
2692
+ label: String(record.name),
2693
+ textColor: 0,
2694
+ backgroundColor: CYAN_400,
2695
+ });
2696
+ }
2697
+ if (record.aliasOf) {
2698
+ tags.push({
2699
+ label: 'alias',
2700
+ textColor: 0,
2701
+ backgroundColor: ORANGE_400,
2702
+ });
2703
+ }
2704
+ if (route.__vd_match) {
2705
+ tags.push({
2706
+ label: 'matches',
2707
+ textColor: 0,
2708
+ backgroundColor: PINK_500,
2709
+ });
2710
+ }
2711
+ if (route.__vd_exactActive) {
2712
+ tags.push({
2713
+ label: 'exact',
2714
+ textColor: 0,
2715
+ backgroundColor: LIME_500,
2716
+ });
2717
+ }
2718
+ if (route.__vd_active) {
2719
+ tags.push({
2720
+ label: 'active',
2721
+ textColor: 0,
2722
+ backgroundColor: BLUE_600,
2723
+ });
2724
+ }
2725
+ if (record.redirect) {
2726
+ tags.push({
2727
+ label: 'redirect: ' +
2728
+ (typeof record.redirect === 'string' ? record.redirect : 'Object'),
2729
+ textColor: 0xffffff,
2730
+ backgroundColor: DARK,
2731
+ });
2732
+ }
2733
+ // add an id to be able to select it. Using the `path` is not possible because
2734
+ // empty path children would collide with their parents
2735
+ let id = record.__vd_id;
2736
+ if (id == null) {
2737
+ id = String(routeRecordId++);
2738
+ record.__vd_id = id;
2739
+ }
2740
+ return {
2741
+ id,
2742
+ label: record.path,
2743
+ tags,
2744
+ children: route.children.map(formatRouteRecordForInspector),
2745
+ };
2746
+ }
2747
+ // incremental id for route records and inspector state
2748
+ let routeRecordId = 0;
2749
+ const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
2750
+ function markRouteRecordActive(route, currentRoute) {
2751
+ // no route will be active if matched is empty
2752
+ // reset the matching state
2753
+ const isExactActive = currentRoute.matched.length &&
2754
+ isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
2755
+ route.__vd_exactActive = route.__vd_active = isExactActive;
2756
+ if (!isExactActive) {
2757
+ route.__vd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record));
2758
+ }
2759
+ route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute));
2760
+ }
2761
+ function resetMatchStateOnRouteRecord(route) {
2762
+ route.__vd_match = false;
2763
+ route.children.forEach(resetMatchStateOnRouteRecord);
2764
+ }
2765
+ function isRouteMatching(route, filter) {
2766
+ const found = String(route.re).match(EXTRACT_REGEXP_RE);
2767
+ route.__vd_match = false;
2768
+ if (!found || found.length < 3) {
2769
+ return false;
2770
+ }
2771
+ // use a regexp without $ at the end to match nested routes better
2772
+ const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]);
2773
+ if (nonEndingRE.test(filter)) {
2774
+ // mark children as matches
2775
+ route.children.forEach(child => isRouteMatching(child, filter));
2776
+ // exception case: `/`
2777
+ if (route.record.path !== '/' || filter === '/') {
2778
+ route.__vd_match = route.re.test(filter);
2779
+ return true;
2780
+ }
2781
+ // hide the / route
2782
+ return false;
2783
+ }
2784
+ const path = route.record.path.toLowerCase();
2785
+ const decodedPath = decode(path);
2786
+ // also allow partial matching on the path
2787
+ if (!filter.startsWith('/') &&
2788
+ (decodedPath.includes(filter) || path.includes(filter)))
2789
+ return true;
2790
+ if (decodedPath.startsWith(filter) || path.startsWith(filter))
2791
+ return true;
2792
+ if (route.record.name && String(route.record.name).includes(filter))
2793
+ return true;
2794
+ return route.children.some(child => isRouteMatching(child, filter));
2795
+ }
2796
+ function omit(obj, keys) {
2797
+ const ret = {};
2798
+ for (const key in obj) {
2799
+ if (!keys.includes(key)) {
2800
+ // @ts-expect-error
2801
+ ret[key] = obj[key];
2802
+ }
2803
+ }
2804
+ return ret;
2805
+ }
2806
+
2807
+ /**
2808
+ * Creates a Router instance that can be used by a Vue app.
2809
+ *
2810
+ * @param options - {@link RouterOptions}
2811
+ */
2812
+ function createRouter(options) {
2813
+ const matcher = createRouterMatcher(options.routes, options);
2814
+ const parseQuery$1 = options.parseQuery || parseQuery;
2815
+ const stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
2816
+ const routerHistory = options.history;
2817
+ if ((process.env.NODE_ENV !== 'production') && !routerHistory)
2818
+ throw new Error('Provide the "history" option when calling "createRouter()":' +
2819
+ ' https://next.router.vuejs.org/api/#history.');
2820
+ const beforeGuards = useCallbacks();
2821
+ const beforeResolveGuards = useCallbacks();
2822
+ const afterGuards = useCallbacks();
2823
+ const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
2824
+ let pendingLocation = START_LOCATION_NORMALIZED;
2825
+ // leave the scrollRestoration if no scrollBehavior is provided
2826
+ if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) {
2827
+ history.scrollRestoration = 'manual';
2828
+ }
2829
+ const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue);
2830
+ const encodeParams = applyToParams.bind(null, encodeParam);
2831
+ const decodeParams =
2832
+ // @ts-expect-error: intentionally avoid the type check
2833
+ applyToParams.bind(null, decode);
2834
+ function addRoute(parentOrRoute, route) {
2835
+ let parent;
2836
+ let record;
2837
+ if (isRouteName(parentOrRoute)) {
2838
+ parent = matcher.getRecordMatcher(parentOrRoute);
2839
+ record = route;
2840
+ }
2841
+ else {
2842
+ record = parentOrRoute;
2843
+ }
2844
+ return matcher.addRoute(record, parent);
2845
+ }
2846
+ function removeRoute(name) {
2847
+ const recordMatcher = matcher.getRecordMatcher(name);
2848
+ if (recordMatcher) {
2849
+ matcher.removeRoute(recordMatcher);
2850
+ }
2851
+ else if ((process.env.NODE_ENV !== 'production')) {
2852
+ warn(`Cannot remove non-existent route "${String(name)}"`);
2853
+ }
2854
+ }
2855
+ function getRoutes() {
2856
+ return matcher.getRoutes().map(routeMatcher => routeMatcher.record);
2857
+ }
2858
+ function hasRoute(name) {
2859
+ return !!matcher.getRecordMatcher(name);
2860
+ }
2861
+ function resolve(rawLocation, currentLocation) {
2862
+ // const objectLocation = routerLocationAsObject(rawLocation)
2863
+ // we create a copy to modify it later
2864
+ currentLocation = assign({}, currentLocation || currentRoute.value);
2865
+ if (typeof rawLocation === 'string') {
2866
+ const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
2867
+ const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation);
2868
+ const href = routerHistory.createHref(locationNormalized.fullPath);
2869
+ if ((process.env.NODE_ENV !== 'production')) {
2870
+ if (href.startsWith('//'))
2871
+ warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
2872
+ else if (!matchedRoute.matched.length) {
2873
+ warn(`No match found for location with path "${rawLocation}"`);
2874
+ }
2875
+ }
2876
+ // locationNormalized is always a new object
2877
+ return assign(locationNormalized, matchedRoute, {
2878
+ params: decodeParams(matchedRoute.params),
2879
+ hash: decode(locationNormalized.hash),
2880
+ redirectedFrom: undefined,
2881
+ href,
2882
+ });
2883
+ }
2884
+ let matcherLocation;
2885
+ // path could be relative in object as well
2886
+ if ('path' in rawLocation) {
2887
+ if ((process.env.NODE_ENV !== 'production') &&
2888
+ 'params' in rawLocation &&
2889
+ !('name' in rawLocation) &&
2890
+ // @ts-expect-error: the type is never
2891
+ Object.keys(rawLocation.params).length) {
2892
+ warn(`Path "${
2893
+ // @ts-expect-error: the type is never
2894
+ rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
2895
+ }
2896
+ matcherLocation = assign({}, rawLocation, {
2897
+ path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path,
2898
+ });
2899
+ }
2900
+ else {
2901
+ // remove any nullish param
2902
+ const targetParams = assign({}, rawLocation.params);
2903
+ for (const key in targetParams) {
2904
+ if (targetParams[key] == null) {
2905
+ delete targetParams[key];
2906
+ }
2907
+ }
2908
+ // pass encoded values to the matcher so it can produce encoded path and fullPath
2909
+ matcherLocation = assign({}, rawLocation, {
2910
+ params: encodeParams(rawLocation.params),
2911
+ });
2912
+ // current location params are decoded, we need to encode them in case the
2913
+ // matcher merges the params
2914
+ currentLocation.params = encodeParams(currentLocation.params);
2915
+ }
2916
+ const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
2917
+ const hash = rawLocation.hash || '';
2918
+ if ((process.env.NODE_ENV !== 'production') && hash && !hash.startsWith('#')) {
2919
+ warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
2920
+ }
2921
+ // decoding them) the matcher might have merged current location params so
2922
+ // we need to run the decoding again
2923
+ matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
2924
+ const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
2925
+ hash: encodeHash(hash),
2926
+ path: matchedRoute.path,
2927
+ }));
2928
+ const href = routerHistory.createHref(fullPath);
2929
+ if ((process.env.NODE_ENV !== 'production')) {
2930
+ if (href.startsWith('//')) {
2931
+ warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
2932
+ }
2933
+ else if (!matchedRoute.matched.length) {
2934
+ warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`);
2935
+ }
2936
+ }
2937
+ return assign({
2938
+ fullPath,
2939
+ // keep the hash encoded so fullPath is effectively path + encodedQuery +
2940
+ // hash
2941
+ hash,
2942
+ query:
2943
+ // if the user is using a custom query lib like qs, we might have
2944
+ // nested objects, so we keep the query as is, meaning it can contain
2945
+ // numbers at `$route.query`, but at the point, the user will have to
2946
+ // use their own type anyway.
2947
+ // https://github.com/vuejs/router/issues/328#issuecomment-649481567
2948
+ stringifyQuery$1 === stringifyQuery
2949
+ ? normalizeQuery(rawLocation.query)
2950
+ : (rawLocation.query || {}),
2951
+ }, matchedRoute, {
2952
+ redirectedFrom: undefined,
2953
+ href,
2954
+ });
2955
+ }
2956
+ function locationAsObject(to) {
2957
+ return typeof to === 'string'
2958
+ ? parseURL(parseQuery$1, to, currentRoute.value.path)
2959
+ : assign({}, to);
2960
+ }
2961
+ function checkCanceledNavigation(to, from) {
2962
+ if (pendingLocation !== to) {
2963
+ return createRouterError(8 /* NAVIGATION_CANCELLED */, {
2964
+ from,
2965
+ to,
2966
+ });
2967
+ }
2968
+ }
2969
+ function push(to) {
2970
+ return pushWithRedirect(to);
2971
+ }
2972
+ function replace(to) {
2973
+ return push(assign(locationAsObject(to), { replace: true }));
2974
+ }
2975
+ function handleRedirectRecord(to) {
2976
+ const lastMatched = to.matched[to.matched.length - 1];
2977
+ if (lastMatched && lastMatched.redirect) {
2978
+ const { redirect } = lastMatched;
2979
+ let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect;
2980
+ if (typeof newTargetLocation === 'string') {
2981
+ newTargetLocation =
2982
+ newTargetLocation.includes('?') || newTargetLocation.includes('#')
2983
+ ? (newTargetLocation = locationAsObject(newTargetLocation))
2984
+ : // force empty params
2985
+ { path: newTargetLocation };
2986
+ // @ts-expect-error: force empty params when a string is passed to let
2987
+ // the router parse them again
2988
+ newTargetLocation.params = {};
2989
+ }
2990
+ if ((process.env.NODE_ENV !== 'production') &&
2991
+ !('path' in newTargetLocation) &&
2992
+ !('name' in newTargetLocation)) {
2993
+ 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.`);
2994
+ throw new Error('Invalid redirect');
2995
+ }
2996
+ return assign({
2997
+ query: to.query,
2998
+ hash: to.hash,
2999
+ params: to.params,
3000
+ }, newTargetLocation);
3001
+ }
3002
+ }
3003
+ function pushWithRedirect(to, redirectedFrom) {
3004
+ const targetLocation = (pendingLocation = resolve(to));
3005
+ const from = currentRoute.value;
3006
+ const data = to.state;
3007
+ const force = to.force;
3008
+ // to could be a string where `replace` is a function
3009
+ const replace = to.replace === true;
3010
+ const shouldRedirect = handleRedirectRecord(targetLocation);
3011
+ if (shouldRedirect)
3012
+ return pushWithRedirect(assign(locationAsObject(shouldRedirect), {
3013
+ state: data,
3014
+ force,
3015
+ replace,
3016
+ }),
3017
+ // keep original redirectedFrom if it exists
3018
+ redirectedFrom || targetLocation);
3019
+ // if it was a redirect we already called `pushWithRedirect` above
3020
+ const toLocation = targetLocation;
3021
+ toLocation.redirectedFrom = redirectedFrom;
3022
+ let failure;
3023
+ if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
3024
+ failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from });
3025
+ // trigger scroll to allow scrolling to the same anchor
3026
+ handleScroll(from, from,
3027
+ // this is a push, the only way for it to be triggered from a
3028
+ // history.listen is with a redirect, which makes it become a push
3029
+ true,
3030
+ // This cannot be the first navigation because the initial location
3031
+ // cannot be manually navigated to
3032
+ false);
3033
+ }
3034
+ return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
3035
+ .catch((error) => isNavigationFailure(error)
3036
+ ? // navigation redirects still mark the router as ready
3037
+ isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)
3038
+ ? error
3039
+ : markAsReady(error) // also returns the error
3040
+ : // reject any unknown error
3041
+ triggerError(error, toLocation, from))
3042
+ .then((failure) => {
3043
+ if (failure) {
3044
+ if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
3045
+ if ((process.env.NODE_ENV !== 'production') &&
3046
+ // we are redirecting to the same location we were already at
3047
+ isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) &&
3048
+ // and we have done it a couple of times
3049
+ redirectedFrom &&
3050
+ // @ts-expect-error: added only in dev
3051
+ (redirectedFrom._count = redirectedFrom._count
3052
+ ? // @ts-expect-error
3053
+ redirectedFrom._count + 1
3054
+ : 1) > 10) {
3055
+ warn(`Detected an infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow. This will break in production if not fixed.`);
3056
+ return Promise.reject(new Error('Infinite redirect in navigation guard'));
3057
+ }
3058
+ return pushWithRedirect(
3059
+ // keep options
3060
+ assign(locationAsObject(failure.to), {
3061
+ state: data,
3062
+ force,
3063
+ replace,
3064
+ }),
3065
+ // preserve the original redirectedFrom if any
3066
+ redirectedFrom || toLocation);
3067
+ }
3068
+ }
3069
+ else {
3070
+ // if we fail we don't finalize the navigation
3071
+ failure = finalizeNavigation(toLocation, from, true, replace, data);
3072
+ }
3073
+ triggerAfterEach(toLocation, from, failure);
3074
+ return failure;
3075
+ });
3076
+ }
3077
+ /**
3078
+ * Helper to reject and skip all navigation guards if a new navigation happened
3079
+ * @param to
3080
+ * @param from
3081
+ */
3082
+ function checkCanceledNavigationAndReject(to, from) {
3083
+ const error = checkCanceledNavigation(to, from);
3084
+ return error ? Promise.reject(error) : Promise.resolve();
3085
+ }
3086
+ // TODO: refactor the whole before guards by internally using router.beforeEach
3087
+ function navigate(to, from) {
3088
+ let guards;
3089
+ const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from);
3090
+ // all components here have been resolved once because we are leaving
3091
+ guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from);
3092
+ // leavingRecords is already reversed
3093
+ for (const record of leavingRecords) {
3094
+ record.leaveGuards.forEach(guard => {
3095
+ guards.push(guardToPromiseFn(guard, to, from));
3096
+ });
3097
+ }
3098
+ const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
3099
+ guards.push(canceledNavigationCheck);
3100
+ // run the queue of per route beforeRouteLeave guards
3101
+ return (runGuardQueue(guards)
3102
+ .then(() => {
3103
+ // check global guards beforeEach
3104
+ guards = [];
3105
+ for (const guard of beforeGuards.list()) {
3106
+ guards.push(guardToPromiseFn(guard, to, from));
3107
+ }
3108
+ guards.push(canceledNavigationCheck);
3109
+ return runGuardQueue(guards);
3110
+ })
3111
+ .then(() => {
3112
+ // check in components beforeRouteUpdate
3113
+ guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from);
3114
+ for (const record of updatingRecords) {
3115
+ record.updateGuards.forEach(guard => {
3116
+ guards.push(guardToPromiseFn(guard, to, from));
3117
+ });
3118
+ }
3119
+ guards.push(canceledNavigationCheck);
3120
+ // run the queue of per route beforeEnter guards
3121
+ return runGuardQueue(guards);
3122
+ })
3123
+ .then(() => {
3124
+ // check the route beforeEnter
3125
+ guards = [];
3126
+ for (const record of to.matched) {
3127
+ // do not trigger beforeEnter on reused views
3128
+ if (record.beforeEnter && !from.matched.includes(record)) {
3129
+ if (Array.isArray(record.beforeEnter)) {
3130
+ for (const beforeEnter of record.beforeEnter)
3131
+ guards.push(guardToPromiseFn(beforeEnter, to, from));
3132
+ }
3133
+ else {
3134
+ guards.push(guardToPromiseFn(record.beforeEnter, to, from));
3135
+ }
3136
+ }
3137
+ }
3138
+ guards.push(canceledNavigationCheck);
3139
+ // run the queue of per route beforeEnter guards
3140
+ return runGuardQueue(guards);
3141
+ })
3142
+ .then(() => {
3143
+ // NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
3144
+ // clear existing enterCallbacks, these are added by extractComponentsGuards
3145
+ to.matched.forEach(record => (record.enterCallbacks = {}));
3146
+ // check in-component beforeRouteEnter
3147
+ guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from);
3148
+ guards.push(canceledNavigationCheck);
3149
+ // run the queue of per route beforeEnter guards
3150
+ return runGuardQueue(guards);
3151
+ })
3152
+ .then(() => {
3153
+ // check global guards beforeResolve
3154
+ guards = [];
3155
+ for (const guard of beforeResolveGuards.list()) {
3156
+ guards.push(guardToPromiseFn(guard, to, from));
3157
+ }
3158
+ guards.push(canceledNavigationCheck);
3159
+ return runGuardQueue(guards);
3160
+ })
3161
+ // catch any navigation canceled
3162
+ .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */)
3163
+ ? err
3164
+ : Promise.reject(err)));
3165
+ }
3166
+ function triggerAfterEach(to, from, failure) {
3167
+ // navigation is confirmed, call afterGuards
3168
+ // TODO: wrap with error handlers
3169
+ for (const guard of afterGuards.list())
3170
+ guard(to, from, failure);
3171
+ }
3172
+ /**
3173
+ * - Cleans up any navigation guards
3174
+ * - Changes the url if necessary
3175
+ * - Calls the scrollBehavior
3176
+ */
3177
+ function finalizeNavigation(toLocation, from, isPush, replace, data) {
3178
+ // a more recent navigation took place
3179
+ const error = checkCanceledNavigation(toLocation, from);
3180
+ if (error)
3181
+ return error;
3182
+ // only consider as push if it's not the first navigation
3183
+ const isFirstNavigation = from === START_LOCATION_NORMALIZED;
3184
+ const state = !isBrowser ? {} : history.state;
3185
+ // change URL only if the user did a push/replace and if it's not the initial navigation because
3186
+ // it's just reflecting the url
3187
+ if (isPush) {
3188
+ // on the initial navigation, we want to reuse the scroll position from
3189
+ // history state if it exists
3190
+ if (replace || isFirstNavigation)
3191
+ routerHistory.replace(toLocation.fullPath, assign({
3192
+ scroll: isFirstNavigation && state && state.scroll,
3193
+ }, data));
3194
+ else
3195
+ routerHistory.push(toLocation.fullPath, data);
3196
+ }
3197
+ // accept current navigation
3198
+ currentRoute.value = toLocation;
3199
+ handleScroll(toLocation, from, isPush, isFirstNavigation);
3200
+ markAsReady();
3201
+ }
3202
+ let removeHistoryListener;
3203
+ // attach listener to history to trigger navigations
3204
+ function setupListeners() {
3205
+ // avoid setting up listeners twice due to an invalid first navigation
3206
+ if (removeHistoryListener)
3207
+ return;
3208
+ removeHistoryListener = routerHistory.listen((to, _from, info) => {
3209
+ // cannot be a redirect route because it was in history
3210
+ const toLocation = resolve(to);
3211
+ // due to dynamic routing, and to hash history with manual navigation
3212
+ // (manually changing the url or calling history.hash = '#/somewhere'),
3213
+ // there could be a redirect record in history
3214
+ const shouldRedirect = handleRedirectRecord(toLocation);
3215
+ if (shouldRedirect) {
3216
+ pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop);
3217
+ return;
3218
+ }
3219
+ pendingLocation = toLocation;
3220
+ const from = currentRoute.value;
3221
+ // TODO: should be moved to web history?
3222
+ if (isBrowser) {
3223
+ saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
3224
+ }
3225
+ navigate(toLocation, from)
3226
+ .catch((error) => {
3227
+ if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) {
3228
+ return error;
3229
+ }
3230
+ if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
3231
+ // Here we could call if (info.delta) routerHistory.go(-info.delta,
3232
+ // false) but this is bug prone as we have no way to wait the
3233
+ // navigation to be finished before calling pushWithRedirect. Using
3234
+ // a setTimeout of 16ms seems to work but there is not guarantee for
3235
+ // it to work on every browser. So Instead we do not restore the
3236
+ // history entry and trigger a new navigation as requested by the
3237
+ // navigation guard.
3238
+ // the error is already handled by router.push we just want to avoid
3239
+ // logging the error
3240
+ pushWithRedirect(error.to, toLocation
3241
+ // avoid an uncaught rejection, let push call triggerError
3242
+ )
3243
+ .then(failure => {
3244
+ // manual change in hash history #916 ending up in the URL not
3245
+ // changing but it was changed by the manual url change, so we
3246
+ // need to manually change it ourselves
3247
+ if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ |
3248
+ 16 /* NAVIGATION_DUPLICATED */) &&
3249
+ !info.delta &&
3250
+ info.type === NavigationType.pop) {
3251
+ routerHistory.go(-1, false);
3252
+ }
3253
+ })
3254
+ .catch(noop);
3255
+ // avoid the then branch
3256
+ return Promise.reject();
3257
+ }
3258
+ // do not restore history on unknown direction
3259
+ if (info.delta)
3260
+ routerHistory.go(-info.delta, false);
3261
+ // unrecognized error, transfer to the global handler
3262
+ return triggerError(error, toLocation, from);
3263
+ })
3264
+ .then((failure) => {
3265
+ failure =
3266
+ failure ||
3267
+ finalizeNavigation(
3268
+ // after navigation, all matched components are resolved
3269
+ toLocation, from, false);
3270
+ // revert the navigation
3271
+ if (failure) {
3272
+ if (info.delta) {
3273
+ routerHistory.go(-info.delta, false);
3274
+ }
3275
+ else if (info.type === NavigationType.pop &&
3276
+ isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) {
3277
+ // manual change in hash history #916
3278
+ // it's like a push but lacks the information of the direction
3279
+ routerHistory.go(-1, false);
3280
+ }
3281
+ }
3282
+ triggerAfterEach(toLocation, from, failure);
3283
+ })
3284
+ .catch(noop);
3285
+ });
3286
+ }
3287
+ // Initialization and Errors
3288
+ let readyHandlers = useCallbacks();
3289
+ let errorHandlers = useCallbacks();
3290
+ let ready;
3291
+ /**
3292
+ * Trigger errorHandlers added via onError and throws the error as well
3293
+ *
3294
+ * @param error - error to throw
3295
+ * @param to - location we were navigating to when the error happened
3296
+ * @param from - location we were navigating from when the error happened
3297
+ * @returns the error as a rejected promise
3298
+ */
3299
+ function triggerError(error, to, from) {
3300
+ markAsReady(error);
3301
+ const list = errorHandlers.list();
3302
+ if (list.length) {
3303
+ list.forEach(handler => handler(error, to, from));
3304
+ }
3305
+ else {
3306
+ if ((process.env.NODE_ENV !== 'production')) {
3307
+ warn('uncaught error during route navigation:');
3308
+ }
3309
+ console.error(error);
3310
+ }
3311
+ return Promise.reject(error);
3312
+ }
3313
+ function isReady() {
3314
+ if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
3315
+ return Promise.resolve();
3316
+ return new Promise((resolve, reject) => {
3317
+ readyHandlers.add([resolve, reject]);
3318
+ });
3319
+ }
3320
+ function markAsReady(err) {
3321
+ if (!ready) {
3322
+ // still not ready if an error happened
3323
+ ready = !err;
3324
+ setupListeners();
3325
+ readyHandlers
3326
+ .list()
3327
+ .forEach(([resolve, reject]) => (err ? reject(err) : resolve()));
3328
+ readyHandlers.reset();
3329
+ }
3330
+ return err;
3331
+ }
3332
+ // Scroll behavior
3333
+ function handleScroll(to, from, isPush, isFirstNavigation) {
3334
+ const { scrollBehavior } = options;
3335
+ if (!isBrowser || !scrollBehavior)
3336
+ return Promise.resolve();
3337
+ const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) ||
3338
+ ((isFirstNavigation || !isPush) &&
3339
+ history.state &&
3340
+ history.state.scroll) ||
3341
+ null;
3342
+ return nextTick()
3343
+ .then(() => scrollBehavior(to, from, scrollPosition))
3344
+ .then(position => position && scrollToPosition(position))
3345
+ .catch(err => triggerError(err, to, from));
3346
+ }
3347
+ const go = (delta) => routerHistory.go(delta);
3348
+ let started;
3349
+ const installedApps = new Set();
3350
+ const router = {
3351
+ currentRoute,
3352
+ addRoute,
3353
+ removeRoute,
3354
+ hasRoute,
3355
+ getRoutes,
3356
+ resolve,
3357
+ options,
3358
+ push,
3359
+ replace,
3360
+ go,
3361
+ back: () => go(-1),
3362
+ forward: () => go(1),
3363
+ beforeEach: beforeGuards.add,
3364
+ beforeResolve: beforeResolveGuards.add,
3365
+ afterEach: afterGuards.add,
3366
+ onError: errorHandlers.add,
3367
+ isReady,
3368
+ install(app) {
3369
+ const router = this;
3370
+ app.component('RouterLink', RouterLink);
3371
+ app.component('RouterView', RouterView);
3372
+ app.config.globalProperties.$router = router;
3373
+ Object.defineProperty(app.config.globalProperties, '$route', {
3374
+ enumerable: true,
3375
+ get: () => unref(currentRoute),
3376
+ });
3377
+ // this initial navigation is only necessary on client, on server it doesn't
3378
+ // make sense because it will create an extra unnecessary navigation and could
3379
+ // lead to problems
3380
+ if (isBrowser &&
3381
+ // used for the initial navigation client side to avoid pushing
3382
+ // multiple times when the router is used in multiple apps
3383
+ !started &&
3384
+ currentRoute.value === START_LOCATION_NORMALIZED) {
3385
+ // see above
3386
+ started = true;
3387
+ push(routerHistory.location).catch(err => {
3388
+ if ((process.env.NODE_ENV !== 'production'))
3389
+ warn('Unexpected error when starting the router:', err);
3390
+ });
3391
+ }
3392
+ const reactiveRoute = {};
3393
+ for (const key in START_LOCATION_NORMALIZED) {
3394
+ // @ts-expect-error: the key matches
3395
+ reactiveRoute[key] = computed(() => currentRoute.value[key]);
3396
+ }
3397
+ app.provide(routerKey, router);
3398
+ app.provide(routeLocationKey, reactive(reactiveRoute));
3399
+ app.provide(routerViewLocationKey, currentRoute);
3400
+ const unmountApp = app.unmount;
3401
+ installedApps.add(app);
3402
+ app.unmount = function () {
3403
+ installedApps.delete(app);
3404
+ // the router is not attached to an app anymore
3405
+ if (installedApps.size < 1) {
3406
+ // invalidate the current navigation
3407
+ pendingLocation = START_LOCATION_NORMALIZED;
3408
+ removeHistoryListener && removeHistoryListener();
3409
+ removeHistoryListener = null;
3410
+ currentRoute.value = START_LOCATION_NORMALIZED;
3411
+ started = false;
3412
+ ready = false;
3413
+ }
3414
+ unmountApp();
3415
+ };
3416
+ if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && isBrowser) {
3417
+ addDevtools(app, router, matcher);
3418
+ }
3419
+ },
3420
+ };
3421
+ return router;
3422
+ }
3423
+ function runGuardQueue(guards) {
3424
+ return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve());
3425
+ }
3426
+ function extractChangingRecords(to, from) {
3427
+ const leavingRecords = [];
3428
+ const updatingRecords = [];
3429
+ const enteringRecords = [];
3430
+ const len = Math.max(from.matched.length, to.matched.length);
3431
+ for (let i = 0; i < len; i++) {
3432
+ const recordFrom = from.matched[i];
3433
+ if (recordFrom) {
3434
+ if (to.matched.find(record => isSameRouteRecord(record, recordFrom)))
3435
+ updatingRecords.push(recordFrom);
3436
+ else
3437
+ leavingRecords.push(recordFrom);
3438
+ }
3439
+ const recordTo = to.matched[i];
3440
+ if (recordTo) {
3441
+ // the type doesn't matter because we are comparing per reference
3442
+ if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) {
3443
+ enteringRecords.push(recordTo);
3444
+ }
3445
+ }
3446
+ }
3447
+ return [leavingRecords, updatingRecords, enteringRecords];
3448
+ }
3449
+
3450
+ /**
3451
+ * Returns the router instance. Equivalent to using `$router` inside
3452
+ * templates.
3453
+ */
3454
+ function useRouter() {
3455
+ return inject(routerKey);
3456
+ }
3457
+ /**
3458
+ * Returns the current route location. Equivalent to using `$route` inside
3459
+ * templates.
3460
+ */
3461
+ function useRoute() {
3462
+ return inject(routeLocationKey);
3463
+ }
3464
+
3465
+ export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey };