vue-router.js 83 KB

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