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