kdu-router 4.0.16-rc.0 → 4.1.6

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