kdu-router 2.7.0 → 4.0.16-rc.0

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