kdu-router 3.6.0 → 3.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3151 @@
1
+ /*!
2
+ * kdu-router v3.6.2
3
+ * (c) 2026 NKDuy
4
+ * @license MIT
5
+ */
6
+ /* */
7
+
8
+ function assert (condition, message) {
9
+ if (!condition) {
10
+ throw new Error(("[kdu-router] " + message))
11
+ }
12
+ }
13
+
14
+ function warn (condition, message) {
15
+ if (!condition) {
16
+ typeof console !== 'undefined' && console.warn(("[kdu-router] " + message));
17
+ }
18
+ }
19
+
20
+ function extend (a, b) {
21
+ for (var key in b) {
22
+ a[key] = b[key];
23
+ }
24
+ return a
25
+ }
26
+
27
+ /* */
28
+
29
+ var encodeReserveRE = /[!'()*]/g;
30
+ var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
31
+ var commaRE = /%2C/g;
32
+
33
+ // fixed encodeURIComponent which is more conformant to RFC3986:
34
+ // - escapes [!'()*]
35
+ // - preserve commas
36
+ var encode = function (str) { return encodeURIComponent(str)
37
+ .replace(encodeReserveRE, encodeReserveReplacer)
38
+ .replace(commaRE, ','); };
39
+
40
+ function decode (str) {
41
+ try {
42
+ return decodeURIComponent(str)
43
+ } catch (err) {
44
+ if (process.env.NODE_ENV !== 'production') {
45
+ warn(false, ("Error decoding \"" + str + "\". Leaving it intact."));
46
+ }
47
+ }
48
+ return str
49
+ }
50
+
51
+ function resolveQuery (
52
+ query,
53
+ extraQuery,
54
+ _parseQuery
55
+ ) {
56
+ if ( extraQuery === void 0 ) extraQuery = {};
57
+
58
+ var parse = _parseQuery || parseQuery;
59
+ var parsedQuery;
60
+ try {
61
+ parsedQuery = parse(query || '');
62
+ } catch (e) {
63
+ process.env.NODE_ENV !== 'production' && warn(false, e.message);
64
+ parsedQuery = {};
65
+ }
66
+ for (var key in extraQuery) {
67
+ var value = extraQuery[key];
68
+ parsedQuery[key] = Array.isArray(value)
69
+ ? value.map(castQueryParamValue)
70
+ : castQueryParamValue(value);
71
+ }
72
+ return parsedQuery
73
+ }
74
+
75
+ var castQueryParamValue = function (value) { return (value == null || typeof value === 'object' ? value : String(value)); };
76
+
77
+ function parseQuery (query) {
78
+ var res = {};
79
+
80
+ query = query.trim().replace(/^(\?|#|&)/, '');
81
+
82
+ if (!query) {
83
+ return res
84
+ }
85
+
86
+ query.split('&').forEach(function (param) {
87
+ var parts = param.replace(/\+/g, ' ').split('=');
88
+ var key = decode(parts.shift());
89
+ var val = parts.length > 0 ? decode(parts.join('=')) : null;
90
+
91
+ if (res[key] === undefined) {
92
+ res[key] = val;
93
+ } else if (Array.isArray(res[key])) {
94
+ res[key].push(val);
95
+ } else {
96
+ res[key] = [res[key], val];
97
+ }
98
+ });
99
+
100
+ return res
101
+ }
102
+
103
+ function stringifyQuery (obj) {
104
+ var res = obj
105
+ ? Object.keys(obj)
106
+ .map(function (key) {
107
+ var val = obj[key];
108
+
109
+ if (val === undefined) {
110
+ return ''
111
+ }
112
+
113
+ if (val === null) {
114
+ return encode(key)
115
+ }
116
+
117
+ if (Array.isArray(val)) {
118
+ var result = [];
119
+ val.forEach(function (val2) {
120
+ if (val2 === undefined) {
121
+ return
122
+ }
123
+ if (val2 === null) {
124
+ result.push(encode(key));
125
+ } else {
126
+ result.push(encode(key) + '=' + encode(val2));
127
+ }
128
+ });
129
+ return result.join('&')
130
+ }
131
+
132
+ return encode(key) + '=' + encode(val)
133
+ })
134
+ .filter(function (x) { return x.length > 0; })
135
+ .join('&')
136
+ : null;
137
+ return res ? ("?" + res) : ''
138
+ }
139
+
140
+ /* */
141
+
142
+ var trailingSlashRE = /\/?$/;
143
+
144
+ function createRoute (
145
+ record,
146
+ location,
147
+ redirectedFrom,
148
+ router
149
+ ) {
150
+ var stringifyQuery = router && router.options.stringifyQuery;
151
+
152
+ var query = location.query || {};
153
+ try {
154
+ query = clone(query);
155
+ } catch (e) {}
156
+
157
+ var route = {
158
+ name: location.name || (record && record.name),
159
+ meta: (record && record.meta) || {},
160
+ path: location.path || '/',
161
+ hash: location.hash || '',
162
+ query: query,
163
+ params: location.params || {},
164
+ fullPath: getFullPath(location, stringifyQuery),
165
+ matched: record ? formatMatch(record) : []
166
+ };
167
+ if (redirectedFrom) {
168
+ route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
169
+ }
170
+ return Object.freeze(route)
171
+ }
172
+
173
+ function clone (value) {
174
+ if (Array.isArray(value)) {
175
+ return value.map(clone)
176
+ } else if (value && typeof value === 'object') {
177
+ var res = {};
178
+ for (var key in value) {
179
+ res[key] = clone(value[key]);
180
+ }
181
+ return res
182
+ } else {
183
+ return value
184
+ }
185
+ }
186
+
187
+ // the starting route that represents the initial state
188
+ var START = createRoute(null, {
189
+ path: '/'
190
+ });
191
+
192
+ function formatMatch (record) {
193
+ var res = [];
194
+ while (record) {
195
+ res.unshift(record);
196
+ record = record.parent;
197
+ }
198
+ return res
199
+ }
200
+
201
+ function getFullPath (
202
+ ref,
203
+ _stringifyQuery
204
+ ) {
205
+ var path = ref.path;
206
+ var query = ref.query; if ( query === void 0 ) query = {};
207
+ var hash = ref.hash; if ( hash === void 0 ) hash = '';
208
+
209
+ var stringify = _stringifyQuery || stringifyQuery;
210
+ return (path || '/') + stringify(query) + hash
211
+ }
212
+
213
+ function isSameRoute (a, b, onlyPath) {
214
+ if (b === START) {
215
+ return a === b
216
+ } else if (!b) {
217
+ return false
218
+ } else if (a.path && b.path) {
219
+ return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
220
+ a.hash === b.hash &&
221
+ isObjectEqual(a.query, b.query))
222
+ } else if (a.name && b.name) {
223
+ return (
224
+ a.name === b.name &&
225
+ (onlyPath || (
226
+ a.hash === b.hash &&
227
+ isObjectEqual(a.query, b.query) &&
228
+ isObjectEqual(a.params, b.params))
229
+ )
230
+ )
231
+ } else {
232
+ return false
233
+ }
234
+ }
235
+
236
+ function isObjectEqual (a, b) {
237
+ if ( a === void 0 ) a = {};
238
+ if ( b === void 0 ) b = {};
239
+
240
+ // handle null value #1566
241
+ if (!a || !b) { return a === b }
242
+ var aKeys = Object.keys(a).sort();
243
+ var bKeys = Object.keys(b).sort();
244
+ if (aKeys.length !== bKeys.length) {
245
+ return false
246
+ }
247
+ return aKeys.every(function (key, i) {
248
+ var aVal = a[key];
249
+ var bKey = bKeys[i];
250
+ if (bKey !== key) { return false }
251
+ var bVal = b[key];
252
+ // query values can be null and undefined
253
+ if (aVal == null || bVal == null) { return aVal === bVal }
254
+ // check nested equality
255
+ if (typeof aVal === 'object' && typeof bVal === 'object') {
256
+ return isObjectEqual(aVal, bVal)
257
+ }
258
+ return String(aVal) === String(bVal)
259
+ })
260
+ }
261
+
262
+ function isIncludedRoute (current, target) {
263
+ return (
264
+ current.path.replace(trailingSlashRE, '/').indexOf(
265
+ target.path.replace(trailingSlashRE, '/')
266
+ ) === 0 &&
267
+ (!target.hash || current.hash === target.hash) &&
268
+ queryIncludes(current.query, target.query)
269
+ )
270
+ }
271
+
272
+ function queryIncludes (current, target) {
273
+ for (var key in target) {
274
+ if (!(key in current)) {
275
+ return false
276
+ }
277
+ }
278
+ return true
279
+ }
280
+
281
+ function handleRouteEntered (route) {
282
+ for (var i = 0; i < route.matched.length; i++) {
283
+ var record = route.matched[i];
284
+ for (var name in record.instances) {
285
+ var instance = record.instances[name];
286
+ var cbs = record.enteredCbs[name];
287
+ if (!instance || !cbs) { continue }
288
+ delete record.enteredCbs[name];
289
+ for (var i$1 = 0; i$1 < cbs.length; i$1++) {
290
+ if (!instance._isBeingDestroyed) { cbs[i$1](instance); }
291
+ }
292
+ }
293
+ }
294
+ }
295
+
296
+ var View = {
297
+ name: 'RouterView',
298
+ functional: true,
299
+ props: {
300
+ name: {
301
+ type: String,
302
+ default: 'default'
303
+ }
304
+ },
305
+ render: function render (_, ref) {
306
+ var props = ref.props;
307
+ var children = ref.children;
308
+ var parent = ref.parent;
309
+ var data = ref.data;
310
+
311
+ // used by devtools to display a router-view badge
312
+ data.routerView = true;
313
+
314
+ // directly use parent context's createElement() function
315
+ // so that components rendered by router-view can resolve named slots
316
+ var h = parent.$createElement;
317
+ var name = props.name;
318
+ var route = parent.$route;
319
+ var cache = parent._routerViewCache || (parent._routerViewCache = {});
320
+
321
+ // determine current view depth, also check to see if the tree
322
+ // has been toggled inactive but kept-alive.
323
+ var depth = 0;
324
+ var inactive = false;
325
+ while (parent && parent._routerRoot !== parent) {
326
+ var knodeData = parent.$knode ? parent.$knode.data : {};
327
+ if (knodeData.routerView) {
328
+ depth++;
329
+ }
330
+ if (knodeData.keepAlive && parent._directInactive && parent._inactive) {
331
+ inactive = true;
332
+ }
333
+ parent = parent.$parent;
334
+ }
335
+ data.routerViewDepth = depth;
336
+
337
+ // render previous view if the tree is inactive and kept-alive
338
+ if (inactive) {
339
+ var cachedData = cache[name];
340
+ var cachedComponent = cachedData && cachedData.component;
341
+ if (cachedComponent) {
342
+ // #2301
343
+ // pass props
344
+ if (cachedData.configProps) {
345
+ fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
346
+ }
347
+ return h(cachedComponent, data, children)
348
+ } else {
349
+ // render previous empty view
350
+ return h()
351
+ }
352
+ }
353
+
354
+ var matched = route.matched[depth];
355
+ var component = matched && matched.components[name];
356
+
357
+ // render empty node if no matched route or no config component
358
+ if (!matched || !component) {
359
+ cache[name] = null;
360
+ return h()
361
+ }
362
+
363
+ // cache component
364
+ cache[name] = { component: component };
365
+
366
+ // attach instance registration hook
367
+ // this will be called in the instance's injected lifecycle hooks
368
+ data.registerRouteInstance = function (vm, val) {
369
+ // val could be undefined for unregistration
370
+ var current = matched.instances[name];
371
+ if (
372
+ (val && current !== vm) ||
373
+ (!val && current === vm)
374
+ ) {
375
+ matched.instances[name] = val;
376
+ }
377
+ }
378
+
379
+ // also register instance in prepatch hook
380
+ // in case the same component instance is reused across different routes
381
+ ;(data.hook || (data.hook = {})).prepatch = function (_, knode) {
382
+ matched.instances[name] = knode.componentInstance;
383
+ };
384
+
385
+ // register instance in init hook
386
+ // in case kept-alive component be actived when routes changed
387
+ data.hook.init = function (knode) {
388
+ if (knode.data.keepAlive &&
389
+ knode.componentInstance &&
390
+ knode.componentInstance !== matched.instances[name]
391
+ ) {
392
+ matched.instances[name] = knode.componentInstance;
393
+ }
394
+
395
+ // if the route transition has already been confirmed then we weren't
396
+ // able to call the cbs during confirmation as the component was not
397
+ // registered yet, so we call it here.
398
+ handleRouteEntered(route);
399
+ };
400
+
401
+ var configProps = matched.props && matched.props[name];
402
+ // save route and configProps in cache
403
+ if (configProps) {
404
+ extend(cache[name], {
405
+ route: route,
406
+ configProps: configProps
407
+ });
408
+ fillPropsinData(component, data, route, configProps);
409
+ }
410
+
411
+ return h(component, data, children)
412
+ }
413
+ };
414
+
415
+ function fillPropsinData (component, data, route, configProps) {
416
+ // resolve props
417
+ var propsToPass = data.props = resolveProps(route, configProps);
418
+ if (propsToPass) {
419
+ // clone to prevent mutation
420
+ propsToPass = data.props = extend({}, propsToPass);
421
+ // pass non-declared props as attrs
422
+ var attrs = data.attrs = data.attrs || {};
423
+ for (var key in propsToPass) {
424
+ if (!component.props || !(key in component.props)) {
425
+ attrs[key] = propsToPass[key];
426
+ delete propsToPass[key];
427
+ }
428
+ }
429
+ }
430
+ }
431
+
432
+ function resolveProps (route, config) {
433
+ switch (typeof config) {
434
+ case 'undefined':
435
+ return
436
+ case 'object':
437
+ return config
438
+ case 'function':
439
+ return config(route)
440
+ case 'boolean':
441
+ return config ? route.params : undefined
442
+ default:
443
+ if (process.env.NODE_ENV !== 'production') {
444
+ warn(
445
+ false,
446
+ "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
447
+ "expecting an object, function or boolean."
448
+ );
449
+ }
450
+ }
451
+ }
452
+
453
+ /* */
454
+
455
+ function resolvePath (
456
+ relative,
457
+ base,
458
+ append
459
+ ) {
460
+ var firstChar = relative.charAt(0);
461
+ if (firstChar === '/') {
462
+ return relative
463
+ }
464
+
465
+ if (firstChar === '?' || firstChar === '#') {
466
+ return base + relative
467
+ }
468
+
469
+ var stack = base.split('/');
470
+
471
+ // remove trailing segment if:
472
+ // - not appending
473
+ // - appending to trailing slash (last segment is empty)
474
+ if (!append || !stack[stack.length - 1]) {
475
+ stack.pop();
476
+ }
477
+
478
+ // resolve relative path
479
+ var segments = relative.replace(/^\//, '').split('/');
480
+ for (var i = 0; i < segments.length; i++) {
481
+ var segment = segments[i];
482
+ if (segment === '..') {
483
+ stack.pop();
484
+ } else if (segment !== '.') {
485
+ stack.push(segment);
486
+ }
487
+ }
488
+
489
+ // ensure leading slash
490
+ if (stack[0] !== '') {
491
+ stack.unshift('');
492
+ }
493
+
494
+ return stack.join('/')
495
+ }
496
+
497
+ function parsePath (path) {
498
+ var hash = '';
499
+ var query = '';
500
+
501
+ var hashIndex = path.indexOf('#');
502
+ if (hashIndex >= 0) {
503
+ hash = path.slice(hashIndex);
504
+ path = path.slice(0, hashIndex);
505
+ }
506
+
507
+ var queryIndex = path.indexOf('?');
508
+ if (queryIndex >= 0) {
509
+ query = path.slice(queryIndex + 1);
510
+ path = path.slice(0, queryIndex);
511
+ }
512
+
513
+ return {
514
+ path: path,
515
+ query: query,
516
+ hash: hash
517
+ }
518
+ }
519
+
520
+ function cleanPath (path) {
521
+ return path.replace(/\/(?:\s*\/)+/g, '/')
522
+ }
523
+
524
+ var isarray = Array.isArray || function (arr) {
525
+ return Object.prototype.toString.call(arr) == '[object Array]';
526
+ };
527
+
528
+ /**
529
+ * Expose `pathToRegexp`.
530
+ */
531
+ var pathToRegexp_1 = pathToRegexp;
532
+ var parse_1 = parse;
533
+ var compile_1 = compile;
534
+ var tokensToFunction_1 = tokensToFunction;
535
+ var tokensToRegExp_1 = tokensToRegExp;
536
+
537
+ /**
538
+ * The main path matching regexp utility.
539
+ *
540
+ * @type {RegExp}
541
+ */
542
+ var PATH_REGEXP = new RegExp([
543
+ // Match escaped characters that would otherwise appear in future matches.
544
+ // This allows the user to escape special characters that won't transform.
545
+ '(\\\\.)',
546
+ // Match Express-style parameters and un-named parameters with a prefix
547
+ // and optional suffixes. Matches appear as:
548
+ //
549
+ // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
550
+ // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
551
+ // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
552
+ '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
553
+ ].join('|'), 'g');
554
+
555
+ /**
556
+ * Parse a string for the raw tokens.
557
+ *
558
+ * @param {string} str
559
+ * @param {Object=} options
560
+ * @return {!Array}
561
+ */
562
+ function parse (str, options) {
563
+ var tokens = [];
564
+ var key = 0;
565
+ var index = 0;
566
+ var path = '';
567
+ var defaultDelimiter = options && options.delimiter || '/';
568
+ var res;
569
+
570
+ while ((res = PATH_REGEXP.exec(str)) != null) {
571
+ var m = res[0];
572
+ var escaped = res[1];
573
+ var offset = res.index;
574
+ path += str.slice(index, offset);
575
+ index = offset + m.length;
576
+
577
+ // Ignore already escaped sequences.
578
+ if (escaped) {
579
+ path += escaped[1];
580
+ continue
581
+ }
582
+
583
+ var next = str[index];
584
+ var prefix = res[2];
585
+ var name = res[3];
586
+ var capture = res[4];
587
+ var group = res[5];
588
+ var modifier = res[6];
589
+ var asterisk = res[7];
590
+
591
+ // Push the current path onto the tokens.
592
+ if (path) {
593
+ tokens.push(path);
594
+ path = '';
595
+ }
596
+
597
+ var partial = prefix != null && next != null && next !== prefix;
598
+ var repeat = modifier === '+' || modifier === '*';
599
+ var optional = modifier === '?' || modifier === '*';
600
+ var delimiter = res[2] || defaultDelimiter;
601
+ var pattern = capture || group;
602
+
603
+ tokens.push({
604
+ name: name || key++,
605
+ prefix: prefix || '',
606
+ delimiter: delimiter,
607
+ optional: optional,
608
+ repeat: repeat,
609
+ partial: partial,
610
+ asterisk: !!asterisk,
611
+ pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
612
+ });
613
+ }
614
+
615
+ // Match any characters still remaining.
616
+ if (index < str.length) {
617
+ path += str.substr(index);
618
+ }
619
+
620
+ // If the path exists, push it onto the end.
621
+ if (path) {
622
+ tokens.push(path);
623
+ }
624
+
625
+ return tokens
626
+ }
627
+
628
+ /**
629
+ * Compile a string to a template function for the path.
630
+ *
631
+ * @param {string} str
632
+ * @param {Object=} options
633
+ * @return {!function(Object=, Object=)}
634
+ */
635
+ function compile (str, options) {
636
+ return tokensToFunction(parse(str, options), options)
637
+ }
638
+
639
+ /**
640
+ * Prettier encoding of URI path segments.
641
+ *
642
+ * @param {string}
643
+ * @return {string}
644
+ */
645
+ function encodeURIComponentPretty (str) {
646
+ return encodeURI(str).replace(/[\/?#]/g, function (c) {
647
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
648
+ })
649
+ }
650
+
651
+ /**
652
+ * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
653
+ *
654
+ * @param {string}
655
+ * @return {string}
656
+ */
657
+ function encodeAsterisk (str) {
658
+ return encodeURI(str).replace(/[?#]/g, function (c) {
659
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
660
+ })
661
+ }
662
+
663
+ /**
664
+ * Expose a method for transforming tokens into the path function.
665
+ */
666
+ function tokensToFunction (tokens, options) {
667
+ // Compile all the tokens into regexps.
668
+ var matches = new Array(tokens.length);
669
+
670
+ // Compile all the patterns before compilation.
671
+ for (var i = 0; i < tokens.length; i++) {
672
+ if (typeof tokens[i] === 'object') {
673
+ matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
674
+ }
675
+ }
676
+
677
+ return function (obj, opts) {
678
+ var path = '';
679
+ var data = obj || {};
680
+ var options = opts || {};
681
+ var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
682
+
683
+ for (var i = 0; i < tokens.length; i++) {
684
+ var token = tokens[i];
685
+
686
+ if (typeof token === 'string') {
687
+ path += token;
688
+
689
+ continue
690
+ }
691
+
692
+ var value = data[token.name];
693
+ var segment;
694
+
695
+ if (value == null) {
696
+ if (token.optional) {
697
+ // Prepend partial segment prefixes.
698
+ if (token.partial) {
699
+ path += token.prefix;
700
+ }
701
+
702
+ continue
703
+ } else {
704
+ throw new TypeError('Expected "' + token.name + '" to be defined')
705
+ }
706
+ }
707
+
708
+ if (isarray(value)) {
709
+ if (!token.repeat) {
710
+ throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
711
+ }
712
+
713
+ if (value.length === 0) {
714
+ if (token.optional) {
715
+ continue
716
+ } else {
717
+ throw new TypeError('Expected "' + token.name + '" to not be empty')
718
+ }
719
+ }
720
+
721
+ for (var j = 0; j < value.length; j++) {
722
+ segment = encode(value[j]);
723
+
724
+ if (!matches[i].test(segment)) {
725
+ throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
726
+ }
727
+
728
+ path += (j === 0 ? token.prefix : token.delimiter) + segment;
729
+ }
730
+
731
+ continue
732
+ }
733
+
734
+ segment = token.asterisk ? encodeAsterisk(value) : encode(value);
735
+
736
+ if (!matches[i].test(segment)) {
737
+ throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
738
+ }
739
+
740
+ path += token.prefix + segment;
741
+ }
742
+
743
+ return path
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Escape a regular expression string.
749
+ *
750
+ * @param {string} str
751
+ * @return {string}
752
+ */
753
+ function escapeString (str) {
754
+ return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
755
+ }
756
+
757
+ /**
758
+ * Escape the capturing group by escaping special characters and meaning.
759
+ *
760
+ * @param {string} group
761
+ * @return {string}
762
+ */
763
+ function escapeGroup (group) {
764
+ return group.replace(/([=!:$\/()])/g, '\\$1')
765
+ }
766
+
767
+ /**
768
+ * Attach the keys as a property of the regexp.
769
+ *
770
+ * @param {!RegExp} re
771
+ * @param {Array} keys
772
+ * @return {!RegExp}
773
+ */
774
+ function attachKeys (re, keys) {
775
+ re.keys = keys;
776
+ return re
777
+ }
778
+
779
+ /**
780
+ * Get the flags for a regexp from the options.
781
+ *
782
+ * @param {Object} options
783
+ * @return {string}
784
+ */
785
+ function flags (options) {
786
+ return options && options.sensitive ? '' : 'i'
787
+ }
788
+
789
+ /**
790
+ * Pull out keys from a regexp.
791
+ *
792
+ * @param {!RegExp} path
793
+ * @param {!Array} keys
794
+ * @return {!RegExp}
795
+ */
796
+ function regexpToRegexp (path, keys) {
797
+ // Use a negative lookahead to match only capturing groups.
798
+ var groups = path.source.match(/\((?!\?)/g);
799
+
800
+ if (groups) {
801
+ for (var i = 0; i < groups.length; i++) {
802
+ keys.push({
803
+ name: i,
804
+ prefix: null,
805
+ delimiter: null,
806
+ optional: false,
807
+ repeat: false,
808
+ partial: false,
809
+ asterisk: false,
810
+ pattern: null
811
+ });
812
+ }
813
+ }
814
+
815
+ return attachKeys(path, keys)
816
+ }
817
+
818
+ /**
819
+ * Transform an array into a regexp.
820
+ *
821
+ * @param {!Array} path
822
+ * @param {Array} keys
823
+ * @param {!Object} options
824
+ * @return {!RegExp}
825
+ */
826
+ function arrayToRegexp (path, keys, options) {
827
+ var parts = [];
828
+
829
+ for (var i = 0; i < path.length; i++) {
830
+ parts.push(pathToRegexp(path[i], keys, options).source);
831
+ }
832
+
833
+ var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
834
+
835
+ return attachKeys(regexp, keys)
836
+ }
837
+
838
+ /**
839
+ * Create a path regexp from string input.
840
+ *
841
+ * @param {string} path
842
+ * @param {!Array} keys
843
+ * @param {!Object} options
844
+ * @return {!RegExp}
845
+ */
846
+ function stringToRegexp (path, keys, options) {
847
+ return tokensToRegExp(parse(path, options), keys, options)
848
+ }
849
+
850
+ /**
851
+ * Expose a function for taking tokens and returning a RegExp.
852
+ *
853
+ * @param {!Array} tokens
854
+ * @param {(Array|Object)=} keys
855
+ * @param {Object=} options
856
+ * @return {!RegExp}
857
+ */
858
+ function tokensToRegExp (tokens, keys, options) {
859
+ if (!isarray(keys)) {
860
+ options = /** @type {!Object} */ (keys || options);
861
+ keys = [];
862
+ }
863
+
864
+ options = options || {};
865
+
866
+ var strict = options.strict;
867
+ var end = options.end !== false;
868
+ var route = '';
869
+
870
+ // Iterate over the tokens and create our regexp string.
871
+ for (var i = 0; i < tokens.length; i++) {
872
+ var token = tokens[i];
873
+
874
+ if (typeof token === 'string') {
875
+ route += escapeString(token);
876
+ } else {
877
+ var prefix = escapeString(token.prefix);
878
+ var capture = '(?:' + token.pattern + ')';
879
+
880
+ keys.push(token);
881
+
882
+ if (token.repeat) {
883
+ capture += '(?:' + prefix + capture + ')*';
884
+ }
885
+
886
+ if (token.optional) {
887
+ if (!token.partial) {
888
+ capture = '(?:' + prefix + '(' + capture + '))?';
889
+ } else {
890
+ capture = prefix + '(' + capture + ')?';
891
+ }
892
+ } else {
893
+ capture = prefix + '(' + capture + ')';
894
+ }
895
+
896
+ route += capture;
897
+ }
898
+ }
899
+
900
+ var delimiter = escapeString(options.delimiter || '/');
901
+ var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
902
+
903
+ // In non-strict mode we allow a slash at the end of match. If the path to
904
+ // match already ends with a slash, we remove it for consistency. The slash
905
+ // is valid at the end of a path match, not in the middle. This is important
906
+ // in non-ending mode, where "/test/" shouldn't match "/test//route".
907
+ if (!strict) {
908
+ route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
909
+ }
910
+
911
+ if (end) {
912
+ route += '$';
913
+ } else {
914
+ // In non-ending mode, we need the capturing groups to match as much as
915
+ // possible by using a positive lookahead to the end or next path segment.
916
+ route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
917
+ }
918
+
919
+ return attachKeys(new RegExp('^' + route, flags(options)), keys)
920
+ }
921
+
922
+ /**
923
+ * Normalize the given path string, returning a regular expression.
924
+ *
925
+ * An empty array can be passed in for the keys, which will hold the
926
+ * placeholder key descriptions. For example, using `/user/:id`, `keys` will
927
+ * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
928
+ *
929
+ * @param {(string|RegExp|Array)} path
930
+ * @param {(Array|Object)=} keys
931
+ * @param {Object=} options
932
+ * @return {!RegExp}
933
+ */
934
+ function pathToRegexp (path, keys, options) {
935
+ if (!isarray(keys)) {
936
+ options = /** @type {!Object} */ (keys || options);
937
+ keys = [];
938
+ }
939
+
940
+ options = options || {};
941
+
942
+ if (path instanceof RegExp) {
943
+ return regexpToRegexp(path, /** @type {!Array} */ (keys))
944
+ }
945
+
946
+ if (isarray(path)) {
947
+ return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
948
+ }
949
+
950
+ return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
951
+ }
952
+ pathToRegexp_1.parse = parse_1;
953
+ pathToRegexp_1.compile = compile_1;
954
+ pathToRegexp_1.tokensToFunction = tokensToFunction_1;
955
+ pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
956
+
957
+ /* */
958
+
959
+ // $flow-disable-line
960
+ var regexpCompileCache = Object.create(null);
961
+
962
+ function fillParams (
963
+ path,
964
+ params,
965
+ routeMsg
966
+ ) {
967
+ params = params || {};
968
+ try {
969
+ var filler =
970
+ regexpCompileCache[path] ||
971
+ (regexpCompileCache[path] = pathToRegexp_1.compile(path));
972
+
973
+ // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
974
+ // and fix #3106 so that you can work with location descriptor object having params.pathMatch equal to empty string
975
+ if (typeof params.pathMatch === 'string') { params[0] = params.pathMatch; }
976
+
977
+ return filler(params, { pretty: true })
978
+ } catch (e) {
979
+ if (process.env.NODE_ENV !== 'production') {
980
+ // Fix #3072 no warn if `pathMatch` is string
981
+ warn(typeof params.pathMatch === 'string', ("missing param for " + routeMsg + ": " + (e.message)));
982
+ }
983
+ return ''
984
+ } finally {
985
+ // delete the 0 if it was added
986
+ delete params[0];
987
+ }
988
+ }
989
+
990
+ /* */
991
+
992
+ function normalizeLocation (
993
+ raw,
994
+ current,
995
+ append,
996
+ router
997
+ ) {
998
+ var next = typeof raw === 'string' ? { path: raw } : raw;
999
+ // named target
1000
+ if (next._normalized) {
1001
+ return next
1002
+ } else if (next.name) {
1003
+ next = extend({}, raw);
1004
+ var params = next.params;
1005
+ if (params && typeof params === 'object') {
1006
+ next.params = extend({}, params);
1007
+ }
1008
+ return next
1009
+ }
1010
+
1011
+ // relative params
1012
+ if (!next.path && next.params && current) {
1013
+ next = extend({}, next);
1014
+ next._normalized = true;
1015
+ var params$1 = extend(extend({}, current.params), next.params);
1016
+ if (current.name) {
1017
+ next.name = current.name;
1018
+ next.params = params$1;
1019
+ } else if (current.matched.length) {
1020
+ var rawPath = current.matched[current.matched.length - 1].path;
1021
+ next.path = fillParams(rawPath, params$1, ("path " + (current.path)));
1022
+ } else if (process.env.NODE_ENV !== 'production') {
1023
+ warn(false, "relative params navigation requires a current route.");
1024
+ }
1025
+ return next
1026
+ }
1027
+
1028
+ var parsedPath = parsePath(next.path || '');
1029
+ var basePath = (current && current.path) || '/';
1030
+ var path = parsedPath.path
1031
+ ? resolvePath(parsedPath.path, basePath, append || next.append)
1032
+ : basePath;
1033
+
1034
+ var query = resolveQuery(
1035
+ parsedPath.query,
1036
+ next.query,
1037
+ router && router.options.parseQuery
1038
+ );
1039
+
1040
+ var hash = next.hash || parsedPath.hash;
1041
+ if (hash && hash.charAt(0) !== '#') {
1042
+ hash = "#" + hash;
1043
+ }
1044
+
1045
+ return {
1046
+ _normalized: true,
1047
+ path: path,
1048
+ query: query,
1049
+ hash: hash
1050
+ }
1051
+ }
1052
+
1053
+ /* */
1054
+
1055
+ // work around weird flow bug
1056
+ var toTypes = [String, Object];
1057
+ var eventTypes = [String, Array];
1058
+
1059
+ var noop = function () {};
1060
+
1061
+ var warnedCustomSlot;
1062
+ var warnedTagProp;
1063
+ var warnedEventProp;
1064
+
1065
+ var Link = {
1066
+ name: 'RouterLink',
1067
+ props: {
1068
+ to: {
1069
+ type: toTypes,
1070
+ required: true
1071
+ },
1072
+ tag: {
1073
+ type: String,
1074
+ default: 'a'
1075
+ },
1076
+ custom: Boolean,
1077
+ exact: Boolean,
1078
+ exactPath: Boolean,
1079
+ append: Boolean,
1080
+ replace: Boolean,
1081
+ activeClass: String,
1082
+ exactActiveClass: String,
1083
+ ariaCurrentValue: {
1084
+ type: String,
1085
+ default: 'page'
1086
+ },
1087
+ event: {
1088
+ type: eventTypes,
1089
+ default: 'click'
1090
+ }
1091
+ },
1092
+ render: function render (h) {
1093
+ var this$1 = this;
1094
+
1095
+ var router = this.$router;
1096
+ var current = this.$route;
1097
+ var ref = router.resolve(
1098
+ this.to,
1099
+ current,
1100
+ this.append
1101
+ );
1102
+ var location = ref.location;
1103
+ var route = ref.route;
1104
+ var href = ref.href;
1105
+
1106
+ var classes = {};
1107
+ var globalActiveClass = router.options.linkActiveClass;
1108
+ var globalExactActiveClass = router.options.linkExactActiveClass;
1109
+ // Support global empty active class
1110
+ var activeClassFallback =
1111
+ globalActiveClass == null ? 'router-link-active' : globalActiveClass;
1112
+ var exactActiveClassFallback =
1113
+ globalExactActiveClass == null
1114
+ ? 'router-link-exact-active'
1115
+ : globalExactActiveClass;
1116
+ var activeClass =
1117
+ this.activeClass == null ? activeClassFallback : this.activeClass;
1118
+ var exactActiveClass =
1119
+ this.exactActiveClass == null
1120
+ ? exactActiveClassFallback
1121
+ : this.exactActiveClass;
1122
+
1123
+ var compareTarget = route.redirectedFrom
1124
+ ? createRoute(null, normalizeLocation(route.redirectedFrom), null, router)
1125
+ : route;
1126
+
1127
+ classes[exactActiveClass] = isSameRoute(current, compareTarget, this.exactPath);
1128
+ classes[activeClass] = this.exact || this.exactPath
1129
+ ? classes[exactActiveClass]
1130
+ : isIncludedRoute(current, compareTarget);
1131
+
1132
+ var ariaCurrentValue = classes[exactActiveClass] ? this.ariaCurrentValue : null;
1133
+
1134
+ var handler = function (e) {
1135
+ if (guardEvent(e)) {
1136
+ if (this$1.replace) {
1137
+ router.replace(location, noop);
1138
+ } else {
1139
+ router.push(location, noop);
1140
+ }
1141
+ }
1142
+ };
1143
+
1144
+ var on = { click: guardEvent };
1145
+ if (Array.isArray(this.event)) {
1146
+ this.event.forEach(function (e) {
1147
+ on[e] = handler;
1148
+ });
1149
+ } else {
1150
+ on[this.event] = handler;
1151
+ }
1152
+
1153
+ var data = { class: classes };
1154
+
1155
+ var scopedSlot =
1156
+ !this.$scopedSlots.$hasNormal &&
1157
+ this.$scopedSlots.default &&
1158
+ this.$scopedSlots.default({
1159
+ href: href,
1160
+ route: route,
1161
+ navigate: handler,
1162
+ isActive: classes[activeClass],
1163
+ isExactActive: classes[exactActiveClass]
1164
+ });
1165
+
1166
+ if (scopedSlot) {
1167
+ if (process.env.NODE_ENV !== 'production' && !this.custom) {
1168
+ !warnedCustomSlot && warn(false, 'In Kdu Router 4, the k-slot API will by default wrap its content with an <a> element. Use the custom prop to remove this warning:\n<router-link k-slot="{ navigate, href }" custom></router-link>\n');
1169
+ warnedCustomSlot = true;
1170
+ }
1171
+ if (scopedSlot.length === 1) {
1172
+ return scopedSlot[0]
1173
+ } else if (scopedSlot.length > 1 || !scopedSlot.length) {
1174
+ if (process.env.NODE_ENV !== 'production') {
1175
+ warn(
1176
+ false,
1177
+ ("<router-link> with to=\"" + (this.to) + "\" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.")
1178
+ );
1179
+ }
1180
+ return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
1181
+ }
1182
+ }
1183
+
1184
+ if (process.env.NODE_ENV !== 'production') {
1185
+ if ('tag' in this.$options.propsData && !warnedTagProp) {
1186
+ warn(
1187
+ false,
1188
+ "<router-link>'s tag prop is deprecated and has been removed in Kdu Router 4. Use the k-slot API to remove this warning: https://kdujs-router.web.app/guide/migration/#removal-of-event-and-tag-props-in-router-link."
1189
+ );
1190
+ warnedTagProp = true;
1191
+ }
1192
+ if ('event' in this.$options.propsData && !warnedEventProp) {
1193
+ warn(
1194
+ false,
1195
+ "<router-link>'s event prop is deprecated and has been removed in Kdu Router 4. Use the k-slot API to remove this warning: https://kdujs-router.web.app/guide/migration/#removal-of-event-and-tag-props-in-router-link."
1196
+ );
1197
+ warnedEventProp = true;
1198
+ }
1199
+ }
1200
+
1201
+ if (this.tag === 'a') {
1202
+ data.on = on;
1203
+ data.attrs = { href: href, 'aria-current': ariaCurrentValue };
1204
+ } else {
1205
+ // find the first <a> child and apply listener and href
1206
+ var a = findAnchor(this.$slots.default);
1207
+ if (a) {
1208
+ // in case the <a> is a static node
1209
+ a.isStatic = false;
1210
+ var aData = (a.data = extend({}, a.data));
1211
+ aData.on = aData.on || {};
1212
+ // transform existing events in both objects into arrays so we can push later
1213
+ for (var event in aData.on) {
1214
+ var handler$1 = aData.on[event];
1215
+ if (event in on) {
1216
+ aData.on[event] = Array.isArray(handler$1) ? handler$1 : [handler$1];
1217
+ }
1218
+ }
1219
+ // append new listeners for router-link
1220
+ for (var event$1 in on) {
1221
+ if (event$1 in aData.on) {
1222
+ // on[event] is always a function
1223
+ aData.on[event$1].push(on[event$1]);
1224
+ } else {
1225
+ aData.on[event$1] = handler;
1226
+ }
1227
+ }
1228
+
1229
+ var aAttrs = (a.data.attrs = extend({}, a.data.attrs));
1230
+ aAttrs.href = href;
1231
+ aAttrs['aria-current'] = ariaCurrentValue;
1232
+ } else {
1233
+ // doesn't have <a> child, apply listener to self
1234
+ data.on = on;
1235
+ }
1236
+ }
1237
+
1238
+ return h(this.tag, data, this.$slots.default)
1239
+ }
1240
+ };
1241
+
1242
+ function guardEvent (e) {
1243
+ // don't redirect with control keys
1244
+ if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
1245
+ // don't redirect when preventDefault called
1246
+ if (e.defaultPrevented) { return }
1247
+ // don't redirect on right click
1248
+ if (e.button !== undefined && e.button !== 0) { return }
1249
+ // don't redirect if `target="_blank"`
1250
+ if (e.currentTarget && e.currentTarget.getAttribute) {
1251
+ var target = e.currentTarget.getAttribute('target');
1252
+ if (/\b_blank\b/i.test(target)) { return }
1253
+ }
1254
+ // this may be a Weex event which doesn't have this method
1255
+ if (e.preventDefault) {
1256
+ e.preventDefault();
1257
+ }
1258
+ return true
1259
+ }
1260
+
1261
+ function findAnchor (children) {
1262
+ if (children) {
1263
+ var child;
1264
+ for (var i = 0; i < children.length; i++) {
1265
+ child = children[i];
1266
+ if (child.tag === 'a') {
1267
+ return child
1268
+ }
1269
+ if (child.children && (child = findAnchor(child.children))) {
1270
+ return child
1271
+ }
1272
+ }
1273
+ }
1274
+ }
1275
+
1276
+ var _Kdu;
1277
+
1278
+ function install (Kdu) {
1279
+ if (install.installed && _Kdu === Kdu) { return }
1280
+ install.installed = true;
1281
+
1282
+ _Kdu = Kdu;
1283
+
1284
+ var isDef = function (v) { return v !== undefined; };
1285
+
1286
+ var registerInstance = function (vm, callVal) {
1287
+ var i = vm.$options._parentKnode;
1288
+ if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
1289
+ i(vm, callVal);
1290
+ }
1291
+ };
1292
+
1293
+ Kdu.mixin({
1294
+ beforeCreate: function beforeCreate () {
1295
+ if (isDef(this.$options.router)) {
1296
+ this._routerRoot = this;
1297
+ this._router = this.$options.router;
1298
+ this._router.init(this);
1299
+ Kdu.util.defineReactive(this, '_route', this._router.history.current);
1300
+ } else {
1301
+ this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
1302
+ }
1303
+ registerInstance(this, this);
1304
+ },
1305
+ destroyed: function destroyed () {
1306
+ registerInstance(this);
1307
+ }
1308
+ });
1309
+
1310
+ Object.defineProperty(Kdu.prototype, '$router', {
1311
+ get: function get () { return this._routerRoot._router }
1312
+ });
1313
+
1314
+ Object.defineProperty(Kdu.prototype, '$route', {
1315
+ get: function get () { return this._routerRoot._route }
1316
+ });
1317
+
1318
+ Kdu.component('RouterView', View);
1319
+ Kdu.component('RouterLink', Link);
1320
+
1321
+ var strats = Kdu.config.optionMergeStrategies;
1322
+ // use the same hook merging strategy for route hooks
1323
+ strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
1324
+ }
1325
+
1326
+ /* */
1327
+
1328
+ var inBrowser = typeof window !== 'undefined';
1329
+
1330
+ /* */
1331
+
1332
+ function createRouteMap (
1333
+ routes,
1334
+ oldPathList,
1335
+ oldPathMap,
1336
+ oldNameMap,
1337
+ parentRoute
1338
+ ) {
1339
+ // the path list is used to control path matching priority
1340
+ var pathList = oldPathList || [];
1341
+ // $flow-disable-line
1342
+ var pathMap = oldPathMap || Object.create(null);
1343
+ // $flow-disable-line
1344
+ var nameMap = oldNameMap || Object.create(null);
1345
+
1346
+ routes.forEach(function (route) {
1347
+ addRouteRecord(pathList, pathMap, nameMap, route, parentRoute);
1348
+ });
1349
+
1350
+ // ensure wildcard routes are always at the end
1351
+ for (var i = 0, l = pathList.length; i < l; i++) {
1352
+ if (pathList[i] === '*') {
1353
+ pathList.push(pathList.splice(i, 1)[0]);
1354
+ l--;
1355
+ i--;
1356
+ }
1357
+ }
1358
+
1359
+ if (process.env.NODE_ENV === 'development') {
1360
+ // warn if routes do not include leading slashes
1361
+ var found = pathList
1362
+ // check for missing leading slash
1363
+ .filter(function (path) { return path && path.charAt(0) !== '*' && path.charAt(0) !== '/'; });
1364
+
1365
+ if (found.length > 0) {
1366
+ var pathNames = found.map(function (path) { return ("- " + path); }).join('\n');
1367
+ warn(false, ("Non-nested routes must include a leading slash character. Fix the following routes: \n" + pathNames));
1368
+ }
1369
+ }
1370
+
1371
+ return {
1372
+ pathList: pathList,
1373
+ pathMap: pathMap,
1374
+ nameMap: nameMap
1375
+ }
1376
+ }
1377
+
1378
+ function addRouteRecord (
1379
+ pathList,
1380
+ pathMap,
1381
+ nameMap,
1382
+ route,
1383
+ parent,
1384
+ matchAs
1385
+ ) {
1386
+ var path = route.path;
1387
+ var name = route.name;
1388
+ if (process.env.NODE_ENV !== 'production') {
1389
+ assert(path != null, "\"path\" is required in a route configuration.");
1390
+ assert(
1391
+ typeof route.component !== 'string',
1392
+ "route config \"component\" for path: " + (String(
1393
+ path || name
1394
+ )) + " cannot be a " + "string id. Use an actual component instead."
1395
+ );
1396
+
1397
+ warn(
1398
+ // eslint-disable-next-line no-control-regex
1399
+ !/[^\u0000-\u007F]+/.test(path),
1400
+ "Route with path \"" + path + "\" contains unencoded characters, make sure " +
1401
+ "your path is correctly encoded before passing it to the router. Use " +
1402
+ "encodeURI to encode static segments of your path."
1403
+ );
1404
+ }
1405
+
1406
+ var pathToRegexpOptions =
1407
+ route.pathToRegexpOptions || {};
1408
+ var normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
1409
+
1410
+ if (typeof route.caseSensitive === 'boolean') {
1411
+ pathToRegexpOptions.sensitive = route.caseSensitive;
1412
+ }
1413
+
1414
+ var record = {
1415
+ path: normalizedPath,
1416
+ regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
1417
+ components: route.components || { default: route.component },
1418
+ alias: route.alias
1419
+ ? typeof route.alias === 'string'
1420
+ ? [route.alias]
1421
+ : route.alias
1422
+ : [],
1423
+ instances: {},
1424
+ enteredCbs: {},
1425
+ name: name,
1426
+ parent: parent,
1427
+ matchAs: matchAs,
1428
+ redirect: route.redirect,
1429
+ beforeEnter: route.beforeEnter,
1430
+ meta: route.meta || {},
1431
+ props:
1432
+ route.props == null
1433
+ ? {}
1434
+ : route.components
1435
+ ? route.props
1436
+ : { default: route.props }
1437
+ };
1438
+
1439
+ if (route.children) {
1440
+ // Warn if route is named, does not redirect and has a default child route.
1441
+ // If users navigate to this route by name, the default child will
1442
+ // not be rendered (GH Issue #629)
1443
+ if (process.env.NODE_ENV !== 'production') {
1444
+ if (
1445
+ route.name &&
1446
+ !route.redirect &&
1447
+ route.children.some(function (child) { return /^\/?$/.test(child.path); })
1448
+ ) {
1449
+ warn(
1450
+ false,
1451
+ "Named Route '" + (route.name) + "' has a default child route. " +
1452
+ "When navigating to this named route (:to=\"{name: '" + (route.name) + "'}\"), " +
1453
+ "the default child route will not be rendered. Remove the name from " +
1454
+ "this route and use the name of the default child route for named " +
1455
+ "links instead."
1456
+ );
1457
+ }
1458
+ }
1459
+ route.children.forEach(function (child) {
1460
+ var childMatchAs = matchAs
1461
+ ? cleanPath((matchAs + "/" + (child.path)))
1462
+ : undefined;
1463
+ addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
1464
+ });
1465
+ }
1466
+
1467
+ if (!pathMap[record.path]) {
1468
+ pathList.push(record.path);
1469
+ pathMap[record.path] = record;
1470
+ }
1471
+
1472
+ if (route.alias !== undefined) {
1473
+ var aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
1474
+ for (var i = 0; i < aliases.length; ++i) {
1475
+ var alias = aliases[i];
1476
+ if (process.env.NODE_ENV !== 'production' && alias === path) {
1477
+ warn(
1478
+ false,
1479
+ ("Found an alias with the same value as the path: \"" + path + "\". You have to remove that alias. It will be ignored in development.")
1480
+ );
1481
+ // skip in dev to make it work
1482
+ continue
1483
+ }
1484
+
1485
+ var aliasRoute = {
1486
+ path: alias,
1487
+ children: route.children
1488
+ };
1489
+ addRouteRecord(
1490
+ pathList,
1491
+ pathMap,
1492
+ nameMap,
1493
+ aliasRoute,
1494
+ parent,
1495
+ record.path || '/' // matchAs
1496
+ );
1497
+ }
1498
+ }
1499
+
1500
+ if (name) {
1501
+ if (!nameMap[name]) {
1502
+ nameMap[name] = record;
1503
+ } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
1504
+ warn(
1505
+ false,
1506
+ "Duplicate named routes definition: " +
1507
+ "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
1508
+ );
1509
+ }
1510
+ }
1511
+ }
1512
+
1513
+ function compileRouteRegex (
1514
+ path,
1515
+ pathToRegexpOptions
1516
+ ) {
1517
+ var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
1518
+ if (process.env.NODE_ENV !== 'production') {
1519
+ var keys = Object.create(null);
1520
+ regex.keys.forEach(function (key) {
1521
+ warn(
1522
+ !keys[key.name],
1523
+ ("Duplicate param keys in route with path: \"" + path + "\"")
1524
+ );
1525
+ keys[key.name] = true;
1526
+ });
1527
+ }
1528
+ return regex
1529
+ }
1530
+
1531
+ function normalizePath (
1532
+ path,
1533
+ parent,
1534
+ strict
1535
+ ) {
1536
+ if (!strict) { path = path.replace(/\/$/, ''); }
1537
+ if (path[0] === '/') { return path }
1538
+ if (parent == null) { return path }
1539
+ return cleanPath(((parent.path) + "/" + path))
1540
+ }
1541
+
1542
+ /* */
1543
+
1544
+
1545
+
1546
+ function createMatcher (
1547
+ routes,
1548
+ router
1549
+ ) {
1550
+ var ref = createRouteMap(routes);
1551
+ var pathList = ref.pathList;
1552
+ var pathMap = ref.pathMap;
1553
+ var nameMap = ref.nameMap;
1554
+
1555
+ function addRoutes (routes) {
1556
+ createRouteMap(routes, pathList, pathMap, nameMap);
1557
+ }
1558
+
1559
+ function addRoute (parentOrRoute, route) {
1560
+ var parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined;
1561
+ // $flow-disable-line
1562
+ createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent);
1563
+
1564
+ // add aliases of parent
1565
+ if (parent && parent.alias.length) {
1566
+ createRouteMap(
1567
+ // $flow-disable-line route is defined if parent is
1568
+ parent.alias.map(function (alias) { return ({ path: alias, children: [route] }); }),
1569
+ pathList,
1570
+ pathMap,
1571
+ nameMap,
1572
+ parent
1573
+ );
1574
+ }
1575
+ }
1576
+
1577
+ function getRoutes () {
1578
+ return pathList.map(function (path) { return pathMap[path]; })
1579
+ }
1580
+
1581
+ function match (
1582
+ raw,
1583
+ currentRoute,
1584
+ redirectedFrom
1585
+ ) {
1586
+ var location = normalizeLocation(raw, currentRoute, false, router);
1587
+ var name = location.name;
1588
+
1589
+ if (name) {
1590
+ var record = nameMap[name];
1591
+ if (process.env.NODE_ENV !== 'production') {
1592
+ warn(record, ("Route with name '" + name + "' does not exist"));
1593
+ }
1594
+ if (!record) { return _createRoute(null, location) }
1595
+ var paramNames = record.regex.keys
1596
+ .filter(function (key) { return !key.optional; })
1597
+ .map(function (key) { return key.name; });
1598
+
1599
+ if (typeof location.params !== 'object') {
1600
+ location.params = {};
1601
+ }
1602
+
1603
+ if (currentRoute && typeof currentRoute.params === 'object') {
1604
+ for (var key in currentRoute.params) {
1605
+ if (!(key in location.params) && paramNames.indexOf(key) > -1) {
1606
+ location.params[key] = currentRoute.params[key];
1607
+ }
1608
+ }
1609
+ }
1610
+
1611
+ location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
1612
+ return _createRoute(record, location, redirectedFrom)
1613
+ } else if (location.path) {
1614
+ location.params = {};
1615
+ for (var i = 0; i < pathList.length; i++) {
1616
+ var path = pathList[i];
1617
+ var record$1 = pathMap[path];
1618
+ if (matchRoute(record$1.regex, location.path, location.params)) {
1619
+ return _createRoute(record$1, location, redirectedFrom)
1620
+ }
1621
+ }
1622
+ }
1623
+ // no match
1624
+ return _createRoute(null, location)
1625
+ }
1626
+
1627
+ function redirect (
1628
+ record,
1629
+ location
1630
+ ) {
1631
+ var originalRedirect = record.redirect;
1632
+ var redirect = typeof originalRedirect === 'function'
1633
+ ? originalRedirect(createRoute(record, location, null, router))
1634
+ : originalRedirect;
1635
+
1636
+ if (typeof redirect === 'string') {
1637
+ redirect = { path: redirect };
1638
+ }
1639
+
1640
+ if (!redirect || typeof redirect !== 'object') {
1641
+ if (process.env.NODE_ENV !== 'production') {
1642
+ warn(
1643
+ false, ("invalid redirect option: " + (JSON.stringify(redirect)))
1644
+ );
1645
+ }
1646
+ return _createRoute(null, location)
1647
+ }
1648
+
1649
+ var re = redirect;
1650
+ var name = re.name;
1651
+ var path = re.path;
1652
+ var query = location.query;
1653
+ var hash = location.hash;
1654
+ var params = location.params;
1655
+ query = re.hasOwnProperty('query') ? re.query : query;
1656
+ hash = re.hasOwnProperty('hash') ? re.hash : hash;
1657
+ params = re.hasOwnProperty('params') ? re.params : params;
1658
+
1659
+ if (name) {
1660
+ // resolved named direct
1661
+ var targetRecord = nameMap[name];
1662
+ if (process.env.NODE_ENV !== 'production') {
1663
+ assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
1664
+ }
1665
+ return match({
1666
+ _normalized: true,
1667
+ name: name,
1668
+ query: query,
1669
+ hash: hash,
1670
+ params: params
1671
+ }, undefined, location)
1672
+ } else if (path) {
1673
+ // 1. resolve relative redirect
1674
+ var rawPath = resolveRecordPath(path, record);
1675
+ // 2. resolve params
1676
+ var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
1677
+ // 3. rematch with existing query and hash
1678
+ return match({
1679
+ _normalized: true,
1680
+ path: resolvedPath,
1681
+ query: query,
1682
+ hash: hash
1683
+ }, undefined, location)
1684
+ } else {
1685
+ if (process.env.NODE_ENV !== 'production') {
1686
+ warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
1687
+ }
1688
+ return _createRoute(null, location)
1689
+ }
1690
+ }
1691
+
1692
+ function alias (
1693
+ record,
1694
+ location,
1695
+ matchAs
1696
+ ) {
1697
+ var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
1698
+ var aliasedMatch = match({
1699
+ _normalized: true,
1700
+ path: aliasedPath
1701
+ });
1702
+ if (aliasedMatch) {
1703
+ var matched = aliasedMatch.matched;
1704
+ var aliasedRecord = matched[matched.length - 1];
1705
+ location.params = aliasedMatch.params;
1706
+ return _createRoute(aliasedRecord, location)
1707
+ }
1708
+ return _createRoute(null, location)
1709
+ }
1710
+
1711
+ function _createRoute (
1712
+ record,
1713
+ location,
1714
+ redirectedFrom
1715
+ ) {
1716
+ if (record && record.redirect) {
1717
+ return redirect(record, redirectedFrom || location)
1718
+ }
1719
+ if (record && record.matchAs) {
1720
+ return alias(record, location, record.matchAs)
1721
+ }
1722
+ return createRoute(record, location, redirectedFrom, router)
1723
+ }
1724
+
1725
+ return {
1726
+ match: match,
1727
+ addRoute: addRoute,
1728
+ getRoutes: getRoutes,
1729
+ addRoutes: addRoutes
1730
+ }
1731
+ }
1732
+
1733
+ function matchRoute (
1734
+ regex,
1735
+ path,
1736
+ params
1737
+ ) {
1738
+ var m = path.match(regex);
1739
+
1740
+ if (!m) {
1741
+ return false
1742
+ } else if (!params) {
1743
+ return true
1744
+ }
1745
+
1746
+ for (var i = 1, len = m.length; i < len; ++i) {
1747
+ var key = regex.keys[i - 1];
1748
+ if (key) {
1749
+ // Fix #1994: using * with props: true generates a param named 0
1750
+ params[key.name || 'pathMatch'] = typeof m[i] === 'string' ? decode(m[i]) : m[i];
1751
+ }
1752
+ }
1753
+
1754
+ return true
1755
+ }
1756
+
1757
+ function resolveRecordPath (path, record) {
1758
+ return resolvePath(path, record.parent ? record.parent.path : '/', true)
1759
+ }
1760
+
1761
+ /* */
1762
+
1763
+ // use User Timing api (if present) for more accurate key precision
1764
+ var Time =
1765
+ inBrowser && window.performance && window.performance.now
1766
+ ? window.performance
1767
+ : Date;
1768
+
1769
+ function genStateKey () {
1770
+ return Time.now().toFixed(3)
1771
+ }
1772
+
1773
+ var _key = genStateKey();
1774
+
1775
+ function getStateKey () {
1776
+ return _key
1777
+ }
1778
+
1779
+ function setStateKey (key) {
1780
+ return (_key = key)
1781
+ }
1782
+
1783
+ /* */
1784
+
1785
+ var positionStore = Object.create(null);
1786
+
1787
+ function setupScroll () {
1788
+ // Prevent browser scroll behavior on History popstate
1789
+ if ('scrollRestoration' in window.history) {
1790
+ window.history.scrollRestoration = 'manual';
1791
+ }
1792
+ // Fix for #1585 for Firefox
1793
+ // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
1794
+ // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
1795
+ // window.location.protocol + '//' + window.location.host
1796
+ // location.host contains the port and location.hostname doesn't
1797
+ var protocolAndPath = window.location.protocol + '//' + window.location.host;
1798
+ var absolutePath = window.location.href.replace(protocolAndPath, '');
1799
+ // preserve existing history state as it could be overriden by the user
1800
+ var stateCopy = extend({}, window.history.state);
1801
+ stateCopy.key = getStateKey();
1802
+ window.history.replaceState(stateCopy, '', absolutePath);
1803
+ window.addEventListener('popstate', handlePopState);
1804
+ return function () {
1805
+ window.removeEventListener('popstate', handlePopState);
1806
+ }
1807
+ }
1808
+
1809
+ function handleScroll (
1810
+ router,
1811
+ to,
1812
+ from,
1813
+ isPop
1814
+ ) {
1815
+ if (!router.app) {
1816
+ return
1817
+ }
1818
+
1819
+ var behavior = router.options.scrollBehavior;
1820
+ if (!behavior) {
1821
+ return
1822
+ }
1823
+
1824
+ if (process.env.NODE_ENV !== 'production') {
1825
+ assert(typeof behavior === 'function', "scrollBehavior must be a function");
1826
+ }
1827
+
1828
+ // wait until re-render finishes before scrolling
1829
+ router.app.$nextTick(function () {
1830
+ var position = getScrollPosition();
1831
+ var shouldScroll = behavior.call(
1832
+ router,
1833
+ to,
1834
+ from,
1835
+ isPop ? position : null
1836
+ );
1837
+
1838
+ if (!shouldScroll) {
1839
+ return
1840
+ }
1841
+
1842
+ if (typeof shouldScroll.then === 'function') {
1843
+ shouldScroll
1844
+ .then(function (shouldScroll) {
1845
+ scrollToPosition((shouldScroll), position);
1846
+ })
1847
+ .catch(function (err) {
1848
+ if (process.env.NODE_ENV !== 'production') {
1849
+ assert(false, err.toString());
1850
+ }
1851
+ });
1852
+ } else {
1853
+ scrollToPosition(shouldScroll, position);
1854
+ }
1855
+ });
1856
+ }
1857
+
1858
+ function saveScrollPosition () {
1859
+ var key = getStateKey();
1860
+ if (key) {
1861
+ positionStore[key] = {
1862
+ x: window.pageXOffset,
1863
+ y: window.pageYOffset
1864
+ };
1865
+ }
1866
+ }
1867
+
1868
+ function handlePopState (e) {
1869
+ saveScrollPosition();
1870
+ if (e.state && e.state.key) {
1871
+ setStateKey(e.state.key);
1872
+ }
1873
+ }
1874
+
1875
+ function getScrollPosition () {
1876
+ var key = getStateKey();
1877
+ if (key) {
1878
+ return positionStore[key]
1879
+ }
1880
+ }
1881
+
1882
+ function getElementPosition (el, offset) {
1883
+ var docEl = document.documentElement;
1884
+ var docRect = docEl.getBoundingClientRect();
1885
+ var elRect = el.getBoundingClientRect();
1886
+ return {
1887
+ x: elRect.left - docRect.left - offset.x,
1888
+ y: elRect.top - docRect.top - offset.y
1889
+ }
1890
+ }
1891
+
1892
+ function isValidPosition (obj) {
1893
+ return isNumber(obj.x) || isNumber(obj.y)
1894
+ }
1895
+
1896
+ function normalizePosition (obj) {
1897
+ return {
1898
+ x: isNumber(obj.x) ? obj.x : window.pageXOffset,
1899
+ y: isNumber(obj.y) ? obj.y : window.pageYOffset
1900
+ }
1901
+ }
1902
+
1903
+ function normalizeOffset (obj) {
1904
+ return {
1905
+ x: isNumber(obj.x) ? obj.x : 0,
1906
+ y: isNumber(obj.y) ? obj.y : 0
1907
+ }
1908
+ }
1909
+
1910
+ function isNumber (v) {
1911
+ return typeof v === 'number'
1912
+ }
1913
+
1914
+ var hashStartsWithNumberRE = /^#\d/;
1915
+
1916
+ function scrollToPosition (shouldScroll, position) {
1917
+ var isObject = typeof shouldScroll === 'object';
1918
+ if (isObject && typeof shouldScroll.selector === 'string') {
1919
+ // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
1920
+ // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
1921
+ var el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
1922
+ ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
1923
+ : document.querySelector(shouldScroll.selector);
1924
+
1925
+ if (el) {
1926
+ var offset =
1927
+ shouldScroll.offset && typeof shouldScroll.offset === 'object'
1928
+ ? shouldScroll.offset
1929
+ : {};
1930
+ offset = normalizeOffset(offset);
1931
+ position = getElementPosition(el, offset);
1932
+ } else if (isValidPosition(shouldScroll)) {
1933
+ position = normalizePosition(shouldScroll);
1934
+ }
1935
+ } else if (isObject && isValidPosition(shouldScroll)) {
1936
+ position = normalizePosition(shouldScroll);
1937
+ }
1938
+
1939
+ if (position) {
1940
+ // $flow-disable-line
1941
+ if ('scrollBehavior' in document.documentElement.style) {
1942
+ window.scrollTo({
1943
+ left: position.x,
1944
+ top: position.y,
1945
+ // $flow-disable-line
1946
+ behavior: shouldScroll.behavior
1947
+ });
1948
+ } else {
1949
+ window.scrollTo(position.x, position.y);
1950
+ }
1951
+ }
1952
+ }
1953
+
1954
+ /* */
1955
+
1956
+ var supportsPushState =
1957
+ inBrowser &&
1958
+ (function () {
1959
+ var ua = window.navigator.userAgent;
1960
+
1961
+ if (
1962
+ (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
1963
+ ua.indexOf('Mobile Safari') !== -1 &&
1964
+ ua.indexOf('Chrome') === -1 &&
1965
+ ua.indexOf('Windows Phone') === -1
1966
+ ) {
1967
+ return false
1968
+ }
1969
+
1970
+ return window.history && typeof window.history.pushState === 'function'
1971
+ })();
1972
+
1973
+ function pushState (url, replace) {
1974
+ saveScrollPosition();
1975
+ // try...catch the pushState call to get around Safari
1976
+ // DOM Exception 18 where it limits to 100 pushState calls
1977
+ var history = window.history;
1978
+ try {
1979
+ if (replace) {
1980
+ // preserve existing history state as it could be overriden by the user
1981
+ var stateCopy = extend({}, history.state);
1982
+ stateCopy.key = getStateKey();
1983
+ history.replaceState(stateCopy, '', url);
1984
+ } else {
1985
+ history.pushState({ key: setStateKey(genStateKey()) }, '', url);
1986
+ }
1987
+ } catch (e) {
1988
+ window.location[replace ? 'replace' : 'assign'](url);
1989
+ }
1990
+ }
1991
+
1992
+ function replaceState (url) {
1993
+ pushState(url, true);
1994
+ }
1995
+
1996
+ // When changing thing, also edit router.d.ts
1997
+ var NavigationFailureType = {
1998
+ redirected: 2,
1999
+ aborted: 4,
2000
+ cancelled: 8,
2001
+ duplicated: 16
2002
+ };
2003
+
2004
+ function createNavigationRedirectedError (from, to) {
2005
+ return createRouterError(
2006
+ from,
2007
+ to,
2008
+ NavigationFailureType.redirected,
2009
+ ("Redirected when going from \"" + (from.fullPath) + "\" to \"" + (stringifyRoute(
2010
+ to
2011
+ )) + "\" via a navigation guard.")
2012
+ )
2013
+ }
2014
+
2015
+ function createNavigationDuplicatedError (from, to) {
2016
+ var error = createRouterError(
2017
+ from,
2018
+ to,
2019
+ NavigationFailureType.duplicated,
2020
+ ("Avoided redundant navigation to current location: \"" + (from.fullPath) + "\".")
2021
+ );
2022
+ // backwards compatible with the first introduction of Errors
2023
+ error.name = 'NavigationDuplicated';
2024
+ return error
2025
+ }
2026
+
2027
+ function createNavigationCancelledError (from, to) {
2028
+ return createRouterError(
2029
+ from,
2030
+ to,
2031
+ NavigationFailureType.cancelled,
2032
+ ("Navigation cancelled from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" with a new navigation.")
2033
+ )
2034
+ }
2035
+
2036
+ function createNavigationAbortedError (from, to) {
2037
+ return createRouterError(
2038
+ from,
2039
+ to,
2040
+ NavigationFailureType.aborted,
2041
+ ("Navigation aborted from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" via a navigation guard.")
2042
+ )
2043
+ }
2044
+
2045
+ function createRouterError (from, to, type, message) {
2046
+ var error = new Error(message);
2047
+ error._isRouter = true;
2048
+ error.from = from;
2049
+ error.to = to;
2050
+ error.type = type;
2051
+
2052
+ return error
2053
+ }
2054
+
2055
+ var propertiesToLog = ['params', 'query', 'hash'];
2056
+
2057
+ function stringifyRoute (to) {
2058
+ if (typeof to === 'string') { return to }
2059
+ if ('path' in to) { return to.path }
2060
+ var location = {};
2061
+ propertiesToLog.forEach(function (key) {
2062
+ if (key in to) { location[key] = to[key]; }
2063
+ });
2064
+ return JSON.stringify(location, null, 2)
2065
+ }
2066
+
2067
+ function isError (err) {
2068
+ return Object.prototype.toString.call(err).indexOf('Error') > -1
2069
+ }
2070
+
2071
+ function isNavigationFailure (err, errorType) {
2072
+ return (
2073
+ isError(err) &&
2074
+ err._isRouter &&
2075
+ (errorType == null || err.type === errorType)
2076
+ )
2077
+ }
2078
+
2079
+ /* */
2080
+
2081
+ function runQueue (queue, fn, cb) {
2082
+ var step = function (index) {
2083
+ if (index >= queue.length) {
2084
+ cb();
2085
+ } else {
2086
+ if (queue[index]) {
2087
+ fn(queue[index], function () {
2088
+ step(index + 1);
2089
+ });
2090
+ } else {
2091
+ step(index + 1);
2092
+ }
2093
+ }
2094
+ };
2095
+ step(0);
2096
+ }
2097
+
2098
+ /* */
2099
+
2100
+ function resolveAsyncComponents (matched) {
2101
+ return function (to, from, next) {
2102
+ var hasAsync = false;
2103
+ var pending = 0;
2104
+ var error = null;
2105
+
2106
+ flatMapComponents(matched, function (def, _, match, key) {
2107
+ // if it's a function and doesn't have cid attached,
2108
+ // assume it's an async component resolve function.
2109
+ // we are not using Kdu's default async resolving mechanism because
2110
+ // we want to halt the navigation until the incoming component has been
2111
+ // resolved.
2112
+ if (typeof def === 'function' && def.cid === undefined) {
2113
+ hasAsync = true;
2114
+ pending++;
2115
+
2116
+ var resolve = once(function (resolvedDef) {
2117
+ if (isESModule(resolvedDef)) {
2118
+ resolvedDef = resolvedDef.default;
2119
+ }
2120
+ // save resolved on async factory in case it's used elsewhere
2121
+ def.resolved = typeof resolvedDef === 'function'
2122
+ ? resolvedDef
2123
+ : _Kdu.extend(resolvedDef);
2124
+ match.components[key] = resolvedDef;
2125
+ pending--;
2126
+ if (pending <= 0) {
2127
+ next();
2128
+ }
2129
+ });
2130
+
2131
+ var reject = once(function (reason) {
2132
+ var msg = "Failed to resolve async component " + key + ": " + reason;
2133
+ process.env.NODE_ENV !== 'production' && warn(false, msg);
2134
+ if (!error) {
2135
+ error = isError(reason)
2136
+ ? reason
2137
+ : new Error(msg);
2138
+ next(error);
2139
+ }
2140
+ });
2141
+
2142
+ var res;
2143
+ try {
2144
+ res = def(resolve, reject);
2145
+ } catch (e) {
2146
+ reject(e);
2147
+ }
2148
+ if (res) {
2149
+ if (typeof res.then === 'function') {
2150
+ res.then(resolve, reject);
2151
+ } else {
2152
+ // new syntax in Kdu 2.3
2153
+ var comp = res.component;
2154
+ if (comp && typeof comp.then === 'function') {
2155
+ comp.then(resolve, reject);
2156
+ }
2157
+ }
2158
+ }
2159
+ }
2160
+ });
2161
+
2162
+ if (!hasAsync) { next(); }
2163
+ }
2164
+ }
2165
+
2166
+ function flatMapComponents (
2167
+ matched,
2168
+ fn
2169
+ ) {
2170
+ return flatten(matched.map(function (m) {
2171
+ return Object.keys(m.components).map(function (key) { return fn(
2172
+ m.components[key],
2173
+ m.instances[key],
2174
+ m, key
2175
+ ); })
2176
+ }))
2177
+ }
2178
+
2179
+ function flatten (arr) {
2180
+ return Array.prototype.concat.apply([], arr)
2181
+ }
2182
+
2183
+ var hasSymbol =
2184
+ typeof Symbol === 'function' &&
2185
+ typeof Symbol.toStringTag === 'symbol';
2186
+
2187
+ function isESModule (obj) {
2188
+ return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
2189
+ }
2190
+
2191
+ // in Webpack 2, require.ensure now also returns a Promise
2192
+ // so the resolve/reject functions may get called an extra time
2193
+ // if the user uses an arrow function shorthand that happens to
2194
+ // return that Promise.
2195
+ function once (fn) {
2196
+ var called = false;
2197
+ return function () {
2198
+ var args = [], len = arguments.length;
2199
+ while ( len-- ) args[ len ] = arguments[ len ];
2200
+
2201
+ if (called) { return }
2202
+ called = true;
2203
+ return fn.apply(this, args)
2204
+ }
2205
+ }
2206
+
2207
+ /* */
2208
+
2209
+ var History = function History (router, base) {
2210
+ this.router = router;
2211
+ this.base = normalizeBase(base);
2212
+ // start with a route object that stands for "nowhere"
2213
+ this.current = START;
2214
+ this.pending = null;
2215
+ this.ready = false;
2216
+ this.readyCbs = [];
2217
+ this.readyErrorCbs = [];
2218
+ this.errorCbs = [];
2219
+ this.listeners = [];
2220
+ };
2221
+
2222
+ History.prototype.listen = function listen (cb) {
2223
+ this.cb = cb;
2224
+ };
2225
+
2226
+ History.prototype.onReady = function onReady (cb, errorCb) {
2227
+ if (this.ready) {
2228
+ cb();
2229
+ } else {
2230
+ this.readyCbs.push(cb);
2231
+ if (errorCb) {
2232
+ this.readyErrorCbs.push(errorCb);
2233
+ }
2234
+ }
2235
+ };
2236
+
2237
+ History.prototype.onError = function onError (errorCb) {
2238
+ this.errorCbs.push(errorCb);
2239
+ };
2240
+
2241
+ History.prototype.transitionTo = function transitionTo (
2242
+ location,
2243
+ onComplete,
2244
+ onAbort
2245
+ ) {
2246
+ var this$1 = this;
2247
+
2248
+ var route;
2249
+ // catch redirect option
2250
+ try {
2251
+ route = this.router.match(location, this.current);
2252
+ } catch (e) {
2253
+ this.errorCbs.forEach(function (cb) {
2254
+ cb(e);
2255
+ });
2256
+ // Exception should still be thrown
2257
+ throw e
2258
+ }
2259
+ var prev = this.current;
2260
+ this.confirmTransition(
2261
+ route,
2262
+ function () {
2263
+ this$1.updateRoute(route);
2264
+ onComplete && onComplete(route);
2265
+ this$1.ensureURL();
2266
+ this$1.router.afterHooks.forEach(function (hook) {
2267
+ hook && hook(route, prev);
2268
+ });
2269
+
2270
+ // fire ready cbs once
2271
+ if (!this$1.ready) {
2272
+ this$1.ready = true;
2273
+ this$1.readyCbs.forEach(function (cb) {
2274
+ cb(route);
2275
+ });
2276
+ }
2277
+ },
2278
+ function (err) {
2279
+ if (onAbort) {
2280
+ onAbort(err);
2281
+ }
2282
+ if (err && !this$1.ready) {
2283
+ // Initial redirection should not mark the history as ready yet
2284
+ // because it's triggered by the redirection instead
2285
+ if (!isNavigationFailure(err, NavigationFailureType.redirected) || prev !== START) {
2286
+ this$1.ready = true;
2287
+ this$1.readyErrorCbs.forEach(function (cb) {
2288
+ cb(err);
2289
+ });
2290
+ }
2291
+ }
2292
+ }
2293
+ );
2294
+ };
2295
+
2296
+ History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
2297
+ var this$1 = this;
2298
+
2299
+ var current = this.current;
2300
+ this.pending = route;
2301
+ var abort = function (err) {
2302
+ // changed after adding errors
2303
+ // before that change, redirect and aborted navigation would produce an err == null
2304
+ if (!isNavigationFailure(err) && isError(err)) {
2305
+ if (this$1.errorCbs.length) {
2306
+ this$1.errorCbs.forEach(function (cb) {
2307
+ cb(err);
2308
+ });
2309
+ } else {
2310
+ if (process.env.NODE_ENV !== 'production') {
2311
+ warn(false, 'uncaught error during route navigation:');
2312
+ }
2313
+ console.error(err);
2314
+ }
2315
+ }
2316
+ onAbort && onAbort(err);
2317
+ };
2318
+ var lastRouteIndex = route.matched.length - 1;
2319
+ var lastCurrentIndex = current.matched.length - 1;
2320
+ if (
2321
+ isSameRoute(route, current) &&
2322
+ // in the case the route map has been dynamically appended to
2323
+ lastRouteIndex === lastCurrentIndex &&
2324
+ route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
2325
+ ) {
2326
+ this.ensureURL();
2327
+ if (route.hash) {
2328
+ handleScroll(this.router, current, route, false);
2329
+ }
2330
+ return abort(createNavigationDuplicatedError(current, route))
2331
+ }
2332
+
2333
+ var ref = resolveQueue(
2334
+ this.current.matched,
2335
+ route.matched
2336
+ );
2337
+ var updated = ref.updated;
2338
+ var deactivated = ref.deactivated;
2339
+ var activated = ref.activated;
2340
+
2341
+ var queue = [].concat(
2342
+ // in-component leave guards
2343
+ extractLeaveGuards(deactivated),
2344
+ // global before hooks
2345
+ this.router.beforeHooks,
2346
+ // in-component update hooks
2347
+ extractUpdateHooks(updated),
2348
+ // in-config enter guards
2349
+ activated.map(function (m) { return m.beforeEnter; }),
2350
+ // async components
2351
+ resolveAsyncComponents(activated)
2352
+ );
2353
+
2354
+ var iterator = function (hook, next) {
2355
+ if (this$1.pending !== route) {
2356
+ return abort(createNavigationCancelledError(current, route))
2357
+ }
2358
+ try {
2359
+ hook(route, current, function (to) {
2360
+ if (to === false) {
2361
+ // next(false) -> abort navigation, ensure current URL
2362
+ this$1.ensureURL(true);
2363
+ abort(createNavigationAbortedError(current, route));
2364
+ } else if (isError(to)) {
2365
+ this$1.ensureURL(true);
2366
+ abort(to);
2367
+ } else if (
2368
+ typeof to === 'string' ||
2369
+ (typeof to === 'object' &&
2370
+ (typeof to.path === 'string' || typeof to.name === 'string'))
2371
+ ) {
2372
+ // next('/') or next({ path: '/' }) -> redirect
2373
+ abort(createNavigationRedirectedError(current, route));
2374
+ if (typeof to === 'object' && to.replace) {
2375
+ this$1.replace(to);
2376
+ } else {
2377
+ this$1.push(to);
2378
+ }
2379
+ } else {
2380
+ // confirm transition and pass on the value
2381
+ next(to);
2382
+ }
2383
+ });
2384
+ } catch (e) {
2385
+ abort(e);
2386
+ }
2387
+ };
2388
+
2389
+ runQueue(queue, iterator, function () {
2390
+ // wait until async components are resolved before
2391
+ // extracting in-component enter guards
2392
+ var enterGuards = extractEnterGuards(activated);
2393
+ var queue = enterGuards.concat(this$1.router.resolveHooks);
2394
+ runQueue(queue, iterator, function () {
2395
+ if (this$1.pending !== route) {
2396
+ return abort(createNavigationCancelledError(current, route))
2397
+ }
2398
+ this$1.pending = null;
2399
+ onComplete(route);
2400
+ if (this$1.router.app) {
2401
+ this$1.router.app.$nextTick(function () {
2402
+ handleRouteEntered(route);
2403
+ });
2404
+ }
2405
+ });
2406
+ });
2407
+ };
2408
+
2409
+ History.prototype.updateRoute = function updateRoute (route) {
2410
+ this.current = route;
2411
+ this.cb && this.cb(route);
2412
+ };
2413
+
2414
+ History.prototype.setupListeners = function setupListeners () {
2415
+ // Default implementation is empty
2416
+ };
2417
+
2418
+ History.prototype.teardown = function teardown () {
2419
+ // clean up event listeners
2420
+ this.listeners.forEach(function (cleanupListener) {
2421
+ cleanupListener();
2422
+ });
2423
+ this.listeners = [];
2424
+
2425
+ // reset current history route
2426
+ this.current = START;
2427
+ this.pending = null;
2428
+ };
2429
+
2430
+ function normalizeBase (base) {
2431
+ if (!base) {
2432
+ if (inBrowser) {
2433
+ // respect <base> tag
2434
+ var baseEl = document.querySelector('base');
2435
+ base = (baseEl && baseEl.getAttribute('href')) || '/';
2436
+ // strip full URL origin
2437
+ base = base.replace(/^https?:\/\/[^\/]+/, '');
2438
+ } else {
2439
+ base = '/';
2440
+ }
2441
+ }
2442
+ // make sure there's the starting slash
2443
+ if (base.charAt(0) !== '/') {
2444
+ base = '/' + base;
2445
+ }
2446
+ // remove trailing slash
2447
+ return base.replace(/\/$/, '')
2448
+ }
2449
+
2450
+ function resolveQueue (
2451
+ current,
2452
+ next
2453
+ ) {
2454
+ var i;
2455
+ var max = Math.max(current.length, next.length);
2456
+ for (i = 0; i < max; i++) {
2457
+ if (current[i] !== next[i]) {
2458
+ break
2459
+ }
2460
+ }
2461
+ return {
2462
+ updated: next.slice(0, i),
2463
+ activated: next.slice(i),
2464
+ deactivated: current.slice(i)
2465
+ }
2466
+ }
2467
+
2468
+ function extractGuards (
2469
+ records,
2470
+ name,
2471
+ bind,
2472
+ reverse
2473
+ ) {
2474
+ var guards = flatMapComponents(records, function (def, instance, match, key) {
2475
+ var guard = extractGuard(def, name);
2476
+ if (guard) {
2477
+ return Array.isArray(guard)
2478
+ ? guard.map(function (guard) { return bind(guard, instance, match, key); })
2479
+ : bind(guard, instance, match, key)
2480
+ }
2481
+ });
2482
+ return flatten(reverse ? guards.reverse() : guards)
2483
+ }
2484
+
2485
+ function extractGuard (
2486
+ def,
2487
+ key
2488
+ ) {
2489
+ if (typeof def !== 'function') {
2490
+ // extend now so that global mixins are applied.
2491
+ def = _Kdu.extend(def);
2492
+ }
2493
+ return def.options[key]
2494
+ }
2495
+
2496
+ function extractLeaveGuards (deactivated) {
2497
+ return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
2498
+ }
2499
+
2500
+ function extractUpdateHooks (updated) {
2501
+ return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
2502
+ }
2503
+
2504
+ function bindGuard (guard, instance) {
2505
+ if (instance) {
2506
+ return function boundRouteGuard () {
2507
+ return guard.apply(instance, arguments)
2508
+ }
2509
+ }
2510
+ }
2511
+
2512
+ function extractEnterGuards (
2513
+ activated
2514
+ ) {
2515
+ return extractGuards(
2516
+ activated,
2517
+ 'beforeRouteEnter',
2518
+ function (guard, _, match, key) {
2519
+ return bindEnterGuard(guard, match, key)
2520
+ }
2521
+ )
2522
+ }
2523
+
2524
+ function bindEnterGuard (
2525
+ guard,
2526
+ match,
2527
+ key
2528
+ ) {
2529
+ return function routeEnterGuard (to, from, next) {
2530
+ return guard(to, from, function (cb) {
2531
+ if (typeof cb === 'function') {
2532
+ if (!match.enteredCbs[key]) {
2533
+ match.enteredCbs[key] = [];
2534
+ }
2535
+ match.enteredCbs[key].push(cb);
2536
+ }
2537
+ next(cb);
2538
+ })
2539
+ }
2540
+ }
2541
+
2542
+ /* */
2543
+
2544
+ var HTML5History = /*@__PURE__*/(function (History) {
2545
+ function HTML5History (router, base) {
2546
+ History.call(this, router, base);
2547
+
2548
+ this._startLocation = getLocation(this.base);
2549
+ }
2550
+
2551
+ if ( History ) HTML5History.__proto__ = History;
2552
+ HTML5History.prototype = Object.create( History && History.prototype );
2553
+ HTML5History.prototype.constructor = HTML5History;
2554
+
2555
+ HTML5History.prototype.setupListeners = function setupListeners () {
2556
+ var this$1 = this;
2557
+
2558
+ if (this.listeners.length > 0) {
2559
+ return
2560
+ }
2561
+
2562
+ var router = this.router;
2563
+ var expectScroll = router.options.scrollBehavior;
2564
+ var supportsScroll = supportsPushState && expectScroll;
2565
+
2566
+ if (supportsScroll) {
2567
+ this.listeners.push(setupScroll());
2568
+ }
2569
+
2570
+ var handleRoutingEvent = function () {
2571
+ var current = this$1.current;
2572
+
2573
+ // Avoiding first `popstate` event dispatched in some browsers but first
2574
+ // history route not updated since async guard at the same time.
2575
+ var location = getLocation(this$1.base);
2576
+ if (this$1.current === START && location === this$1._startLocation) {
2577
+ return
2578
+ }
2579
+
2580
+ this$1.transitionTo(location, function (route) {
2581
+ if (supportsScroll) {
2582
+ handleScroll(router, route, current, true);
2583
+ }
2584
+ });
2585
+ };
2586
+ window.addEventListener('popstate', handleRoutingEvent);
2587
+ this.listeners.push(function () {
2588
+ window.removeEventListener('popstate', handleRoutingEvent);
2589
+ });
2590
+ };
2591
+
2592
+ HTML5History.prototype.go = function go (n) {
2593
+ window.history.go(n);
2594
+ };
2595
+
2596
+ HTML5History.prototype.push = function push (location, onComplete, onAbort) {
2597
+ var this$1 = this;
2598
+
2599
+ var ref = this;
2600
+ var fromRoute = ref.current;
2601
+ this.transitionTo(location, function (route) {
2602
+ pushState(cleanPath(this$1.base + route.fullPath));
2603
+ handleScroll(this$1.router, route, fromRoute, false);
2604
+ onComplete && onComplete(route);
2605
+ }, onAbort);
2606
+ };
2607
+
2608
+ HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
2609
+ var this$1 = this;
2610
+
2611
+ var ref = this;
2612
+ var fromRoute = ref.current;
2613
+ this.transitionTo(location, function (route) {
2614
+ replaceState(cleanPath(this$1.base + route.fullPath));
2615
+ handleScroll(this$1.router, route, fromRoute, false);
2616
+ onComplete && onComplete(route);
2617
+ }, onAbort);
2618
+ };
2619
+
2620
+ HTML5History.prototype.ensureURL = function ensureURL (push) {
2621
+ if (getLocation(this.base) !== this.current.fullPath) {
2622
+ var current = cleanPath(this.base + this.current.fullPath);
2623
+ push ? pushState(current) : replaceState(current);
2624
+ }
2625
+ };
2626
+
2627
+ HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
2628
+ return getLocation(this.base)
2629
+ };
2630
+
2631
+ return HTML5History;
2632
+ }(History));
2633
+
2634
+ function getLocation (base) {
2635
+ var path = window.location.pathname;
2636
+ var pathLowerCase = path.toLowerCase();
2637
+ var baseLowerCase = base.toLowerCase();
2638
+ // base="/a" shouldn't turn path="/app" into "/a/pp"
2639
+ // so we ensure the trailing slash in the base
2640
+ if (base && ((pathLowerCase === baseLowerCase) ||
2641
+ (pathLowerCase.indexOf(cleanPath(baseLowerCase + '/')) === 0))) {
2642
+ path = path.slice(base.length);
2643
+ }
2644
+ return (path || '/') + window.location.search + window.location.hash
2645
+ }
2646
+
2647
+ /* */
2648
+
2649
+ var HashHistory = /*@__PURE__*/(function (History) {
2650
+ function HashHistory (router, base, fallback) {
2651
+ History.call(this, router, base);
2652
+ // check history fallback deeplinking
2653
+ if (fallback && checkFallback(this.base)) {
2654
+ return
2655
+ }
2656
+ ensureSlash();
2657
+ }
2658
+
2659
+ if ( History ) HashHistory.__proto__ = History;
2660
+ HashHistory.prototype = Object.create( History && History.prototype );
2661
+ HashHistory.prototype.constructor = HashHistory;
2662
+
2663
+ // this is delayed until the app mounts
2664
+ // to avoid the hashchange listener being fired too early
2665
+ HashHistory.prototype.setupListeners = function setupListeners () {
2666
+ var this$1 = this;
2667
+
2668
+ if (this.listeners.length > 0) {
2669
+ return
2670
+ }
2671
+
2672
+ var router = this.router;
2673
+ var expectScroll = router.options.scrollBehavior;
2674
+ var supportsScroll = supportsPushState && expectScroll;
2675
+
2676
+ if (supportsScroll) {
2677
+ this.listeners.push(setupScroll());
2678
+ }
2679
+
2680
+ var handleRoutingEvent = function () {
2681
+ var current = this$1.current;
2682
+ if (!ensureSlash()) {
2683
+ return
2684
+ }
2685
+ this$1.transitionTo(getHash(), function (route) {
2686
+ if (supportsScroll) {
2687
+ handleScroll(this$1.router, route, current, true);
2688
+ }
2689
+ if (!supportsPushState) {
2690
+ replaceHash(route.fullPath);
2691
+ }
2692
+ });
2693
+ };
2694
+ var eventType = supportsPushState ? 'popstate' : 'hashchange';
2695
+ window.addEventListener(
2696
+ eventType,
2697
+ handleRoutingEvent
2698
+ );
2699
+ this.listeners.push(function () {
2700
+ window.removeEventListener(eventType, handleRoutingEvent);
2701
+ });
2702
+ };
2703
+
2704
+ HashHistory.prototype.push = function push (location, onComplete, onAbort) {
2705
+ var this$1 = this;
2706
+
2707
+ var ref = this;
2708
+ var fromRoute = ref.current;
2709
+ this.transitionTo(
2710
+ location,
2711
+ function (route) {
2712
+ pushHash(route.fullPath);
2713
+ handleScroll(this$1.router, route, fromRoute, false);
2714
+ onComplete && onComplete(route);
2715
+ },
2716
+ onAbort
2717
+ );
2718
+ };
2719
+
2720
+ HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
2721
+ var this$1 = this;
2722
+
2723
+ var ref = this;
2724
+ var fromRoute = ref.current;
2725
+ this.transitionTo(
2726
+ location,
2727
+ function (route) {
2728
+ replaceHash(route.fullPath);
2729
+ handleScroll(this$1.router, route, fromRoute, false);
2730
+ onComplete && onComplete(route);
2731
+ },
2732
+ onAbort
2733
+ );
2734
+ };
2735
+
2736
+ HashHistory.prototype.go = function go (n) {
2737
+ window.history.go(n);
2738
+ };
2739
+
2740
+ HashHistory.prototype.ensureURL = function ensureURL (push) {
2741
+ var current = this.current.fullPath;
2742
+ if (getHash() !== current) {
2743
+ push ? pushHash(current) : replaceHash(current);
2744
+ }
2745
+ };
2746
+
2747
+ HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
2748
+ return getHash()
2749
+ };
2750
+
2751
+ return HashHistory;
2752
+ }(History));
2753
+
2754
+ function checkFallback (base) {
2755
+ var location = getLocation(base);
2756
+ if (!/^\/#/.test(location)) {
2757
+ window.location.replace(cleanPath(base + '/#' + location));
2758
+ return true
2759
+ }
2760
+ }
2761
+
2762
+ function ensureSlash () {
2763
+ var path = getHash();
2764
+ if (path.charAt(0) === '/') {
2765
+ return true
2766
+ }
2767
+ replaceHash('/' + path);
2768
+ return false
2769
+ }
2770
+
2771
+ function getHash () {
2772
+ // We can't use window.location.hash here because it's not
2773
+ // consistent across browsers - Firefox will pre-decode it!
2774
+ var href = window.location.href;
2775
+ var index = href.indexOf('#');
2776
+ // empty path
2777
+ if (index < 0) { return '' }
2778
+
2779
+ href = href.slice(index + 1);
2780
+
2781
+ return href
2782
+ }
2783
+
2784
+ function getUrl (path) {
2785
+ var href = window.location.href;
2786
+ var i = href.indexOf('#');
2787
+ var base = i >= 0 ? href.slice(0, i) : href;
2788
+ return (base + "#" + path)
2789
+ }
2790
+
2791
+ function pushHash (path) {
2792
+ if (supportsPushState) {
2793
+ pushState(getUrl(path));
2794
+ } else {
2795
+ window.location.hash = path;
2796
+ }
2797
+ }
2798
+
2799
+ function replaceHash (path) {
2800
+ if (supportsPushState) {
2801
+ replaceState(getUrl(path));
2802
+ } else {
2803
+ window.location.replace(getUrl(path));
2804
+ }
2805
+ }
2806
+
2807
+ /* */
2808
+
2809
+ var AbstractHistory = /*@__PURE__*/(function (History) {
2810
+ function AbstractHistory (router, base) {
2811
+ History.call(this, router, base);
2812
+ this.stack = [];
2813
+ this.index = -1;
2814
+ }
2815
+
2816
+ if ( History ) AbstractHistory.__proto__ = History;
2817
+ AbstractHistory.prototype = Object.create( History && History.prototype );
2818
+ AbstractHistory.prototype.constructor = AbstractHistory;
2819
+
2820
+ AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
2821
+ var this$1 = this;
2822
+
2823
+ this.transitionTo(
2824
+ location,
2825
+ function (route) {
2826
+ this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
2827
+ this$1.index++;
2828
+ onComplete && onComplete(route);
2829
+ },
2830
+ onAbort
2831
+ );
2832
+ };
2833
+
2834
+ AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
2835
+ var this$1 = this;
2836
+
2837
+ this.transitionTo(
2838
+ location,
2839
+ function (route) {
2840
+ this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
2841
+ onComplete && onComplete(route);
2842
+ },
2843
+ onAbort
2844
+ );
2845
+ };
2846
+
2847
+ AbstractHistory.prototype.go = function go (n) {
2848
+ var this$1 = this;
2849
+
2850
+ var targetIndex = this.index + n;
2851
+ if (targetIndex < 0 || targetIndex >= this.stack.length) {
2852
+ return
2853
+ }
2854
+ var route = this.stack[targetIndex];
2855
+ this.confirmTransition(
2856
+ route,
2857
+ function () {
2858
+ var prev = this$1.current;
2859
+ this$1.index = targetIndex;
2860
+ this$1.updateRoute(route);
2861
+ this$1.router.afterHooks.forEach(function (hook) {
2862
+ hook && hook(route, prev);
2863
+ });
2864
+ },
2865
+ function (err) {
2866
+ if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
2867
+ this$1.index = targetIndex;
2868
+ }
2869
+ }
2870
+ );
2871
+ };
2872
+
2873
+ AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
2874
+ var current = this.stack[this.stack.length - 1];
2875
+ return current ? current.fullPath : '/'
2876
+ };
2877
+
2878
+ AbstractHistory.prototype.ensureURL = function ensureURL () {
2879
+ // noop
2880
+ };
2881
+
2882
+ return AbstractHistory;
2883
+ }(History));
2884
+
2885
+ /* */
2886
+
2887
+
2888
+
2889
+ var KduRouter = function KduRouter (options) {
2890
+ if ( options === void 0 ) options = {};
2891
+
2892
+ if (process.env.NODE_ENV !== 'production') {
2893
+ warn(this instanceof KduRouter, "Router must be called with the new operator.");
2894
+ }
2895
+ this.app = null;
2896
+ this.apps = [];
2897
+ this.options = options;
2898
+ this.beforeHooks = [];
2899
+ this.resolveHooks = [];
2900
+ this.afterHooks = [];
2901
+ this.matcher = createMatcher(options.routes || [], this);
2902
+
2903
+ var mode = options.mode || 'hash';
2904
+ this.fallback =
2905
+ mode === 'history' && !supportsPushState && options.fallback !== false;
2906
+ if (this.fallback) {
2907
+ mode = 'hash';
2908
+ }
2909
+ if (!inBrowser) {
2910
+ mode = 'abstract';
2911
+ }
2912
+ this.mode = mode;
2913
+
2914
+ switch (mode) {
2915
+ case 'history':
2916
+ this.history = new HTML5History(this, options.base);
2917
+ break
2918
+ case 'hash':
2919
+ this.history = new HashHistory(this, options.base, this.fallback);
2920
+ break
2921
+ case 'abstract':
2922
+ this.history = new AbstractHistory(this, options.base);
2923
+ break
2924
+ default:
2925
+ if (process.env.NODE_ENV !== 'production') {
2926
+ assert(false, ("invalid mode: " + mode));
2927
+ }
2928
+ }
2929
+ };
2930
+
2931
+ var prototypeAccessors = { currentRoute: { configurable: true } };
2932
+
2933
+ KduRouter.prototype.match = function match (raw, current, redirectedFrom) {
2934
+ return this.matcher.match(raw, current, redirectedFrom)
2935
+ };
2936
+
2937
+ prototypeAccessors.currentRoute.get = function () {
2938
+ return this.history && this.history.current
2939
+ };
2940
+
2941
+ KduRouter.prototype.init = function init (app /* Kdu component instance */) {
2942
+ var this$1 = this;
2943
+
2944
+ process.env.NODE_ENV !== 'production' &&
2945
+ assert(
2946
+ install.installed,
2947
+ "not installed. Make sure to call `Kdu.use(KduRouter)` " +
2948
+ "before creating root instance."
2949
+ );
2950
+
2951
+ this.apps.push(app);
2952
+
2953
+ // set up app destroyed handler
2954
+ app.$once('hook:destroyed', function () {
2955
+ // clean out app from this.apps array once destroyed
2956
+ var index = this$1.apps.indexOf(app);
2957
+ if (index > -1) { this$1.apps.splice(index, 1); }
2958
+ // ensure we still have a main app or null if no apps
2959
+ // we do not release the router so it can be reused
2960
+ if (this$1.app === app) { this$1.app = this$1.apps[0] || null; }
2961
+
2962
+ if (!this$1.app) { this$1.history.teardown(); }
2963
+ });
2964
+
2965
+ // main app previously initialized
2966
+ // return as we don't need to set up new history listener
2967
+ if (this.app) {
2968
+ return
2969
+ }
2970
+
2971
+ this.app = app;
2972
+
2973
+ var history = this.history;
2974
+
2975
+ if (history instanceof HTML5History || history instanceof HashHistory) {
2976
+ var handleInitialScroll = function (routeOrError) {
2977
+ var from = history.current;
2978
+ var expectScroll = this$1.options.scrollBehavior;
2979
+ var supportsScroll = supportsPushState && expectScroll;
2980
+
2981
+ if (supportsScroll && 'fullPath' in routeOrError) {
2982
+ handleScroll(this$1, routeOrError, from, false);
2983
+ }
2984
+ };
2985
+ var setupListeners = function (routeOrError) {
2986
+ history.setupListeners();
2987
+ handleInitialScroll(routeOrError);
2988
+ };
2989
+ history.transitionTo(
2990
+ history.getCurrentLocation(),
2991
+ setupListeners,
2992
+ setupListeners
2993
+ );
2994
+ }
2995
+
2996
+ history.listen(function (route) {
2997
+ this$1.apps.forEach(function (app) {
2998
+ app._route = route;
2999
+ });
3000
+ });
3001
+ };
3002
+
3003
+ KduRouter.prototype.beforeEach = function beforeEach (fn) {
3004
+ return registerHook(this.beforeHooks, fn)
3005
+ };
3006
+
3007
+ KduRouter.prototype.beforeResolve = function beforeResolve (fn) {
3008
+ return registerHook(this.resolveHooks, fn)
3009
+ };
3010
+
3011
+ KduRouter.prototype.afterEach = function afterEach (fn) {
3012
+ return registerHook(this.afterHooks, fn)
3013
+ };
3014
+
3015
+ KduRouter.prototype.onReady = function onReady (cb, errorCb) {
3016
+ this.history.onReady(cb, errorCb);
3017
+ };
3018
+
3019
+ KduRouter.prototype.onError = function onError (errorCb) {
3020
+ this.history.onError(errorCb);
3021
+ };
3022
+
3023
+ KduRouter.prototype.push = function push (location, onComplete, onAbort) {
3024
+ var this$1 = this;
3025
+
3026
+ // $flow-disable-line
3027
+ if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
3028
+ return new Promise(function (resolve, reject) {
3029
+ this$1.history.push(location, resolve, reject);
3030
+ })
3031
+ } else {
3032
+ this.history.push(location, onComplete, onAbort);
3033
+ }
3034
+ };
3035
+
3036
+ KduRouter.prototype.replace = function replace (location, onComplete, onAbort) {
3037
+ var this$1 = this;
3038
+
3039
+ // $flow-disable-line
3040
+ if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
3041
+ return new Promise(function (resolve, reject) {
3042
+ this$1.history.replace(location, resolve, reject);
3043
+ })
3044
+ } else {
3045
+ this.history.replace(location, onComplete, onAbort);
3046
+ }
3047
+ };
3048
+
3049
+ KduRouter.prototype.go = function go (n) {
3050
+ this.history.go(n);
3051
+ };
3052
+
3053
+ KduRouter.prototype.back = function back () {
3054
+ this.go(-1);
3055
+ };
3056
+
3057
+ KduRouter.prototype.forward = function forward () {
3058
+ this.go(1);
3059
+ };
3060
+
3061
+ KduRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
3062
+ var route = to
3063
+ ? to.matched
3064
+ ? to
3065
+ : this.resolve(to).route
3066
+ : this.currentRoute;
3067
+ if (!route) {
3068
+ return []
3069
+ }
3070
+ return [].concat.apply(
3071
+ [],
3072
+ route.matched.map(function (m) {
3073
+ return Object.keys(m.components).map(function (key) {
3074
+ return m.components[key]
3075
+ })
3076
+ })
3077
+ )
3078
+ };
3079
+
3080
+ KduRouter.prototype.resolve = function resolve (
3081
+ to,
3082
+ current,
3083
+ append
3084
+ ) {
3085
+ current = current || this.history.current;
3086
+ var location = normalizeLocation(to, current, append, this);
3087
+ var route = this.match(location, current);
3088
+ var fullPath = route.redirectedFrom || route.fullPath;
3089
+ var base = this.history.base;
3090
+ var href = createHref(base, fullPath, this.mode);
3091
+ return {
3092
+ location: location,
3093
+ route: route,
3094
+ href: href,
3095
+ // for backwards compat
3096
+ normalizedTo: location,
3097
+ resolved: route
3098
+ }
3099
+ };
3100
+
3101
+ KduRouter.prototype.getRoutes = function getRoutes () {
3102
+ return this.matcher.getRoutes()
3103
+ };
3104
+
3105
+ KduRouter.prototype.addRoute = function addRoute (parentOrRoute, route) {
3106
+ this.matcher.addRoute(parentOrRoute, route);
3107
+ if (this.history.current !== START) {
3108
+ this.history.transitionTo(this.history.getCurrentLocation());
3109
+ }
3110
+ };
3111
+
3112
+ KduRouter.prototype.addRoutes = function addRoutes (routes) {
3113
+ if (process.env.NODE_ENV !== 'production') {
3114
+ warn(false, 'router.addRoutes() is deprecated and has been removed in Kdu Router 4. Use router.addRoute() instead.');
3115
+ }
3116
+ this.matcher.addRoutes(routes);
3117
+ if (this.history.current !== START) {
3118
+ this.history.transitionTo(this.history.getCurrentLocation());
3119
+ }
3120
+ };
3121
+
3122
+ Object.defineProperties( KduRouter.prototype, prototypeAccessors );
3123
+
3124
+ function registerHook (list, fn) {
3125
+ list.push(fn);
3126
+ return function () {
3127
+ var i = list.indexOf(fn);
3128
+ if (i > -1) { list.splice(i, 1); }
3129
+ }
3130
+ }
3131
+
3132
+ function createHref (base, fullPath, mode) {
3133
+ var path = mode === 'hash' ? '#' + fullPath : fullPath;
3134
+ return base ? cleanPath(base + '/' + path) : path
3135
+ }
3136
+
3137
+ // We cannot remove this as it would be a breaking change
3138
+ KduRouter.install = install;
3139
+ KduRouter.version = '3.6.2';
3140
+ KduRouter.isNavigationFailure = isNavigationFailure;
3141
+ KduRouter.NavigationFailureType = NavigationFailureType;
3142
+ KduRouter.START_LOCATION = START;
3143
+
3144
+ if (inBrowser && window.Kdu) {
3145
+ window.Kdu.use(KduRouter);
3146
+ }
3147
+
3148
+ var version = '3.6.2';
3149
+
3150
+ export default KduRouter;
3151
+ export { NavigationFailureType, Link as RouterLink, View as RouterView, START as START_LOCATION, isNavigationFailure, version };