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