vue-router.js 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539
  1. import {
  2. computed,
  3. defineComponent,
  4. getCurrentInstance,
  5. h,
  6. inject,
  7. nextTick,
  8. onActivated,
  9. onDeactivated,
  10. onUnmounted,
  11. provide,
  12. reactive,
  13. ref,
  14. shallowRef,
  15. unref,
  16. watch,
  17. watchEffect
  18. } from "./chunk-ZUXVXN6F.js";
  19. import "./chunk-A5ICIBVI.js";
  20. // node_modules/@vue/devtools-api/lib/esm/env.js
  21. function getDevtoolsGlobalHook() {
  22. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  23. }
  24. function getTarget() {
  25. return typeof navigator !== "undefined" && typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
  26. }
  27. var isProxyAvailable = typeof Proxy === "function";
  28. // node_modules/@vue/devtools-api/lib/esm/const.js
  29. var HOOK_SETUP = "devtools-plugin:setup";
  30. var HOOK_PLUGIN_SETTINGS_SET = "plugin:settings:set";
  31. // node_modules/@vue/devtools-api/lib/esm/time.js
  32. var supported;
  33. var perf;
  34. function isPerformanceSupported() {
  35. var _a;
  36. if (supported !== void 0) {
  37. return supported;
  38. }
  39. if (typeof window !== "undefined" && window.performance) {
  40. supported = true;
  41. perf = window.performance;
  42. } else if (typeof global !== "undefined" && ((_a = global.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
  43. supported = true;
  44. perf = global.perf_hooks.performance;
  45. } else {
  46. supported = false;
  47. }
  48. return supported;
  49. }
  50. function now() {
  51. return isPerformanceSupported() ? perf.now() : Date.now();
  52. }
  53. // node_modules/@vue/devtools-api/lib/esm/proxy.js
  54. var ApiProxy = class {
  55. constructor(plugin, hook) {
  56. this.target = null;
  57. this.targetQueue = [];
  58. this.onQueue = [];
  59. this.plugin = plugin;
  60. this.hook = hook;
  61. const defaultSettings = {};
  62. if (plugin.settings) {
  63. for (const id in plugin.settings) {
  64. const item = plugin.settings[id];
  65. defaultSettings[id] = item.defaultValue;
  66. }
  67. }
  68. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  69. let currentSettings = Object.assign({}, defaultSettings);
  70. try {
  71. const raw = localStorage.getItem(localSettingsSaveId);
  72. const data = JSON.parse(raw);
  73. Object.assign(currentSettings, data);
  74. } catch (e) {
  75. }
  76. this.fallbacks = {
  77. getSettings() {
  78. return currentSettings;
  79. },
  80. setSettings(value) {
  81. try {
  82. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  83. } catch (e) {
  84. }
  85. currentSettings = value;
  86. },
  87. now() {
  88. return now();
  89. }
  90. };
  91. if (hook) {
  92. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  93. if (pluginId === this.plugin.id) {
  94. this.fallbacks.setSettings(value);
  95. }
  96. });
  97. }
  98. this.proxiedOn = new Proxy({}, {
  99. get: (_target, prop) => {
  100. if (this.target) {
  101. return this.target.on[prop];
  102. } else {
  103. return (...args) => {
  104. this.onQueue.push({
  105. method: prop,
  106. args
  107. });
  108. };
  109. }
  110. }
  111. });
  112. this.proxiedTarget = new Proxy({}, {
  113. get: (_target, prop) => {
  114. if (this.target) {
  115. return this.target[prop];
  116. } else if (prop === "on") {
  117. return this.proxiedOn;
  118. } else if (Object.keys(this.fallbacks).includes(prop)) {
  119. return (...args) => {
  120. this.targetQueue.push({
  121. method: prop,
  122. args,
  123. resolve: () => {
  124. }
  125. });
  126. return this.fallbacks[prop](...args);
  127. };
  128. } else {
  129. return (...args) => {
  130. return new Promise((resolve) => {
  131. this.targetQueue.push({
  132. method: prop,
  133. args,
  134. resolve
  135. });
  136. });
  137. };
  138. }
  139. }
  140. });
  141. }
  142. async setRealTarget(target) {
  143. this.target = target;
  144. for (const item of this.onQueue) {
  145. this.target.on[item.method](...item.args);
  146. }
  147. for (const item of this.targetQueue) {
  148. item.resolve(await this.target[item.method](...item.args));
  149. }
  150. }
  151. };
  152. // node_modules/@vue/devtools-api/lib/esm/index.js
  153. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  154. const descriptor = pluginDescriptor;
  155. const target = getTarget();
  156. const hook = getDevtoolsGlobalHook();
  157. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  158. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  159. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  160. } else {
  161. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  162. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  163. list.push({
  164. pluginDescriptor: descriptor,
  165. setupFn,
  166. proxy
  167. });
  168. if (proxy)
  169. setupFn(proxy.proxiedTarget);
  170. }
  171. }
  172. // node_modules/vue-router/dist/vue-router.esm-bundler.js
  173. var hasSymbol = typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol";
  174. var PolySymbol = (name) => hasSymbol ? Symbol(true ? "[vue-router]: " + name : name) : (true ? "[vue-router]: " : "_vr_") + name;
  175. var matchedRouteKey = PolySymbol(true ? "router view location matched" : "rvlm");
  176. var viewDepthKey = PolySymbol(true ? "router view depth" : "rvd");
  177. var routerKey = PolySymbol(true ? "router" : "r");
  178. var routeLocationKey = PolySymbol(true ? "route location" : "rl");
  179. var routerViewLocationKey = PolySymbol(true ? "router view location" : "rvl");
  180. var isBrowser = typeof window !== "undefined";
  181. function isESModule(obj) {
  182. return obj.__esModule || hasSymbol && obj[Symbol.toStringTag] === "Module";
  183. }
  184. var assign = Object.assign;
  185. function applyToParams(fn, params) {
  186. const newParams = {};
  187. for (const key in params) {
  188. const value = params[key];
  189. newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value);
  190. }
  191. return newParams;
  192. }
  193. var noop = () => {
  194. };
  195. function warn(msg) {
  196. const args = Array.from(arguments).slice(1);
  197. console.warn.apply(console, ["[Vue Router warn]: " + msg].concat(args));
  198. }
  199. var TRAILING_SLASH_RE = /\/$/;
  200. var removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, "");
  201. function parseURL(parseQuery2, location2, currentLocation = "/") {
  202. let path, query = {}, searchString = "", hash = "";
  203. const searchPos = location2.indexOf("?");
  204. const hashPos = location2.indexOf("#", searchPos > -1 ? searchPos : 0);
  205. if (searchPos > -1) {
  206. path = location2.slice(0, searchPos);
  207. searchString = location2.slice(searchPos + 1, hashPos > -1 ? hashPos : location2.length);
  208. query = parseQuery2(searchString);
  209. }
  210. if (hashPos > -1) {
  211. path = path || location2.slice(0, hashPos);
  212. hash = location2.slice(hashPos, location2.length);
  213. }
  214. path = resolveRelativePath(path != null ? path : location2, currentLocation);
  215. return {
  216. fullPath: path + (searchString && "?") + searchString + hash,
  217. path,
  218. query,
  219. hash
  220. };
  221. }
  222. function stringifyURL(stringifyQuery2, location2) {
  223. const query = location2.query ? stringifyQuery2(location2.query) : "";
  224. return location2.path + (query && "?") + query + (location2.hash || "");
  225. }
  226. function stripBase(pathname, base) {
  227. if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase()))
  228. return pathname;
  229. return pathname.slice(base.length) || "/";
  230. }
  231. function isSameRouteLocation(stringifyQuery2, a, b) {
  232. const aLastIndex = a.matched.length - 1;
  233. const bLastIndex = b.matched.length - 1;
  234. return aLastIndex > -1 && aLastIndex === bLastIndex && isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && isSameRouteLocationParams(a.params, b.params) && stringifyQuery2(a.query) === stringifyQuery2(b.query) && a.hash === b.hash;
  235. }
  236. function isSameRouteRecord(a, b) {
  237. return (a.aliasOf || a) === (b.aliasOf || b);
  238. }
  239. function isSameRouteLocationParams(a, b) {
  240. if (Object.keys(a).length !== Object.keys(b).length)
  241. return false;
  242. for (const key in a) {
  243. if (!isSameRouteLocationParamsValue(a[key], b[key]))
  244. return false;
  245. }
  246. return true;
  247. }
  248. function isSameRouteLocationParamsValue(a, b) {
  249. return Array.isArray(a) ? isEquivalentArray(a, b) : Array.isArray(b) ? isEquivalentArray(b, a) : a === b;
  250. }
  251. function isEquivalentArray(a, b) {
  252. return Array.isArray(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b;
  253. }
  254. function resolveRelativePath(to, from) {
  255. if (to.startsWith("/"))
  256. return to;
  257. if (!from.startsWith("/")) {
  258. warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
  259. return to;
  260. }
  261. if (!to)
  262. return from;
  263. const fromSegments = from.split("/");
  264. const toSegments = to.split("/");
  265. let position = fromSegments.length - 1;
  266. let toPosition;
  267. let segment;
  268. for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
  269. segment = toSegments[toPosition];
  270. if (position === 1 || segment === ".")
  271. continue;
  272. if (segment === "..")
  273. position--;
  274. else
  275. break;
  276. }
  277. return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(toPosition - (toPosition === toSegments.length ? 1 : 0)).join("/");
  278. }
  279. var NavigationType;
  280. (function(NavigationType2) {
  281. NavigationType2["pop"] = "pop";
  282. NavigationType2["push"] = "push";
  283. })(NavigationType || (NavigationType = {}));
  284. var NavigationDirection;
  285. (function(NavigationDirection2) {
  286. NavigationDirection2["back"] = "back";
  287. NavigationDirection2["forward"] = "forward";
  288. NavigationDirection2["unknown"] = "";
  289. })(NavigationDirection || (NavigationDirection = {}));
  290. var START = "";
  291. function normalizeBase(base) {
  292. if (!base) {
  293. if (isBrowser) {
  294. const baseEl = document.querySelector("base");
  295. base = baseEl && baseEl.getAttribute("href") || "/";
  296. base = base.replace(/^\w+:\/\/[^\/]+/, "");
  297. } else {
  298. base = "/";
  299. }
  300. }
  301. if (base[0] !== "/" && base[0] !== "#")
  302. base = "/" + base;
  303. return removeTrailingSlash(base);
  304. }
  305. var BEFORE_HASH_RE = /^[^#]+#/;
  306. function createHref(base, location2) {
  307. return base.replace(BEFORE_HASH_RE, "#") + location2;
  308. }
  309. function getElementPosition(el, offset) {
  310. const docRect = document.documentElement.getBoundingClientRect();
  311. const elRect = el.getBoundingClientRect();
  312. return {
  313. behavior: offset.behavior,
  314. left: elRect.left - docRect.left - (offset.left || 0),
  315. top: elRect.top - docRect.top - (offset.top || 0)
  316. };
  317. }
  318. var computeScrollPosition = () => ({
  319. left: window.pageXOffset,
  320. top: window.pageYOffset
  321. });
  322. function scrollToPosition(position) {
  323. let scrollToOptions;
  324. if ("el" in position) {
  325. const positionEl = position.el;
  326. const isIdSelector = typeof positionEl === "string" && positionEl.startsWith("#");
  327. if (typeof position.el === "string") {
  328. if (!isIdSelector || !document.getElementById(position.el.slice(1))) {
  329. try {
  330. const foundEl = document.querySelector(position.el);
  331. if (isIdSelector && foundEl) {
  332. warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
  333. return;
  334. }
  335. } catch (err) {
  336. 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).`);
  337. return;
  338. }
  339. }
  340. }
  341. const el = typeof positionEl === "string" ? isIdSelector ? document.getElementById(positionEl.slice(1)) : document.querySelector(positionEl) : positionEl;
  342. if (!el) {
  343. warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`);
  344. return;
  345. }
  346. scrollToOptions = getElementPosition(el, position);
  347. } else {
  348. scrollToOptions = position;
  349. }
  350. if ("scrollBehavior" in document.documentElement.style)
  351. window.scrollTo(scrollToOptions);
  352. else {
  353. window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset);
  354. }
  355. }
  356. function getScrollKey(path, delta) {
  357. const position = history.state ? history.state.position - delta : -1;
  358. return position + path;
  359. }
  360. var scrollPositions = new Map();
  361. function saveScrollPosition(key, scrollPosition) {
  362. scrollPositions.set(key, scrollPosition);
  363. }
  364. function getSavedScrollPosition(key) {
  365. const scroll = scrollPositions.get(key);
  366. scrollPositions.delete(key);
  367. return scroll;
  368. }
  369. var createBaseLocation = () => location.protocol + "//" + location.host;
  370. function createCurrentLocation(base, location2) {
  371. const { pathname, search, hash } = location2;
  372. const hashPos = base.indexOf("#");
  373. if (hashPos > -1) {
  374. let slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1;
  375. let pathFromHash = hash.slice(slicePos);
  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. let pauseState = null;
  387. const popStateHandler = ({ state }) => {
  388. const to = createCurrentLocation(base, location);
  389. const from = currentLocation.value;
  390. const fromState = historyState.value;
  391. let delta = 0;
  392. if (state) {
  393. currentLocation.value = to;
  394. historyState.value = state;
  395. if (pauseState && pauseState === from) {
  396. pauseState = null;
  397. return;
  398. }
  399. delta = fromState ? state.position - fromState.position : 0;
  400. } else {
  401. replace(to);
  402. }
  403. listeners.forEach((listener) => {
  404. listener(currentLocation.value, from, {
  405. delta,
  406. type: NavigationType.pop,
  407. direction: delta ? delta > 0 ? NavigationDirection.forward : NavigationDirection.back : NavigationDirection.unknown
  408. });
  409. });
  410. };
  411. function pauseListeners() {
  412. pauseState = currentLocation.value;
  413. }
  414. function listen(callback) {
  415. listeners.push(callback);
  416. const teardown = () => {
  417. const index = listeners.indexOf(callback);
  418. if (index > -1)
  419. listeners.splice(index, 1);
  420. };
  421. teardowns.push(teardown);
  422. return teardown;
  423. }
  424. function beforeUnloadListener() {
  425. const { history: history2 } = window;
  426. if (!history2.state)
  427. return;
  428. history2.replaceState(assign({}, history2.state, { scroll: computeScrollPosition() }), "");
  429. }
  430. function destroy() {
  431. for (const teardown of teardowns)
  432. teardown();
  433. teardowns = [];
  434. window.removeEventListener("popstate", popStateHandler);
  435. window.removeEventListener("beforeunload", beforeUnloadListener);
  436. }
  437. window.addEventListener("popstate", popStateHandler);
  438. window.addEventListener("beforeunload", beforeUnloadListener);
  439. return {
  440. pauseListeners,
  441. listen,
  442. destroy
  443. };
  444. }
  445. function buildState(back, current, forward, replaced = false, computeScroll = false) {
  446. return {
  447. back,
  448. current,
  449. forward,
  450. replaced,
  451. position: window.history.length,
  452. scroll: computeScroll ? computeScrollPosition() : null
  453. };
  454. }
  455. function useHistoryStateNavigation(base) {
  456. const { history: history2, location: location2 } = window;
  457. const currentLocation = {
  458. value: createCurrentLocation(base, location2)
  459. };
  460. const historyState = { value: history2.state };
  461. if (!historyState.value) {
  462. changeLocation(currentLocation.value, {
  463. back: null,
  464. current: currentLocation.value,
  465. forward: null,
  466. position: history2.length - 1,
  467. replaced: true,
  468. scroll: null
  469. }, true);
  470. }
  471. function changeLocation(to, state, replace2) {
  472. const hashIndex = base.indexOf("#");
  473. const url = hashIndex > -1 ? (location2.host && document.querySelector("base") ? base : base.slice(hashIndex)) + to : createBaseLocation() + base + to;
  474. try {
  475. history2[replace2 ? "replaceState" : "pushState"](state, "", url);
  476. historyState.value = state;
  477. } catch (err) {
  478. if (true) {
  479. warn("Error with push/replace State", err);
  480. } else {
  481. console.error(err);
  482. }
  483. location2[replace2 ? "replace" : "assign"](url);
  484. }
  485. }
  486. function replace(to, data) {
  487. const state = assign({}, history2.state, buildState(historyState.value.back, to, historyState.value.forward, true), data, { position: historyState.value.position });
  488. changeLocation(to, state, true);
  489. currentLocation.value = to;
  490. }
  491. function push(to, data) {
  492. const currentState = assign({}, historyState.value, history2.state, {
  493. forward: to,
  494. scroll: computeScrollPosition()
  495. });
  496. if (!history2.state) {
  497. 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:
  498. history.replaceState(history.state, '', url)
  499. You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.`);
  500. }
  501. changeLocation(currentState.current, currentState, true);
  502. const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data);
  503. changeLocation(to, state, false);
  504. currentLocation.value = to;
  505. }
  506. return {
  507. location: currentLocation,
  508. state: historyState,
  509. push,
  510. replace
  511. };
  512. }
  513. function createWebHistory(base) {
  514. base = normalizeBase(base);
  515. const historyNavigation = useHistoryStateNavigation(base);
  516. const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
  517. function go(delta, triggerListeners = true) {
  518. if (!triggerListeners)
  519. historyListeners.pauseListeners();
  520. history.go(delta);
  521. }
  522. const routerHistory = assign({
  523. location: "",
  524. base,
  525. go,
  526. createHref: createHref.bind(null, base)
  527. }, historyNavigation, historyListeners);
  528. Object.defineProperty(routerHistory, "location", {
  529. enumerable: true,
  530. get: () => historyNavigation.location.value
  531. });
  532. Object.defineProperty(routerHistory, "state", {
  533. enumerable: true,
  534. get: () => historyNavigation.state.value
  535. });
  536. return routerHistory;
  537. }
  538. function createMemoryHistory(base = "") {
  539. let listeners = [];
  540. let queue = [START];
  541. let position = 0;
  542. base = normalizeBase(base);
  543. function setLocation(location2) {
  544. position++;
  545. if (position === queue.length) {
  546. queue.push(location2);
  547. } else {
  548. queue.splice(position);
  549. queue.push(location2);
  550. }
  551. }
  552. function triggerListeners(to, from, { direction, delta }) {
  553. const info = {
  554. direction,
  555. delta,
  556. type: NavigationType.pop
  557. };
  558. for (const callback of listeners) {
  559. callback(to, from, info);
  560. }
  561. }
  562. const routerHistory = {
  563. location: START,
  564. state: {},
  565. base,
  566. createHref: createHref.bind(null, base),
  567. replace(to) {
  568. queue.splice(position--, 1);
  569. setLocation(to);
  570. },
  571. push(to, data) {
  572. setLocation(to);
  573. },
  574. listen(callback) {
  575. listeners.push(callback);
  576. return () => {
  577. const index = listeners.indexOf(callback);
  578. if (index > -1)
  579. listeners.splice(index, 1);
  580. };
  581. },
  582. destroy() {
  583. listeners = [];
  584. queue = [START];
  585. position = 0;
  586. },
  587. go(delta, shouldTrigger = true) {
  588. const from = this.location;
  589. const direction = delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
  590. position = Math.max(0, Math.min(position + delta, queue.length - 1));
  591. if (shouldTrigger) {
  592. triggerListeners(this.location, from, {
  593. direction,
  594. delta
  595. });
  596. }
  597. }
  598. };
  599. Object.defineProperty(routerHistory, "location", {
  600. enumerable: true,
  601. get: () => queue[position]
  602. });
  603. return routerHistory;
  604. }
  605. function createWebHashHistory(base) {
  606. base = location.host ? base || location.pathname + location.search : "";
  607. if (!base.includes("#"))
  608. base += "#";
  609. if (!base.endsWith("#/") && !base.endsWith("#")) {
  610. warn(`A hash base must end with a "#":
  611. "${base}" should be "${base.replace(/#.*$/, "#")}".`);
  612. }
  613. return createWebHistory(base);
  614. }
  615. function isRouteLocation(route) {
  616. return typeof route === "string" || route && typeof route === "object";
  617. }
  618. function isRouteName(name) {
  619. return typeof name === "string" || typeof name === "symbol";
  620. }
  621. var START_LOCATION_NORMALIZED = {
  622. path: "/",
  623. name: void 0,
  624. params: {},
  625. query: {},
  626. hash: "",
  627. fullPath: "/",
  628. matched: [],
  629. meta: {},
  630. redirectedFrom: void 0
  631. };
  632. var NavigationFailureSymbol = PolySymbol(true ? "navigation failure" : "nf");
  633. var NavigationFailureType;
  634. (function(NavigationFailureType2) {
  635. NavigationFailureType2[NavigationFailureType2["aborted"] = 4] = "aborted";
  636. NavigationFailureType2[NavigationFailureType2["cancelled"] = 8] = "cancelled";
  637. NavigationFailureType2[NavigationFailureType2["duplicated"] = 16] = "duplicated";
  638. })(NavigationFailureType || (NavigationFailureType = {}));
  639. var ErrorTypeMessages = {
  640. [1]({ location: location2, currentLocation }) {
  641. return `No match for
  642. ${JSON.stringify(location2)}${currentLocation ? "\nwhile being at\n" + JSON.stringify(currentLocation) : ""}`;
  643. },
  644. [2]({ from, to }) {
  645. return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
  646. },
  647. [4]({ from, to }) {
  648. return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
  649. },
  650. [8]({ from, to }) {
  651. return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
  652. },
  653. [16]({ from, to }) {
  654. return `Avoided redundant navigation to current location: "${from.fullPath}".`;
  655. }
  656. };
  657. function createRouterError(type, params) {
  658. if (true) {
  659. return assign(new Error(ErrorTypeMessages[type](params)), {
  660. type,
  661. [NavigationFailureSymbol]: true
  662. }, params);
  663. } else {
  664. return assign(new Error(), {
  665. type,
  666. [NavigationFailureSymbol]: true
  667. }, params);
  668. }
  669. }
  670. function isNavigationFailure(error, type) {
  671. return error instanceof Error && NavigationFailureSymbol in error && (type == null || !!(error.type & type));
  672. }
  673. var propertiesToLog = ["params", "query", "hash"];
  674. function stringifyRoute(to) {
  675. if (typeof to === "string")
  676. return to;
  677. if ("path" in to)
  678. return to.path;
  679. const location2 = {};
  680. for (const key of propertiesToLog) {
  681. if (key in to)
  682. location2[key] = to[key];
  683. }
  684. return JSON.stringify(location2, null, 2);
  685. }
  686. var BASE_PARAM_PATTERN = "[^/]+?";
  687. var BASE_PATH_PARSER_OPTIONS = {
  688. sensitive: false,
  689. strict: false,
  690. start: true,
  691. end: true
  692. };
  693. var REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
  694. function tokensToParser(segments, extraOptions) {
  695. const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
  696. const score = [];
  697. let pattern = options.start ? "^" : "";
  698. const keys = [];
  699. for (const segment of segments) {
  700. const segmentScores = segment.length ? [] : [90];
  701. if (options.strict && !segment.length)
  702. pattern += "/";
  703. for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
  704. const token = segment[tokenIndex];
  705. let subSegmentScore = 40 + (options.sensitive ? 0.25 : 0);
  706. if (token.type === 0) {
  707. if (!tokenIndex)
  708. pattern += "/";
  709. pattern += token.value.replace(REGEX_CHARS_RE, "\\$&");
  710. subSegmentScore += 40;
  711. } else if (token.type === 1) {
  712. const { value, repeatable, optional, regexp } = token;
  713. keys.push({
  714. name: value,
  715. repeatable,
  716. optional
  717. });
  718. const re2 = regexp ? regexp : BASE_PARAM_PATTERN;
  719. if (re2 !== BASE_PARAM_PATTERN) {
  720. subSegmentScore += 10;
  721. try {
  722. new RegExp(`(${re2})`);
  723. } catch (err) {
  724. throw new Error(`Invalid custom RegExp for param "${value}" (${re2}): ` + err.message);
  725. }
  726. }
  727. let subPattern = repeatable ? `((?:${re2})(?:/(?:${re2}))*)` : `(${re2})`;
  728. if (!tokenIndex)
  729. subPattern = optional && segment.length < 2 ? `(?:/${subPattern})` : "/" + subPattern;
  730. if (optional)
  731. subPattern += "?";
  732. pattern += subPattern;
  733. subSegmentScore += 20;
  734. if (optional)
  735. subSegmentScore += -8;
  736. if (repeatable)
  737. subSegmentScore += -20;
  738. if (re2 === ".*")
  739. subSegmentScore += -50;
  740. }
  741. segmentScores.push(subSegmentScore);
  742. }
  743. score.push(segmentScores);
  744. }
  745. if (options.strict && options.end) {
  746. const i = score.length - 1;
  747. score[i][score[i].length - 1] += 0.7000000000000001;
  748. }
  749. if (!options.strict)
  750. pattern += "/?";
  751. if (options.end)
  752. pattern += "$";
  753. else if (options.strict)
  754. pattern += "(?:/|$)";
  755. const re = new RegExp(pattern, options.sensitive ? "" : "i");
  756. function parse(path) {
  757. const match = path.match(re);
  758. const params = {};
  759. if (!match)
  760. return null;
  761. for (let i = 1; i < match.length; i++) {
  762. const value = match[i] || "";
  763. const key = keys[i - 1];
  764. params[key.name] = value && key.repeatable ? value.split("/") : value;
  765. }
  766. return params;
  767. }
  768. function stringify(params) {
  769. let path = "";
  770. let avoidDuplicatedSlash = false;
  771. for (const segment of segments) {
  772. if (!avoidDuplicatedSlash || !path.endsWith("/"))
  773. path += "/";
  774. avoidDuplicatedSlash = false;
  775. for (const token of segment) {
  776. if (token.type === 0) {
  777. path += token.value;
  778. } else if (token.type === 1) {
  779. const { value, repeatable, optional } = token;
  780. const param = value in params ? params[value] : "";
  781. if (Array.isArray(param) && !repeatable)
  782. throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
  783. const text = Array.isArray(param) ? param.join("/") : param;
  784. if (!text) {
  785. if (optional) {
  786. if (segment.length < 2 && segments.length > 1) {
  787. if (path.endsWith("/"))
  788. path = path.slice(0, -1);
  789. else
  790. avoidDuplicatedSlash = true;
  791. }
  792. } else
  793. throw new Error(`Missing required param "${value}"`);
  794. }
  795. path += text;
  796. }
  797. }
  798. }
  799. return path;
  800. }
  801. return {
  802. re,
  803. score,
  804. keys,
  805. parse,
  806. stringify
  807. };
  808. }
  809. function compareScoreArray(a, b) {
  810. let i = 0;
  811. while (i < a.length && i < b.length) {
  812. const diff = b[i] - a[i];
  813. if (diff)
  814. return diff;
  815. i++;
  816. }
  817. if (a.length < b.length) {
  818. return a.length === 1 && a[0] === 40 + 40 ? -1 : 1;
  819. } else if (a.length > b.length) {
  820. return b.length === 1 && b[0] === 40 + 40 ? 1 : -1;
  821. }
  822. return 0;
  823. }
  824. function comparePathParserScore(a, b) {
  825. let i = 0;
  826. const aScore = a.score;
  827. const bScore = b.score;
  828. while (i < aScore.length && i < bScore.length) {
  829. const comp = compareScoreArray(aScore[i], bScore[i]);
  830. if (comp)
  831. return comp;
  832. i++;
  833. }
  834. if (Math.abs(bScore.length - aScore.length) === 1) {
  835. if (isLastScoreNegative(aScore))
  836. return 1;
  837. if (isLastScoreNegative(bScore))
  838. return -1;
  839. }
  840. return bScore.length - aScore.length;
  841. }
  842. function isLastScoreNegative(score) {
  843. const last = score[score.length - 1];
  844. return score.length > 0 && last[last.length - 1] < 0;
  845. }
  846. var ROOT_TOKEN = {
  847. type: 0,
  848. value: ""
  849. };
  850. var VALID_PARAM_RE = /[a-zA-Z0-9_]/;
  851. function tokenizePath(path) {
  852. if (!path)
  853. return [[]];
  854. if (path === "/")
  855. return [[ROOT_TOKEN]];
  856. if (!path.startsWith("/")) {
  857. throw new Error(true ? `Route paths should start with a "/": "${path}" should be "/${path}".` : `Invalid path "${path}"`);
  858. }
  859. function crash(message) {
  860. throw new Error(`ERR (${state})/"${buffer}": ${message}`);
  861. }
  862. let state = 0;
  863. let previousState = state;
  864. const tokens = [];
  865. let segment;
  866. function finalizeSegment() {
  867. if (segment)
  868. tokens.push(segment);
  869. segment = [];
  870. }
  871. let i = 0;
  872. let char;
  873. let buffer = "";
  874. let customRe = "";
  875. function consumeBuffer() {
  876. if (!buffer)
  877. return;
  878. if (state === 0) {
  879. segment.push({
  880. type: 0,
  881. value: buffer
  882. });
  883. } else if (state === 1 || state === 2 || state === 3) {
  884. if (segment.length > 1 && (char === "*" || char === "+"))
  885. crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
  886. segment.push({
  887. type: 1,
  888. value: buffer,
  889. regexp: customRe,
  890. repeatable: char === "*" || char === "+",
  891. optional: char === "*" || char === "?"
  892. });
  893. } else {
  894. crash("Invalid state to consume buffer");
  895. }
  896. buffer = "";
  897. }
  898. function addCharToBuffer() {
  899. buffer += char;
  900. }
  901. while (i < path.length) {
  902. char = path[i++];
  903. if (char === "\\" && state !== 2) {
  904. previousState = state;
  905. state = 4;
  906. continue;
  907. }
  908. switch (state) {
  909. case 0:
  910. if (char === "/") {
  911. if (buffer) {
  912. consumeBuffer();
  913. }
  914. finalizeSegment();
  915. } else if (char === ":") {
  916. consumeBuffer();
  917. state = 1;
  918. } else {
  919. addCharToBuffer();
  920. }
  921. break;
  922. case 4:
  923. addCharToBuffer();
  924. state = previousState;
  925. break;
  926. case 1:
  927. if (char === "(") {
  928. state = 2;
  929. } else if (VALID_PARAM_RE.test(char)) {
  930. addCharToBuffer();
  931. } else {
  932. consumeBuffer();
  933. state = 0;
  934. if (char !== "*" && char !== "?" && char !== "+")
  935. i--;
  936. }
  937. break;
  938. case 2:
  939. if (char === ")") {
  940. if (customRe[customRe.length - 1] == "\\")
  941. customRe = customRe.slice(0, -1) + char;
  942. else
  943. state = 3;
  944. } else {
  945. customRe += char;
  946. }
  947. break;
  948. case 3:
  949. consumeBuffer();
  950. state = 0;
  951. if (char !== "*" && char !== "?" && char !== "+")
  952. i--;
  953. customRe = "";
  954. break;
  955. default:
  956. crash("Unknown state");
  957. break;
  958. }
  959. }
  960. if (state === 2)
  961. crash(`Unfinished custom RegExp for param "${buffer}"`);
  962. consumeBuffer();
  963. finalizeSegment();
  964. return tokens;
  965. }
  966. function createRouteRecordMatcher(record, parent, options) {
  967. const parser = tokensToParser(tokenizePath(record.path), options);
  968. if (true) {
  969. const existingKeys = new Set();
  970. for (const key of parser.keys) {
  971. if (existingKeys.has(key.name))
  972. warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
  973. existingKeys.add(key.name);
  974. }
  975. }
  976. const matcher = assign(parser, {
  977. record,
  978. parent,
  979. children: [],
  980. alias: []
  981. });
  982. if (parent) {
  983. if (!matcher.record.aliasOf === !parent.record.aliasOf)
  984. parent.children.push(matcher);
  985. }
  986. return matcher;
  987. }
  988. function createRouterMatcher(routes, globalOptions) {
  989. const matchers = [];
  990. const matcherMap = new Map();
  991. globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions);
  992. function getRecordMatcher(name) {
  993. return matcherMap.get(name);
  994. }
  995. function addRoute(record, parent, originalRecord) {
  996. const isRootAdd = !originalRecord;
  997. const mainNormalizedRecord = normalizeRouteRecord(record);
  998. mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
  999. const options = mergeOptions(globalOptions, record);
  1000. const normalizedRecords = [
  1001. mainNormalizedRecord
  1002. ];
  1003. if ("alias" in record) {
  1004. const aliases = typeof record.alias === "string" ? [record.alias] : record.alias;
  1005. for (const alias of aliases) {
  1006. normalizedRecords.push(assign({}, mainNormalizedRecord, {
  1007. components: originalRecord ? originalRecord.record.components : mainNormalizedRecord.components,
  1008. path: alias,
  1009. aliasOf: originalRecord ? originalRecord.record : mainNormalizedRecord
  1010. }));
  1011. }
  1012. }
  1013. let matcher;
  1014. let originalMatcher;
  1015. for (const normalizedRecord of normalizedRecords) {
  1016. const { path } = normalizedRecord;
  1017. if (parent && path[0] !== "/") {
  1018. const parentPath = parent.record.path;
  1019. const connectingSlash = parentPath[parentPath.length - 1] === "/" ? "" : "/";
  1020. normalizedRecord.path = parent.record.path + (path && connectingSlash + path);
  1021. }
  1022. if (normalizedRecord.path === "*") {
  1023. throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\nSee more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.');
  1024. }
  1025. matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
  1026. if (parent && path[0] === "/")
  1027. checkMissingParamsInAbsolutePath(matcher, parent);
  1028. if (originalRecord) {
  1029. originalRecord.alias.push(matcher);
  1030. if (true) {
  1031. checkSameParams(originalRecord, matcher);
  1032. }
  1033. } else {
  1034. originalMatcher = originalMatcher || matcher;
  1035. if (originalMatcher !== matcher)
  1036. originalMatcher.alias.push(matcher);
  1037. if (isRootAdd && record.name && !isAliasRecord(matcher))
  1038. removeRoute(record.name);
  1039. }
  1040. if ("children" in mainNormalizedRecord) {
  1041. const children = mainNormalizedRecord.children;
  1042. for (let i = 0; i < children.length; i++) {
  1043. addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
  1044. }
  1045. }
  1046. originalRecord = originalRecord || matcher;
  1047. insertMatcher(matcher);
  1048. }
  1049. return originalMatcher ? () => {
  1050. removeRoute(originalMatcher);
  1051. } : noop;
  1052. }
  1053. function removeRoute(matcherRef) {
  1054. if (isRouteName(matcherRef)) {
  1055. const matcher = matcherMap.get(matcherRef);
  1056. if (matcher) {
  1057. matcherMap.delete(matcherRef);
  1058. matchers.splice(matchers.indexOf(matcher), 1);
  1059. matcher.children.forEach(removeRoute);
  1060. matcher.alias.forEach(removeRoute);
  1061. }
  1062. } else {
  1063. const index = matchers.indexOf(matcherRef);
  1064. if (index > -1) {
  1065. matchers.splice(index, 1);
  1066. if (matcherRef.record.name)
  1067. matcherMap.delete(matcherRef.record.name);
  1068. matcherRef.children.forEach(removeRoute);
  1069. matcherRef.alias.forEach(removeRoute);
  1070. }
  1071. }
  1072. }
  1073. function getRoutes() {
  1074. return matchers;
  1075. }
  1076. function insertMatcher(matcher) {
  1077. let i = 0;
  1078. while (i < matchers.length && comparePathParserScore(matcher, matchers[i]) >= 0 && (matcher.record.path !== matchers[i].record.path || !isRecordChildOf(matcher, matchers[i])))
  1079. i++;
  1080. matchers.splice(i, 0, matcher);
  1081. if (matcher.record.name && !isAliasRecord(matcher))
  1082. matcherMap.set(matcher.record.name, matcher);
  1083. }
  1084. function resolve(location2, currentLocation) {
  1085. let matcher;
  1086. let params = {};
  1087. let path;
  1088. let name;
  1089. if ("name" in location2 && location2.name) {
  1090. matcher = matcherMap.get(location2.name);
  1091. if (!matcher)
  1092. throw createRouterError(1, {
  1093. location: location2
  1094. });
  1095. name = matcher.record.name;
  1096. params = assign(paramsFromLocation(currentLocation.params, matcher.keys.filter((k) => !k.optional).map((k) => k.name)), location2.params);
  1097. path = matcher.stringify(params);
  1098. } else if ("path" in location2) {
  1099. path = location2.path;
  1100. if (!path.startsWith("/")) {
  1101. 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.`);
  1102. }
  1103. matcher = matchers.find((m) => m.re.test(path));
  1104. if (matcher) {
  1105. params = matcher.parse(path);
  1106. name = matcher.record.name;
  1107. }
  1108. } else {
  1109. matcher = currentLocation.name ? matcherMap.get(currentLocation.name) : matchers.find((m) => m.re.test(currentLocation.path));
  1110. if (!matcher)
  1111. throw createRouterError(1, {
  1112. location: location2,
  1113. currentLocation
  1114. });
  1115. name = matcher.record.name;
  1116. params = assign({}, currentLocation.params, location2.params);
  1117. path = matcher.stringify(params);
  1118. }
  1119. const matched = [];
  1120. let parentMatcher = matcher;
  1121. while (parentMatcher) {
  1122. matched.unshift(parentMatcher.record);
  1123. parentMatcher = parentMatcher.parent;
  1124. }
  1125. return {
  1126. name,
  1127. path,
  1128. params,
  1129. matched,
  1130. meta: mergeMetaFields(matched)
  1131. };
  1132. }
  1133. routes.forEach((route) => addRoute(route));
  1134. return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher };
  1135. }
  1136. function paramsFromLocation(params, keys) {
  1137. const newParams = {};
  1138. for (const key of keys) {
  1139. if (key in params)
  1140. newParams[key] = params[key];
  1141. }
  1142. return newParams;
  1143. }
  1144. function normalizeRouteRecord(record) {
  1145. return {
  1146. path: record.path,
  1147. redirect: record.redirect,
  1148. name: record.name,
  1149. meta: record.meta || {},
  1150. aliasOf: void 0,
  1151. beforeEnter: record.beforeEnter,
  1152. props: normalizeRecordProps(record),
  1153. children: record.children || [],
  1154. instances: {},
  1155. leaveGuards: new Set(),
  1156. updateGuards: new Set(),
  1157. enterCallbacks: {},
  1158. components: "components" in record ? record.components || {} : { default: record.component }
  1159. };
  1160. }
  1161. function normalizeRecordProps(record) {
  1162. const propsObject = {};
  1163. const props = record.props || false;
  1164. if ("component" in record) {
  1165. propsObject.default = props;
  1166. } else {
  1167. for (const name in record.components)
  1168. propsObject[name] = typeof props === "boolean" ? props : props[name];
  1169. }
  1170. return propsObject;
  1171. }
  1172. function isAliasRecord(record) {
  1173. while (record) {
  1174. if (record.record.aliasOf)
  1175. return true;
  1176. record = record.parent;
  1177. }
  1178. return false;
  1179. }
  1180. function mergeMetaFields(matched) {
  1181. return matched.reduce((meta, record) => assign(meta, record.meta), {});
  1182. }
  1183. function mergeOptions(defaults, partialOptions) {
  1184. const options = {};
  1185. for (const key in defaults) {
  1186. options[key] = key in partialOptions ? partialOptions[key] : defaults[key];
  1187. }
  1188. return options;
  1189. }
  1190. function isSameParam(a, b) {
  1191. return a.name === b.name && a.optional === b.optional && a.repeatable === b.repeatable;
  1192. }
  1193. function checkSameParams(a, b) {
  1194. for (const key of a.keys) {
  1195. if (!key.optional && !b.keys.find(isSameParam.bind(null, key)))
  1196. return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
  1197. }
  1198. for (const key of b.keys) {
  1199. if (!key.optional && !a.keys.find(isSameParam.bind(null, key)))
  1200. return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`);
  1201. }
  1202. }
  1203. function checkMissingParamsInAbsolutePath(record, parent) {
  1204. for (const key of parent.keys) {
  1205. if (!record.keys.find(isSameParam.bind(null, key)))
  1206. return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
  1207. }
  1208. }
  1209. function isRecordChildOf(record, parent) {
  1210. return parent.children.some((child) => child === record || isRecordChildOf(record, child));
  1211. }
  1212. var HASH_RE = /#/g;
  1213. var AMPERSAND_RE = /&/g;
  1214. var SLASH_RE = /\//g;
  1215. var EQUAL_RE = /=/g;
  1216. var IM_RE = /\?/g;
  1217. var PLUS_RE = /\+/g;
  1218. var ENC_BRACKET_OPEN_RE = /%5B/g;
  1219. var ENC_BRACKET_CLOSE_RE = /%5D/g;
  1220. var ENC_CARET_RE = /%5E/g;
  1221. var ENC_BACKTICK_RE = /%60/g;
  1222. var ENC_CURLY_OPEN_RE = /%7B/g;
  1223. var ENC_PIPE_RE = /%7C/g;
  1224. var ENC_CURLY_CLOSE_RE = /%7D/g;
  1225. var ENC_SPACE_RE = /%20/g;
  1226. function commonEncode(text) {
  1227. return encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]");
  1228. }
  1229. function encodeHash(text) {
  1230. return commonEncode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
  1231. }
  1232. function encodeQueryValue(text) {
  1233. return commonEncode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
  1234. }
  1235. function encodeQueryKey(text) {
  1236. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  1237. }
  1238. function encodePath(text) {
  1239. return commonEncode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F");
  1240. }
  1241. function encodeParam(text) {
  1242. return text == null ? "" : encodePath(text).replace(SLASH_RE, "%2F");
  1243. }
  1244. function decode(text) {
  1245. try {
  1246. return decodeURIComponent("" + text);
  1247. } catch (err) {
  1248. warn(`Error decoding "${text}". Using original value`);
  1249. }
  1250. return "" + text;
  1251. }
  1252. function parseQuery(search) {
  1253. const query = {};
  1254. if (search === "" || search === "?")
  1255. return query;
  1256. const hasLeadingIM = search[0] === "?";
  1257. const searchParams = (hasLeadingIM ? search.slice(1) : search).split("&");
  1258. for (let i = 0; i < searchParams.length; ++i) {
  1259. const searchParam = searchParams[i].replace(PLUS_RE, " ");
  1260. const eqPos = searchParam.indexOf("=");
  1261. const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
  1262. const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
  1263. if (key in query) {
  1264. let currentValue = query[key];
  1265. if (!Array.isArray(currentValue)) {
  1266. currentValue = query[key] = [currentValue];
  1267. }
  1268. currentValue.push(value);
  1269. } else {
  1270. query[key] = value;
  1271. }
  1272. }
  1273. return query;
  1274. }
  1275. function stringifyQuery(query) {
  1276. let search = "";
  1277. for (let key in query) {
  1278. const value = query[key];
  1279. key = encodeQueryKey(key);
  1280. if (value == null) {
  1281. if (value !== void 0) {
  1282. search += (search.length ? "&" : "") + key;
  1283. }
  1284. continue;
  1285. }
  1286. const values = Array.isArray(value) ? value.map((v) => v && encodeQueryValue(v)) : [value && encodeQueryValue(value)];
  1287. values.forEach((value2) => {
  1288. if (value2 !== void 0) {
  1289. search += (search.length ? "&" : "") + key;
  1290. if (value2 != null)
  1291. search += "=" + value2;
  1292. }
  1293. });
  1294. }
  1295. return search;
  1296. }
  1297. function normalizeQuery(query) {
  1298. const normalizedQuery = {};
  1299. for (const key in query) {
  1300. const value = query[key];
  1301. if (value !== void 0) {
  1302. normalizedQuery[key] = Array.isArray(value) ? value.map((v) => v == null ? null : "" + v) : value == null ? value : "" + value;
  1303. }
  1304. }
  1305. return normalizedQuery;
  1306. }
  1307. function useCallbacks() {
  1308. let handlers = [];
  1309. function add(handler) {
  1310. handlers.push(handler);
  1311. return () => {
  1312. const i = handlers.indexOf(handler);
  1313. if (i > -1)
  1314. handlers.splice(i, 1);
  1315. };
  1316. }
  1317. function reset() {
  1318. handlers = [];
  1319. }
  1320. return {
  1321. add,
  1322. list: () => handlers,
  1323. reset
  1324. };
  1325. }
  1326. function registerGuard(record, name, guard) {
  1327. const removeFromList = () => {
  1328. record[name].delete(guard);
  1329. };
  1330. onUnmounted(removeFromList);
  1331. onDeactivated(removeFromList);
  1332. onActivated(() => {
  1333. record[name].add(guard);
  1334. });
  1335. record[name].add(guard);
  1336. }
  1337. function onBeforeRouteLeave(leaveGuard) {
  1338. if (!getCurrentInstance()) {
  1339. warn("getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function");
  1340. return;
  1341. }
  1342. const activeRecord = inject(matchedRouteKey, {}).value;
  1343. if (!activeRecord) {
  1344. warn("No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside of a component child of <router-view>. Maybe you called it inside of App.vue?");
  1345. return;
  1346. }
  1347. registerGuard(activeRecord, "leaveGuards", leaveGuard);
  1348. }
  1349. function onBeforeRouteUpdate(updateGuard) {
  1350. if (!getCurrentInstance()) {
  1351. warn("getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function");
  1352. return;
  1353. }
  1354. const activeRecord = inject(matchedRouteKey, {}).value;
  1355. if (!activeRecord) {
  1356. warn("No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside of a component child of <router-view>. Maybe you called it inside of App.vue?");
  1357. return;
  1358. }
  1359. registerGuard(activeRecord, "updateGuards", updateGuard);
  1360. }
  1361. function guardToPromiseFn(guard, to, from, record, name) {
  1362. const enterCallbackArray = record && (record.enterCallbacks[name] = record.enterCallbacks[name] || []);
  1363. return () => new Promise((resolve, reject) => {
  1364. const next = (valid) => {
  1365. if (valid === false)
  1366. reject(createRouterError(4, {
  1367. from,
  1368. to
  1369. }));
  1370. else if (valid instanceof Error) {
  1371. reject(valid);
  1372. } else if (isRouteLocation(valid)) {
  1373. reject(createRouterError(2, {
  1374. from: to,
  1375. to: valid
  1376. }));
  1377. } else {
  1378. if (enterCallbackArray && record.enterCallbacks[name] === enterCallbackArray && typeof valid === "function")
  1379. enterCallbackArray.push(valid);
  1380. resolve();
  1381. }
  1382. };
  1383. const guardReturn = guard.call(record && record.instances[name], to, from, true ? canOnlyBeCalledOnce(next, to, from) : next);
  1384. let guardCall = Promise.resolve(guardReturn);
  1385. if (guard.length < 3)
  1386. guardCall = guardCall.then(next);
  1387. if (guard.length > 2) {
  1388. const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ""}:
  1389. ${guard.toString()}
  1390. . If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
  1391. if (typeof guardReturn === "object" && "then" in guardReturn) {
  1392. guardCall = guardCall.then((resolvedValue) => {
  1393. if (!next._called) {
  1394. warn(message);
  1395. return Promise.reject(new Error("Invalid navigation guard"));
  1396. }
  1397. return resolvedValue;
  1398. });
  1399. } else if (guardReturn !== void 0) {
  1400. if (!next._called) {
  1401. warn(message);
  1402. reject(new Error("Invalid navigation guard"));
  1403. return;
  1404. }
  1405. }
  1406. }
  1407. guardCall.catch((err) => reject(err));
  1408. });
  1409. }
  1410. function canOnlyBeCalledOnce(next, to, from) {
  1411. let called = 0;
  1412. return function() {
  1413. if (called++ === 1)
  1414. 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.`);
  1415. next._called = true;
  1416. if (called === 1)
  1417. next.apply(null, arguments);
  1418. };
  1419. }
  1420. function extractComponentsGuards(matched, guardType, to, from) {
  1421. const guards = [];
  1422. for (const record of matched) {
  1423. for (const name in record.components) {
  1424. let rawComponent = record.components[name];
  1425. if (true) {
  1426. if (!rawComponent || typeof rawComponent !== "object" && typeof rawComponent !== "function") {
  1427. warn(`Component "${name}" in record with path "${record.path}" is not a valid component. Received "${String(rawComponent)}".`);
  1428. throw new Error("Invalid route component");
  1429. } else if ("then" in rawComponent) {
  1430. warn(`Component "${name}" in record with path "${record.path}" is a Promise instead of a function that returns a Promise. Did you write "import('./MyPage.vue')" instead of "() => import('./MyPage.vue')" ? This will break in production if not fixed.`);
  1431. const promise = rawComponent;
  1432. rawComponent = () => promise;
  1433. } else if (rawComponent.__asyncLoader && !rawComponent.__warnedDefineAsync) {
  1434. rawComponent.__warnedDefineAsync = true;
  1435. warn(`Component "${name}" in record with path "${record.path}" is defined using "defineAsyncComponent()". Write "() => import('./MyPage.vue')" instead of "defineAsyncComponent(() => import('./MyPage.vue'))".`);
  1436. }
  1437. }
  1438. if (guardType !== "beforeRouteEnter" && !record.instances[name])
  1439. continue;
  1440. if (isRouteComponent(rawComponent)) {
  1441. const options = rawComponent.__vccOpts || rawComponent;
  1442. const guard = options[guardType];
  1443. guard && guards.push(guardToPromiseFn(guard, to, from, record, name));
  1444. } else {
  1445. let componentPromise = rawComponent();
  1446. if (!("catch" in componentPromise)) {
  1447. 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.`);
  1448. componentPromise = Promise.resolve(componentPromise);
  1449. }
  1450. guards.push(() => componentPromise.then((resolved) => {
  1451. if (!resolved)
  1452. return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`));
  1453. const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
  1454. record.components[name] = resolvedComponent;
  1455. const options = resolvedComponent.__vccOpts || resolvedComponent;
  1456. const guard = options[guardType];
  1457. return guard && guardToPromiseFn(guard, to, from, record, name)();
  1458. }));
  1459. }
  1460. }
  1461. }
  1462. return guards;
  1463. }
  1464. function isRouteComponent(component) {
  1465. return typeof component === "object" || "displayName" in component || "props" in component || "__vccOpts" in component;
  1466. }
  1467. function useLink(props) {
  1468. const router = inject(routerKey);
  1469. const currentRoute = inject(routeLocationKey);
  1470. const route = computed(() => router.resolve(unref(props.to)));
  1471. const activeRecordIndex = computed(() => {
  1472. const { matched } = route.value;
  1473. const { length } = matched;
  1474. const routeMatched = matched[length - 1];
  1475. const currentMatched = currentRoute.matched;
  1476. if (!routeMatched || !currentMatched.length)
  1477. return -1;
  1478. const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
  1479. if (index > -1)
  1480. return index;
  1481. const parentRecordPath = getOriginalPath(matched[length - 2]);
  1482. return length > 1 && getOriginalPath(routeMatched) === parentRecordPath && currentMatched[currentMatched.length - 1].path !== parentRecordPath ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) : index;
  1483. });
  1484. const isActive = computed(() => activeRecordIndex.value > -1 && includesParams(currentRoute.params, route.value.params));
  1485. const isExactActive = computed(() => activeRecordIndex.value > -1 && activeRecordIndex.value === currentRoute.matched.length - 1 && isSameRouteLocationParams(currentRoute.params, route.value.params));
  1486. function navigate(e = {}) {
  1487. if (guardEvent(e)) {
  1488. return router[unref(props.replace) ? "replace" : "push"](unref(props.to)).catch(noop);
  1489. }
  1490. return Promise.resolve();
  1491. }
  1492. if (isBrowser) {
  1493. const instance = getCurrentInstance();
  1494. if (instance) {
  1495. const linkContextDevtools = {
  1496. route: route.value,
  1497. isActive: isActive.value,
  1498. isExactActive: isExactActive.value
  1499. };
  1500. instance.__vrl_devtools = instance.__vrl_devtools || [];
  1501. instance.__vrl_devtools.push(linkContextDevtools);
  1502. watchEffect(() => {
  1503. linkContextDevtools.route = route.value;
  1504. linkContextDevtools.isActive = isActive.value;
  1505. linkContextDevtools.isExactActive = isExactActive.value;
  1506. }, { flush: "post" });
  1507. }
  1508. }
  1509. return {
  1510. route,
  1511. href: computed(() => route.value.href),
  1512. isActive,
  1513. isExactActive,
  1514. navigate
  1515. };
  1516. }
  1517. var RouterLinkImpl = defineComponent({
  1518. name: "RouterLink",
  1519. compatConfig: { MODE: 3 },
  1520. props: {
  1521. to: {
  1522. type: [String, Object],
  1523. required: true
  1524. },
  1525. replace: Boolean,
  1526. activeClass: String,
  1527. exactActiveClass: String,
  1528. custom: Boolean,
  1529. ariaCurrentValue: {
  1530. type: String,
  1531. default: "page"
  1532. }
  1533. },
  1534. useLink,
  1535. setup(props, { slots }) {
  1536. const link = reactive(useLink(props));
  1537. const { options } = inject(routerKey);
  1538. const elClass = computed(() => ({
  1539. [getLinkClass(props.activeClass, options.linkActiveClass, "router-link-active")]: link.isActive,
  1540. [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, "router-link-exact-active")]: link.isExactActive
  1541. }));
  1542. return () => {
  1543. const children = slots.default && slots.default(link);
  1544. return props.custom ? children : h("a", {
  1545. "aria-current": link.isExactActive ? props.ariaCurrentValue : null,
  1546. href: link.href,
  1547. onClick: link.navigate,
  1548. class: elClass.value
  1549. }, children);
  1550. };
  1551. }
  1552. });
  1553. var RouterLink = RouterLinkImpl;
  1554. function guardEvent(e) {
  1555. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
  1556. return;
  1557. if (e.defaultPrevented)
  1558. return;
  1559. if (e.button !== void 0 && e.button !== 0)
  1560. return;
  1561. if (e.currentTarget && e.currentTarget.getAttribute) {
  1562. const target = e.currentTarget.getAttribute("target");
  1563. if (/\b_blank\b/i.test(target))
  1564. return;
  1565. }
  1566. if (e.preventDefault)
  1567. e.preventDefault();
  1568. return true;
  1569. }
  1570. function includesParams(outer, inner) {
  1571. for (const key in inner) {
  1572. const innerValue = inner[key];
  1573. const outerValue = outer[key];
  1574. if (typeof innerValue === "string") {
  1575. if (innerValue !== outerValue)
  1576. return false;
  1577. } else {
  1578. if (!Array.isArray(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value !== outerValue[i]))
  1579. return false;
  1580. }
  1581. }
  1582. return true;
  1583. }
  1584. function getOriginalPath(record) {
  1585. return record ? record.aliasOf ? record.aliasOf.path : record.path : "";
  1586. }
  1587. var getLinkClass = (propClass, globalClass, defaultClass) => propClass != null ? propClass : globalClass != null ? globalClass : defaultClass;
  1588. var RouterViewImpl = defineComponent({
  1589. name: "RouterView",
  1590. inheritAttrs: false,
  1591. props: {
  1592. name: {
  1593. type: String,
  1594. default: "default"
  1595. },
  1596. route: Object
  1597. },
  1598. compatConfig: { MODE: 3 },
  1599. setup(props, { attrs, slots }) {
  1600. warnDeprecatedUsage();
  1601. const injectedRoute = inject(routerViewLocationKey);
  1602. const routeToDisplay = computed(() => props.route || injectedRoute.value);
  1603. const depth = inject(viewDepthKey, 0);
  1604. const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth]);
  1605. provide(viewDepthKey, depth + 1);
  1606. provide(matchedRouteKey, matchedRouteRef);
  1607. provide(routerViewLocationKey, routeToDisplay);
  1608. const viewRef = ref();
  1609. watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => {
  1610. if (to) {
  1611. to.instances[name] = instance;
  1612. if (from && from !== to && instance && instance === oldInstance) {
  1613. if (!to.leaveGuards.size) {
  1614. to.leaveGuards = from.leaveGuards;
  1615. }
  1616. if (!to.updateGuards.size) {
  1617. to.updateGuards = from.updateGuards;
  1618. }
  1619. }
  1620. }
  1621. if (instance && to && (!from || !isSameRouteRecord(to, from) || !oldInstance)) {
  1622. (to.enterCallbacks[name] || []).forEach((callback) => callback(instance));
  1623. }
  1624. }, { flush: "post" });
  1625. return () => {
  1626. const route = routeToDisplay.value;
  1627. const matchedRoute = matchedRouteRef.value;
  1628. const ViewComponent = matchedRoute && matchedRoute.components[props.name];
  1629. const currentName = props.name;
  1630. if (!ViewComponent) {
  1631. return normalizeSlot(slots.default, { Component: ViewComponent, route });
  1632. }
  1633. const routePropsOption = matchedRoute.props[props.name];
  1634. const routeProps = routePropsOption ? routePropsOption === true ? route.params : typeof routePropsOption === "function" ? routePropsOption(route) : routePropsOption : null;
  1635. const onVnodeUnmounted = (vnode) => {
  1636. if (vnode.component.isUnmounted) {
  1637. matchedRoute.instances[currentName] = null;
  1638. }
  1639. };
  1640. const component = h(ViewComponent, assign({}, routeProps, attrs, {
  1641. onVnodeUnmounted,
  1642. ref: viewRef
  1643. }));
  1644. if (isBrowser && component.ref) {
  1645. const info = {
  1646. depth,
  1647. name: matchedRoute.name,
  1648. path: matchedRoute.path,
  1649. meta: matchedRoute.meta
  1650. };
  1651. const internalInstances = Array.isArray(component.ref) ? component.ref.map((r) => r.i) : [component.ref.i];
  1652. internalInstances.forEach((instance) => {
  1653. instance.__vrv_devtools = info;
  1654. });
  1655. }
  1656. return normalizeSlot(slots.default, { Component: component, route }) || component;
  1657. };
  1658. }
  1659. });
  1660. function normalizeSlot(slot, data) {
  1661. if (!slot)
  1662. return null;
  1663. const slotContent = slot(data);
  1664. return slotContent.length === 1 ? slotContent[0] : slotContent;
  1665. }
  1666. var RouterView = RouterViewImpl;
  1667. function warnDeprecatedUsage() {
  1668. const instance = getCurrentInstance();
  1669. const parentName = instance.parent && instance.parent.type.name;
  1670. if (parentName && (parentName === "KeepAlive" || parentName.includes("Transition"))) {
  1671. const comp = parentName === "KeepAlive" ? "keep-alive" : "transition";
  1672. warn(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.
  1673. Use slot props instead:
  1674. <router-view v-slot="{ Component }">
  1675. <${comp}>
  1676. <component :is="Component" />
  1677. </${comp}>
  1678. </router-view>`);
  1679. }
  1680. }
  1681. function formatRouteLocation(routeLocation, tooltip) {
  1682. const copy = assign({}, routeLocation, {
  1683. matched: routeLocation.matched.map((matched) => omit(matched, ["instances", "children", "aliasOf"]))
  1684. });
  1685. return {
  1686. _custom: {
  1687. type: null,
  1688. readOnly: true,
  1689. display: routeLocation.fullPath,
  1690. tooltip,
  1691. value: copy
  1692. }
  1693. };
  1694. }
  1695. function formatDisplay(display) {
  1696. return {
  1697. _custom: {
  1698. display
  1699. }
  1700. };
  1701. }
  1702. var routerId = 0;
  1703. function addDevtools(app, router, matcher) {
  1704. if (router.__hasDevtools)
  1705. return;
  1706. router.__hasDevtools = true;
  1707. const id = routerId++;
  1708. setupDevtoolsPlugin({
  1709. id: "org.vuejs.router" + (id ? "." + id : ""),
  1710. label: "Vue Router",
  1711. packageName: "vue-router",
  1712. homepage: "https://router.vuejs.org",
  1713. logo: "https://router.vuejs.org/logo.png",
  1714. componentStateTypes: ["Routing"],
  1715. app
  1716. }, (api) => {
  1717. api.on.inspectComponent((payload, ctx) => {
  1718. if (payload.instanceData) {
  1719. payload.instanceData.state.push({
  1720. type: "Routing",
  1721. key: "$route",
  1722. editable: false,
  1723. value: formatRouteLocation(router.currentRoute.value, "Current Route")
  1724. });
  1725. }
  1726. });
  1727. api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
  1728. if (componentInstance.__vrv_devtools) {
  1729. const info = componentInstance.__vrv_devtools;
  1730. node.tags.push({
  1731. label: (info.name ? `${info.name.toString()}: ` : "") + info.path,
  1732. textColor: 0,
  1733. tooltip: "This component is rendered by &lt;router-view&gt;",
  1734. backgroundColor: PINK_500
  1735. });
  1736. }
  1737. if (Array.isArray(componentInstance.__vrl_devtools)) {
  1738. componentInstance.__devtoolsApi = api;
  1739. componentInstance.__vrl_devtools.forEach((devtoolsData) => {
  1740. let backgroundColor = ORANGE_400;
  1741. let tooltip = "";
  1742. if (devtoolsData.isExactActive) {
  1743. backgroundColor = LIME_500;
  1744. tooltip = "This is exactly active";
  1745. } else if (devtoolsData.isActive) {
  1746. backgroundColor = BLUE_600;
  1747. tooltip = "This link is active";
  1748. }
  1749. node.tags.push({
  1750. label: devtoolsData.route.path,
  1751. textColor: 0,
  1752. tooltip,
  1753. backgroundColor
  1754. });
  1755. });
  1756. }
  1757. });
  1758. watch(router.currentRoute, () => {
  1759. refreshRoutesView();
  1760. api.notifyComponentUpdate();
  1761. api.sendInspectorTree(routerInspectorId);
  1762. api.sendInspectorState(routerInspectorId);
  1763. });
  1764. const navigationsLayerId = "router:navigations:" + id;
  1765. api.addTimelineLayer({
  1766. id: navigationsLayerId,
  1767. label: `Router${id ? " " + id : ""} Navigations`,
  1768. color: 4237508
  1769. });
  1770. router.onError((error, to) => {
  1771. api.addTimelineEvent({
  1772. layerId: navigationsLayerId,
  1773. event: {
  1774. title: "Error during Navigation",
  1775. subtitle: to.fullPath,
  1776. logType: "error",
  1777. time: api.now(),
  1778. data: { error },
  1779. groupId: to.meta.__navigationId
  1780. }
  1781. });
  1782. });
  1783. let navigationId = 0;
  1784. router.beforeEach((to, from) => {
  1785. const data = {
  1786. guard: formatDisplay("beforeEach"),
  1787. from: formatRouteLocation(from, "Current Location during this navigation"),
  1788. to: formatRouteLocation(to, "Target location")
  1789. };
  1790. Object.defineProperty(to.meta, "__navigationId", {
  1791. value: navigationId++
  1792. });
  1793. api.addTimelineEvent({
  1794. layerId: navigationsLayerId,
  1795. event: {
  1796. time: api.now(),
  1797. title: "Start of navigation",
  1798. subtitle: to.fullPath,
  1799. data,
  1800. groupId: to.meta.__navigationId
  1801. }
  1802. });
  1803. });
  1804. router.afterEach((to, from, failure) => {
  1805. const data = {
  1806. guard: formatDisplay("afterEach")
  1807. };
  1808. if (failure) {
  1809. data.failure = {
  1810. _custom: {
  1811. type: Error,
  1812. readOnly: true,
  1813. display: failure ? failure.message : "",
  1814. tooltip: "Navigation Failure",
  1815. value: failure
  1816. }
  1817. };
  1818. data.status = formatDisplay("\u274C");
  1819. } else {
  1820. data.status = formatDisplay("\u2705");
  1821. }
  1822. data.from = formatRouteLocation(from, "Current Location during this navigation");
  1823. data.to = formatRouteLocation(to, "Target location");
  1824. api.addTimelineEvent({
  1825. layerId: navigationsLayerId,
  1826. event: {
  1827. title: "End of navigation",
  1828. subtitle: to.fullPath,
  1829. time: api.now(),
  1830. data,
  1831. logType: failure ? "warning" : "default",
  1832. groupId: to.meta.__navigationId
  1833. }
  1834. });
  1835. });
  1836. const routerInspectorId = "router-inspector:" + id;
  1837. api.addInspector({
  1838. id: routerInspectorId,
  1839. label: "Routes" + (id ? " " + id : ""),
  1840. icon: "book",
  1841. treeFilterPlaceholder: "Search routes"
  1842. });
  1843. function refreshRoutesView() {
  1844. if (!activeRoutesPayload)
  1845. return;
  1846. const payload = activeRoutesPayload;
  1847. let routes = matcher.getRoutes().filter((route) => !route.parent);
  1848. routes.forEach(resetMatchStateOnRouteRecord);
  1849. if (payload.filter) {
  1850. routes = routes.filter((route) => isRouteMatching(route, payload.filter.toLowerCase()));
  1851. }
  1852. routes.forEach((route) => markRouteRecordActive(route, router.currentRoute.value));
  1853. payload.rootNodes = routes.map(formatRouteRecordForInspector);
  1854. }
  1855. let activeRoutesPayload;
  1856. api.on.getInspectorTree((payload) => {
  1857. activeRoutesPayload = payload;
  1858. if (payload.app === app && payload.inspectorId === routerInspectorId) {
  1859. refreshRoutesView();
  1860. }
  1861. });
  1862. api.on.getInspectorState((payload) => {
  1863. if (payload.app === app && payload.inspectorId === routerInspectorId) {
  1864. const routes = matcher.getRoutes();
  1865. const route = routes.find((route2) => route2.record.__vd_id === payload.nodeId);
  1866. if (route) {
  1867. payload.state = {
  1868. options: formatRouteRecordMatcherForStateInspector(route)
  1869. };
  1870. }
  1871. }
  1872. });
  1873. api.sendInspectorTree(routerInspectorId);
  1874. api.sendInspectorState(routerInspectorId);
  1875. });
  1876. }
  1877. function modifierForKey(key) {
  1878. if (key.optional) {
  1879. return key.repeatable ? "*" : "?";
  1880. } else {
  1881. return key.repeatable ? "+" : "";
  1882. }
  1883. }
  1884. function formatRouteRecordMatcherForStateInspector(route) {
  1885. const { record } = route;
  1886. const fields = [
  1887. { editable: false, key: "path", value: record.path }
  1888. ];
  1889. if (record.name != null) {
  1890. fields.push({
  1891. editable: false,
  1892. key: "name",
  1893. value: record.name
  1894. });
  1895. }
  1896. fields.push({ editable: false, key: "regexp", value: route.re });
  1897. if (route.keys.length) {
  1898. fields.push({
  1899. editable: false,
  1900. key: "keys",
  1901. value: {
  1902. _custom: {
  1903. type: null,
  1904. readOnly: true,
  1905. display: route.keys.map((key) => `${key.name}${modifierForKey(key)}`).join(" "),
  1906. tooltip: "Param keys",
  1907. value: route.keys
  1908. }
  1909. }
  1910. });
  1911. }
  1912. if (record.redirect != null) {
  1913. fields.push({
  1914. editable: false,
  1915. key: "redirect",
  1916. value: record.redirect
  1917. });
  1918. }
  1919. if (route.alias.length) {
  1920. fields.push({
  1921. editable: false,
  1922. key: "aliases",
  1923. value: route.alias.map((alias) => alias.record.path)
  1924. });
  1925. }
  1926. fields.push({
  1927. key: "score",
  1928. editable: false,
  1929. value: {
  1930. _custom: {
  1931. type: null,
  1932. readOnly: true,
  1933. display: route.score.map((score) => score.join(", ")).join(" | "),
  1934. tooltip: "Score used to sort routes",
  1935. value: route.score
  1936. }
  1937. }
  1938. });
  1939. return fields;
  1940. }
  1941. var PINK_500 = 15485081;
  1942. var BLUE_600 = 2450411;
  1943. var LIME_500 = 8702998;
  1944. var CYAN_400 = 2282478;
  1945. var ORANGE_400 = 16486972;
  1946. var DARK = 6710886;
  1947. function formatRouteRecordForInspector(route) {
  1948. const tags = [];
  1949. const { record } = route;
  1950. if (record.name != null) {
  1951. tags.push({
  1952. label: String(record.name),
  1953. textColor: 0,
  1954. backgroundColor: CYAN_400
  1955. });
  1956. }
  1957. if (record.aliasOf) {
  1958. tags.push({
  1959. label: "alias",
  1960. textColor: 0,
  1961. backgroundColor: ORANGE_400
  1962. });
  1963. }
  1964. if (route.__vd_match) {
  1965. tags.push({
  1966. label: "matches",
  1967. textColor: 0,
  1968. backgroundColor: PINK_500
  1969. });
  1970. }
  1971. if (route.__vd_exactActive) {
  1972. tags.push({
  1973. label: "exact",
  1974. textColor: 0,
  1975. backgroundColor: LIME_500
  1976. });
  1977. }
  1978. if (route.__vd_active) {
  1979. tags.push({
  1980. label: "active",
  1981. textColor: 0,
  1982. backgroundColor: BLUE_600
  1983. });
  1984. }
  1985. if (record.redirect) {
  1986. tags.push({
  1987. label: "redirect: " + (typeof record.redirect === "string" ? record.redirect : "Object"),
  1988. textColor: 16777215,
  1989. backgroundColor: DARK
  1990. });
  1991. }
  1992. let id = record.__vd_id;
  1993. if (id == null) {
  1994. id = String(routeRecordId++);
  1995. record.__vd_id = id;
  1996. }
  1997. return {
  1998. id,
  1999. label: record.path,
  2000. tags,
  2001. children: route.children.map(formatRouteRecordForInspector)
  2002. };
  2003. }
  2004. var routeRecordId = 0;
  2005. var EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
  2006. function markRouteRecordActive(route, currentRoute) {
  2007. const isExactActive = currentRoute.matched.length && isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
  2008. route.__vd_exactActive = route.__vd_active = isExactActive;
  2009. if (!isExactActive) {
  2010. route.__vd_active = currentRoute.matched.some((match) => isSameRouteRecord(match, route.record));
  2011. }
  2012. route.children.forEach((childRoute) => markRouteRecordActive(childRoute, currentRoute));
  2013. }
  2014. function resetMatchStateOnRouteRecord(route) {
  2015. route.__vd_match = false;
  2016. route.children.forEach(resetMatchStateOnRouteRecord);
  2017. }
  2018. function isRouteMatching(route, filter) {
  2019. const found = String(route.re).match(EXTRACT_REGEXP_RE);
  2020. route.__vd_match = false;
  2021. if (!found || found.length < 3) {
  2022. return false;
  2023. }
  2024. const nonEndingRE = new RegExp(found[1].replace(/\$$/, ""), found[2]);
  2025. if (nonEndingRE.test(filter)) {
  2026. route.children.forEach((child) => isRouteMatching(child, filter));
  2027. if (route.record.path !== "/" || filter === "/") {
  2028. route.__vd_match = route.re.test(filter);
  2029. return true;
  2030. }
  2031. return false;
  2032. }
  2033. const path = route.record.path.toLowerCase();
  2034. const decodedPath = decode(path);
  2035. if (!filter.startsWith("/") && (decodedPath.includes(filter) || path.includes(filter)))
  2036. return true;
  2037. if (decodedPath.startsWith(filter) || path.startsWith(filter))
  2038. return true;
  2039. if (route.record.name && String(route.record.name).includes(filter))
  2040. return true;
  2041. return route.children.some((child) => isRouteMatching(child, filter));
  2042. }
  2043. function omit(obj, keys) {
  2044. const ret = {};
  2045. for (const key in obj) {
  2046. if (!keys.includes(key)) {
  2047. ret[key] = obj[key];
  2048. }
  2049. }
  2050. return ret;
  2051. }
  2052. function createRouter(options) {
  2053. const matcher = createRouterMatcher(options.routes, options);
  2054. const parseQuery$1 = options.parseQuery || parseQuery;
  2055. const stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
  2056. const routerHistory = options.history;
  2057. if (!routerHistory)
  2058. throw new Error('Provide the "history" option when calling "createRouter()": https://next.router.vuejs.org/api/#history.');
  2059. const beforeGuards = useCallbacks();
  2060. const beforeResolveGuards = useCallbacks();
  2061. const afterGuards = useCallbacks();
  2062. const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
  2063. let pendingLocation = START_LOCATION_NORMALIZED;
  2064. if (isBrowser && options.scrollBehavior && "scrollRestoration" in history) {
  2065. history.scrollRestoration = "manual";
  2066. }
  2067. const normalizeParams = applyToParams.bind(null, (paramValue) => "" + paramValue);
  2068. const encodeParams = applyToParams.bind(null, encodeParam);
  2069. const decodeParams = applyToParams.bind(null, decode);
  2070. function addRoute(parentOrRoute, route) {
  2071. let parent;
  2072. let record;
  2073. if (isRouteName(parentOrRoute)) {
  2074. parent = matcher.getRecordMatcher(parentOrRoute);
  2075. record = route;
  2076. } else {
  2077. record = parentOrRoute;
  2078. }
  2079. return matcher.addRoute(record, parent);
  2080. }
  2081. function removeRoute(name) {
  2082. const recordMatcher = matcher.getRecordMatcher(name);
  2083. if (recordMatcher) {
  2084. matcher.removeRoute(recordMatcher);
  2085. } else if (true) {
  2086. warn(`Cannot remove non-existent route "${String(name)}"`);
  2087. }
  2088. }
  2089. function getRoutes() {
  2090. return matcher.getRoutes().map((routeMatcher) => routeMatcher.record);
  2091. }
  2092. function hasRoute(name) {
  2093. return !!matcher.getRecordMatcher(name);
  2094. }
  2095. function resolve(rawLocation, currentLocation) {
  2096. currentLocation = assign({}, currentLocation || currentRoute.value);
  2097. if (typeof rawLocation === "string") {
  2098. const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
  2099. const matchedRoute2 = matcher.resolve({ path: locationNormalized.path }, currentLocation);
  2100. const href2 = routerHistory.createHref(locationNormalized.fullPath);
  2101. if (true) {
  2102. if (href2.startsWith("//"))
  2103. warn(`Location "${rawLocation}" resolved to "${href2}". A resolved location cannot start with multiple slashes.`);
  2104. else if (!matchedRoute2.matched.length) {
  2105. warn(`No match found for location with path "${rawLocation}"`);
  2106. }
  2107. }
  2108. return assign(locationNormalized, matchedRoute2, {
  2109. params: decodeParams(matchedRoute2.params),
  2110. hash: decode(locationNormalized.hash),
  2111. redirectedFrom: void 0,
  2112. href: href2
  2113. });
  2114. }
  2115. let matcherLocation;
  2116. if ("path" in rawLocation) {
  2117. if ("params" in rawLocation && !("name" in rawLocation) && Object.keys(rawLocation.params).length) {
  2118. warn(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
  2119. }
  2120. matcherLocation = assign({}, rawLocation, {
  2121. path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path
  2122. });
  2123. } else {
  2124. const targetParams = assign({}, rawLocation.params);
  2125. for (const key in targetParams) {
  2126. if (targetParams[key] == null) {
  2127. delete targetParams[key];
  2128. }
  2129. }
  2130. matcherLocation = assign({}, rawLocation, {
  2131. params: encodeParams(rawLocation.params)
  2132. });
  2133. currentLocation.params = encodeParams(currentLocation.params);
  2134. }
  2135. const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
  2136. const hash = rawLocation.hash || "";
  2137. if (hash && !hash.startsWith("#")) {
  2138. warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
  2139. }
  2140. matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
  2141. const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
  2142. hash: encodeHash(hash),
  2143. path: matchedRoute.path
  2144. }));
  2145. const href = routerHistory.createHref(fullPath);
  2146. if (true) {
  2147. if (href.startsWith("//")) {
  2148. warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
  2149. } else if (!matchedRoute.matched.length) {
  2150. warn(`No match found for location with path "${"path" in rawLocation ? rawLocation.path : rawLocation}"`);
  2151. }
  2152. }
  2153. return assign({
  2154. fullPath,
  2155. hash,
  2156. query: stringifyQuery$1 === stringifyQuery ? normalizeQuery(rawLocation.query) : rawLocation.query || {}
  2157. }, matchedRoute, {
  2158. redirectedFrom: void 0,
  2159. href
  2160. });
  2161. }
  2162. function locationAsObject(to) {
  2163. return typeof to === "string" ? parseURL(parseQuery$1, to, currentRoute.value.path) : assign({}, to);
  2164. }
  2165. function checkCanceledNavigation(to, from) {
  2166. if (pendingLocation !== to) {
  2167. return createRouterError(8, {
  2168. from,
  2169. to
  2170. });
  2171. }
  2172. }
  2173. function push(to) {
  2174. return pushWithRedirect(to);
  2175. }
  2176. function replace(to) {
  2177. return push(assign(locationAsObject(to), { replace: true }));
  2178. }
  2179. function handleRedirectRecord(to) {
  2180. const lastMatched = to.matched[to.matched.length - 1];
  2181. if (lastMatched && lastMatched.redirect) {
  2182. const { redirect } = lastMatched;
  2183. let newTargetLocation = typeof redirect === "function" ? redirect(to) : redirect;
  2184. if (typeof newTargetLocation === "string") {
  2185. newTargetLocation = newTargetLocation.includes("?") || newTargetLocation.includes("#") ? newTargetLocation = locationAsObject(newTargetLocation) : { path: newTargetLocation };
  2186. newTargetLocation.params = {};
  2187. }
  2188. if (!("path" in newTargetLocation) && !("name" in newTargetLocation)) {
  2189. warn(`Invalid redirect found:
  2190. ${JSON.stringify(newTargetLocation, null, 2)}
  2191. when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
  2192. throw new Error("Invalid redirect");
  2193. }
  2194. return assign({
  2195. query: to.query,
  2196. hash: to.hash,
  2197. params: to.params
  2198. }, newTargetLocation);
  2199. }
  2200. }
  2201. function pushWithRedirect(to, redirectedFrom) {
  2202. const targetLocation = pendingLocation = resolve(to);
  2203. const from = currentRoute.value;
  2204. const data = to.state;
  2205. const force = to.force;
  2206. const replace2 = to.replace === true;
  2207. const shouldRedirect = handleRedirectRecord(targetLocation);
  2208. if (shouldRedirect)
  2209. return pushWithRedirect(assign(locationAsObject(shouldRedirect), {
  2210. state: data,
  2211. force,
  2212. replace: replace2
  2213. }), redirectedFrom || targetLocation);
  2214. const toLocation = targetLocation;
  2215. toLocation.redirectedFrom = redirectedFrom;
  2216. let failure;
  2217. if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
  2218. failure = createRouterError(16, { to: toLocation, from });
  2219. handleScroll(from, from, true, false);
  2220. }
  2221. return (failure ? Promise.resolve(failure) : navigate(toLocation, from)).catch((error) => isNavigationFailure(error) ? isNavigationFailure(error, 2) ? error : markAsReady(error) : triggerError(error, toLocation, from)).then((failure2) => {
  2222. if (failure2) {
  2223. if (isNavigationFailure(failure2, 2)) {
  2224. if (isSameRouteLocation(stringifyQuery$1, resolve(failure2.to), toLocation) && redirectedFrom && (redirectedFrom._count = redirectedFrom._count ? redirectedFrom._count + 1 : 1) > 10) {
  2225. 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.`);
  2226. return Promise.reject(new Error("Infinite redirect in navigation guard"));
  2227. }
  2228. return pushWithRedirect(assign(locationAsObject(failure2.to), {
  2229. state: data,
  2230. force,
  2231. replace: replace2
  2232. }), redirectedFrom || toLocation);
  2233. }
  2234. } else {
  2235. failure2 = finalizeNavigation(toLocation, from, true, replace2, data);
  2236. }
  2237. triggerAfterEach(toLocation, from, failure2);
  2238. return failure2;
  2239. });
  2240. }
  2241. function checkCanceledNavigationAndReject(to, from) {
  2242. const error = checkCanceledNavigation(to, from);
  2243. return error ? Promise.reject(error) : Promise.resolve();
  2244. }
  2245. function navigate(to, from) {
  2246. let guards;
  2247. const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from);
  2248. guards = extractComponentsGuards(leavingRecords.reverse(), "beforeRouteLeave", to, from);
  2249. for (const record of leavingRecords) {
  2250. record.leaveGuards.forEach((guard) => {
  2251. guards.push(guardToPromiseFn(guard, to, from));
  2252. });
  2253. }
  2254. const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
  2255. guards.push(canceledNavigationCheck);
  2256. return runGuardQueue(guards).then(() => {
  2257. guards = [];
  2258. for (const guard of beforeGuards.list()) {
  2259. guards.push(guardToPromiseFn(guard, to, from));
  2260. }
  2261. guards.push(canceledNavigationCheck);
  2262. return runGuardQueue(guards);
  2263. }).then(() => {
  2264. guards = extractComponentsGuards(updatingRecords, "beforeRouteUpdate", to, from);
  2265. for (const record of updatingRecords) {
  2266. record.updateGuards.forEach((guard) => {
  2267. guards.push(guardToPromiseFn(guard, to, from));
  2268. });
  2269. }
  2270. guards.push(canceledNavigationCheck);
  2271. return runGuardQueue(guards);
  2272. }).then(() => {
  2273. guards = [];
  2274. for (const record of to.matched) {
  2275. if (record.beforeEnter && !from.matched.includes(record)) {
  2276. if (Array.isArray(record.beforeEnter)) {
  2277. for (const beforeEnter of record.beforeEnter)
  2278. guards.push(guardToPromiseFn(beforeEnter, to, from));
  2279. } else {
  2280. guards.push(guardToPromiseFn(record.beforeEnter, to, from));
  2281. }
  2282. }
  2283. }
  2284. guards.push(canceledNavigationCheck);
  2285. return runGuardQueue(guards);
  2286. }).then(() => {
  2287. to.matched.forEach((record) => record.enterCallbacks = {});
  2288. guards = extractComponentsGuards(enteringRecords, "beforeRouteEnter", to, from);
  2289. guards.push(canceledNavigationCheck);
  2290. return runGuardQueue(guards);
  2291. }).then(() => {
  2292. guards = [];
  2293. for (const guard of beforeResolveGuards.list()) {
  2294. guards.push(guardToPromiseFn(guard, to, from));
  2295. }
  2296. guards.push(canceledNavigationCheck);
  2297. return runGuardQueue(guards);
  2298. }).catch((err) => isNavigationFailure(err, 8) ? err : Promise.reject(err));
  2299. }
  2300. function triggerAfterEach(to, from, failure) {
  2301. for (const guard of afterGuards.list())
  2302. guard(to, from, failure);
  2303. }
  2304. function finalizeNavigation(toLocation, from, isPush, replace2, data) {
  2305. const error = checkCanceledNavigation(toLocation, from);
  2306. if (error)
  2307. return error;
  2308. const isFirstNavigation = from === START_LOCATION_NORMALIZED;
  2309. const state = !isBrowser ? {} : history.state;
  2310. if (isPush) {
  2311. if (replace2 || isFirstNavigation)
  2312. routerHistory.replace(toLocation.fullPath, assign({
  2313. scroll: isFirstNavigation && state && state.scroll
  2314. }, data));
  2315. else
  2316. routerHistory.push(toLocation.fullPath, data);
  2317. }
  2318. currentRoute.value = toLocation;
  2319. handleScroll(toLocation, from, isPush, isFirstNavigation);
  2320. markAsReady();
  2321. }
  2322. let removeHistoryListener;
  2323. function setupListeners() {
  2324. if (removeHistoryListener)
  2325. return;
  2326. removeHistoryListener = routerHistory.listen((to, _from, info) => {
  2327. const toLocation = resolve(to);
  2328. const shouldRedirect = handleRedirectRecord(toLocation);
  2329. if (shouldRedirect) {
  2330. pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop);
  2331. return;
  2332. }
  2333. pendingLocation = toLocation;
  2334. const from = currentRoute.value;
  2335. if (isBrowser) {
  2336. saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
  2337. }
  2338. navigate(toLocation, from).catch((error) => {
  2339. if (isNavigationFailure(error, 4 | 8)) {
  2340. return error;
  2341. }
  2342. if (isNavigationFailure(error, 2)) {
  2343. pushWithRedirect(error.to, toLocation).then((failure) => {
  2344. if (isNavigationFailure(failure, 4 | 16) && !info.delta && info.type === NavigationType.pop) {
  2345. routerHistory.go(-1, false);
  2346. }
  2347. }).catch(noop);
  2348. return Promise.reject();
  2349. }
  2350. if (info.delta)
  2351. routerHistory.go(-info.delta, false);
  2352. return triggerError(error, toLocation, from);
  2353. }).then((failure) => {
  2354. failure = failure || finalizeNavigation(toLocation, from, false);
  2355. if (failure) {
  2356. if (info.delta) {
  2357. routerHistory.go(-info.delta, false);
  2358. } else if (info.type === NavigationType.pop && isNavigationFailure(failure, 4 | 16)) {
  2359. routerHistory.go(-1, false);
  2360. }
  2361. }
  2362. triggerAfterEach(toLocation, from, failure);
  2363. }).catch(noop);
  2364. });
  2365. }
  2366. let readyHandlers = useCallbacks();
  2367. let errorHandlers = useCallbacks();
  2368. let ready;
  2369. function triggerError(error, to, from) {
  2370. markAsReady(error);
  2371. const list = errorHandlers.list();
  2372. if (list.length) {
  2373. list.forEach((handler) => handler(error, to, from));
  2374. } else {
  2375. if (true) {
  2376. warn("uncaught error during route navigation:");
  2377. }
  2378. console.error(error);
  2379. }
  2380. return Promise.reject(error);
  2381. }
  2382. function isReady() {
  2383. if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
  2384. return Promise.resolve();
  2385. return new Promise((resolve2, reject) => {
  2386. readyHandlers.add([resolve2, reject]);
  2387. });
  2388. }
  2389. function markAsReady(err) {
  2390. if (!ready) {
  2391. ready = !err;
  2392. setupListeners();
  2393. readyHandlers.list().forEach(([resolve2, reject]) => err ? reject(err) : resolve2());
  2394. readyHandlers.reset();
  2395. }
  2396. return err;
  2397. }
  2398. function handleScroll(to, from, isPush, isFirstNavigation) {
  2399. const { scrollBehavior } = options;
  2400. if (!isBrowser || !scrollBehavior)
  2401. return Promise.resolve();
  2402. const scrollPosition = !isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0)) || (isFirstNavigation || !isPush) && history.state && history.state.scroll || null;
  2403. return nextTick().then(() => scrollBehavior(to, from, scrollPosition)).then((position) => position && scrollToPosition(position)).catch((err) => triggerError(err, to, from));
  2404. }
  2405. const go = (delta) => routerHistory.go(delta);
  2406. let started;
  2407. const installedApps = new Set();
  2408. const router = {
  2409. currentRoute,
  2410. addRoute,
  2411. removeRoute,
  2412. hasRoute,
  2413. getRoutes,
  2414. resolve,
  2415. options,
  2416. push,
  2417. replace,
  2418. go,
  2419. back: () => go(-1),
  2420. forward: () => go(1),
  2421. beforeEach: beforeGuards.add,
  2422. beforeResolve: beforeResolveGuards.add,
  2423. afterEach: afterGuards.add,
  2424. onError: errorHandlers.add,
  2425. isReady,
  2426. install(app) {
  2427. const router2 = this;
  2428. app.component("RouterLink", RouterLink);
  2429. app.component("RouterView", RouterView);
  2430. app.config.globalProperties.$router = router2;
  2431. Object.defineProperty(app.config.globalProperties, "$route", {
  2432. enumerable: true,
  2433. get: () => unref(currentRoute)
  2434. });
  2435. if (isBrowser && !started && currentRoute.value === START_LOCATION_NORMALIZED) {
  2436. started = true;
  2437. push(routerHistory.location).catch((err) => {
  2438. if (true)
  2439. warn("Unexpected error when starting the router:", err);
  2440. });
  2441. }
  2442. const reactiveRoute = {};
  2443. for (const key in START_LOCATION_NORMALIZED) {
  2444. reactiveRoute[key] = computed(() => currentRoute.value[key]);
  2445. }
  2446. app.provide(routerKey, router2);
  2447. app.provide(routeLocationKey, reactive(reactiveRoute));
  2448. app.provide(routerViewLocationKey, currentRoute);
  2449. const unmountApp = app.unmount;
  2450. installedApps.add(app);
  2451. app.unmount = function() {
  2452. installedApps.delete(app);
  2453. if (installedApps.size < 1) {
  2454. pendingLocation = START_LOCATION_NORMALIZED;
  2455. removeHistoryListener && removeHistoryListener();
  2456. removeHistoryListener = null;
  2457. currentRoute.value = START_LOCATION_NORMALIZED;
  2458. started = false;
  2459. ready = false;
  2460. }
  2461. unmountApp();
  2462. };
  2463. if (isBrowser) {
  2464. addDevtools(app, router2, matcher);
  2465. }
  2466. }
  2467. };
  2468. return router;
  2469. }
  2470. function runGuardQueue(guards) {
  2471. return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve());
  2472. }
  2473. function extractChangingRecords(to, from) {
  2474. const leavingRecords = [];
  2475. const updatingRecords = [];
  2476. const enteringRecords = [];
  2477. const len = Math.max(from.matched.length, to.matched.length);
  2478. for (let i = 0; i < len; i++) {
  2479. const recordFrom = from.matched[i];
  2480. if (recordFrom) {
  2481. if (to.matched.find((record) => isSameRouteRecord(record, recordFrom)))
  2482. updatingRecords.push(recordFrom);
  2483. else
  2484. leavingRecords.push(recordFrom);
  2485. }
  2486. const recordTo = to.matched[i];
  2487. if (recordTo) {
  2488. if (!from.matched.find((record) => isSameRouteRecord(record, recordTo))) {
  2489. enteringRecords.push(recordTo);
  2490. }
  2491. }
  2492. }
  2493. return [leavingRecords, updatingRecords, enteringRecords];
  2494. }
  2495. function useRouter() {
  2496. return inject(routerKey);
  2497. }
  2498. function useRoute() {
  2499. return inject(routeLocationKey);
  2500. }
  2501. export {
  2502. NavigationFailureType,
  2503. RouterLink,
  2504. RouterView,
  2505. START_LOCATION_NORMALIZED as START_LOCATION,
  2506. createMemoryHistory,
  2507. createRouter,
  2508. createRouterMatcher,
  2509. createWebHashHistory,
  2510. createWebHistory,
  2511. isNavigationFailure,
  2512. matchedRouteKey,
  2513. onBeforeRouteLeave,
  2514. onBeforeRouteUpdate,
  2515. parseQuery,
  2516. routeLocationKey,
  2517. routerKey,
  2518. routerViewLocationKey,
  2519. stringifyQuery,
  2520. useLink,
  2521. useRoute,
  2522. useRouter,
  2523. viewDepthKey
  2524. };
  2525. /*!
  2526. * vue-router v4.0.16
  2527. * (c) 2022 Eduardo San Martin Morote
  2528. * @license MIT
  2529. */
  2530. //# sourceMappingURL=vue-router.js.map