@shijiu/jsview 2.3.151-test.0 → 3.0.0-next-vue.0

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