vue-router_dist_vue-router__esm-bundler.js 90 KB

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