vue-router.js 92 KB

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