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