vue-router.mjs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. /*!
  2. * vue-router v4.6.3
  3. * (c) 2025 Eduardo San Martin Morote
  4. * @license MIT
  5. */
  6. import { ErrorTypes, NavigationDirection, NavigationFailureType, NavigationType, START, START_LOCATION_NORMALIZED, addDevtools, applyToParams, assign, computeScrollPosition, createHref, createRouterError, decode, encodeHash, encodeParam, extractChangingRecords, extractComponentsGuards, getSavedScrollPosition, getScrollKey, guardToPromiseFn, isArray, isBrowser, isNavigationFailure, isRouteLocation, isRouteName, isSameRouteLocation, isSameRouteLocationParams, isSameRouteRecord, loadRouteLocation, matchedRouteKey, mergeOptions, noop, normalizeBase, normalizeQuery, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, parseURL, routeLocationKey, routerKey, routerViewLocationKey, saveScrollPosition, scrollToPosition, stringifyQuery, stringifyURL, stripBase, useCallbacks, viewDepthKey, warn as warn$1 } from "./devtools-BLCumUwL.mjs";
  7. import { computed, defineComponent, getCurrentInstance, h, inject, nextTick, provide, reactive, ref, shallowReactive, shallowRef, unref, watch, watchEffect } from "vue";
  8. //#region src/history/html5.ts
  9. let createBaseLocation = () => location.protocol + "//" + location.host;
  10. /**
  11. * Creates a normalized history location from a window.location object
  12. * @param base - The base path
  13. * @param location - The window.location object
  14. */
  15. function createCurrentLocation(base, location$1) {
  16. const { pathname, search, hash } = location$1;
  17. const hashPos = base.indexOf("#");
  18. if (hashPos > -1) {
  19. let slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1;
  20. let pathFromHash = hash.slice(slicePos);
  21. if (pathFromHash[0] !== "/") pathFromHash = "/" + pathFromHash;
  22. return stripBase(pathFromHash, "");
  23. }
  24. return stripBase(pathname, base) + search + hash;
  25. }
  26. function useHistoryListeners(base, historyState, currentLocation, replace) {
  27. let listeners = [];
  28. let teardowns = [];
  29. let pauseState = null;
  30. const popStateHandler = ({ state }) => {
  31. const to = createCurrentLocation(base, location);
  32. const from = currentLocation.value;
  33. const fromState = historyState.value;
  34. let delta = 0;
  35. if (state) {
  36. currentLocation.value = to;
  37. historyState.value = state;
  38. if (pauseState && pauseState === from) {
  39. pauseState = null;
  40. return;
  41. }
  42. delta = fromState ? state.position - fromState.position : 0;
  43. } else replace(to);
  44. listeners.forEach((listener) => {
  45. listener(currentLocation.value, from, {
  46. delta,
  47. type: NavigationType.pop,
  48. direction: delta ? delta > 0 ? NavigationDirection.forward : NavigationDirection.back : NavigationDirection.unknown
  49. });
  50. });
  51. };
  52. function pauseListeners() {
  53. pauseState = currentLocation.value;
  54. }
  55. function listen(callback) {
  56. listeners.push(callback);
  57. const teardown = () => {
  58. const index = listeners.indexOf(callback);
  59. if (index > -1) listeners.splice(index, 1);
  60. };
  61. teardowns.push(teardown);
  62. return teardown;
  63. }
  64. function beforeUnloadListener() {
  65. if (document.visibilityState === "hidden") {
  66. const { history: history$1 } = window;
  67. if (!history$1.state) return;
  68. history$1.replaceState(assign({}, history$1.state, { scroll: computeScrollPosition() }), "");
  69. }
  70. }
  71. function destroy() {
  72. for (const teardown of teardowns) teardown();
  73. teardowns = [];
  74. window.removeEventListener("popstate", popStateHandler);
  75. window.removeEventListener("pagehide", beforeUnloadListener);
  76. document.removeEventListener("visibilitychange", beforeUnloadListener);
  77. }
  78. window.addEventListener("popstate", popStateHandler);
  79. window.addEventListener("pagehide", beforeUnloadListener);
  80. document.addEventListener("visibilitychange", beforeUnloadListener);
  81. return {
  82. pauseListeners,
  83. listen,
  84. destroy
  85. };
  86. }
  87. /**
  88. * Creates a state object
  89. */
  90. function buildState(back, current, forward, replaced = false, computeScroll = false) {
  91. return {
  92. back,
  93. current,
  94. forward,
  95. replaced,
  96. position: window.history.length,
  97. scroll: computeScroll ? computeScrollPosition() : null
  98. };
  99. }
  100. function useHistoryStateNavigation(base) {
  101. const { history: history$1, location: location$1 } = window;
  102. const currentLocation = { value: createCurrentLocation(base, location$1) };
  103. const historyState = { value: history$1.state };
  104. if (!historyState.value) changeLocation(currentLocation.value, {
  105. back: null,
  106. current: currentLocation.value,
  107. forward: null,
  108. position: history$1.length - 1,
  109. replaced: true,
  110. scroll: null
  111. }, true);
  112. function changeLocation(to, state, replace$1) {
  113. /**
  114. * if a base tag is provided, and we are on a normal domain, we have to
  115. * respect the provided `base` attribute because pushState() will use it and
  116. * potentially erase anything before the `#` like at
  117. * https://github.com/vuejs/router/issues/685 where a base of
  118. * `/folder/#` but a base of `/` would erase the `/folder/` section. If
  119. * there is no host, the `<base>` tag makes no sense and if there isn't a
  120. * base tag we can just use everything after the `#`.
  121. */
  122. const hashIndex = base.indexOf("#");
  123. const url = hashIndex > -1 ? (location$1.host && document.querySelector("base") ? base : base.slice(hashIndex)) + to : createBaseLocation() + base + to;
  124. try {
  125. history$1[replace$1 ? "replaceState" : "pushState"](state, "", url);
  126. historyState.value = state;
  127. } catch (err) {
  128. if (process.env.NODE_ENV !== "production") warn$1("Error with push/replace State", err);
  129. else console.error(err);
  130. location$1[replace$1 ? "replace" : "assign"](url);
  131. }
  132. }
  133. function replace(to, data) {
  134. changeLocation(to, assign({}, history$1.state, buildState(historyState.value.back, to, historyState.value.forward, true), data, { position: historyState.value.position }), true);
  135. currentLocation.value = to;
  136. }
  137. function push(to, data) {
  138. const currentState = assign({}, historyState.value, history$1.state, {
  139. forward: to,
  140. scroll: computeScrollPosition()
  141. });
  142. if (process.env.NODE_ENV !== "production" && !history$1.state) warn$1("history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\nhistory.replaceState(history.state, '', url)\n\nYou can find more information at https://router.vuejs.org/guide/migration/#Usage-of-history-state");
  143. changeLocation(currentState.current, currentState, true);
  144. changeLocation(to, assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data), false);
  145. currentLocation.value = to;
  146. }
  147. return {
  148. location: currentLocation,
  149. state: historyState,
  150. push,
  151. replace
  152. };
  153. }
  154. /**
  155. * Creates an HTML5 history. Most common history for single page applications.
  156. *
  157. * @param base -
  158. */
  159. function createWebHistory(base) {
  160. base = normalizeBase(base);
  161. const historyNavigation = useHistoryStateNavigation(base);
  162. const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
  163. function go(delta, triggerListeners = true) {
  164. if (!triggerListeners) historyListeners.pauseListeners();
  165. history.go(delta);
  166. }
  167. const routerHistory = assign({
  168. location: "",
  169. base,
  170. go,
  171. createHref: createHref.bind(null, base)
  172. }, historyNavigation, historyListeners);
  173. Object.defineProperty(routerHistory, "location", {
  174. enumerable: true,
  175. get: () => historyNavigation.location.value
  176. });
  177. Object.defineProperty(routerHistory, "state", {
  178. enumerable: true,
  179. get: () => historyNavigation.state.value
  180. });
  181. return routerHistory;
  182. }
  183. //#endregion
  184. //#region src/history/memory.ts
  185. /**
  186. * Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere.
  187. * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`.
  188. *
  189. * @param base - Base applied to all urls, defaults to '/'
  190. * @returns a history object that can be passed to the router constructor
  191. */
  192. function createMemoryHistory(base = "") {
  193. let listeners = [];
  194. let queue = [[START, {}]];
  195. let position = 0;
  196. base = normalizeBase(base);
  197. function setLocation(location$1, state = {}) {
  198. position++;
  199. if (position !== queue.length) queue.splice(position);
  200. queue.push([location$1, state]);
  201. }
  202. function triggerListeners(to, from, { direction, delta }) {
  203. const info = {
  204. direction,
  205. delta,
  206. type: NavigationType.pop
  207. };
  208. for (const callback of listeners) callback(to, from, info);
  209. }
  210. const routerHistory = {
  211. location: START,
  212. state: {},
  213. base,
  214. createHref: createHref.bind(null, base),
  215. replace(to, state) {
  216. queue.splice(position--, 1);
  217. setLocation(to, state);
  218. },
  219. push(to, state) {
  220. setLocation(to, state);
  221. },
  222. listen(callback) {
  223. listeners.push(callback);
  224. return () => {
  225. const index = listeners.indexOf(callback);
  226. if (index > -1) listeners.splice(index, 1);
  227. };
  228. },
  229. destroy() {
  230. listeners = [];
  231. queue = [[START, {}]];
  232. position = 0;
  233. },
  234. go(delta, shouldTrigger = true) {
  235. const from = this.location;
  236. const direction = delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
  237. position = Math.max(0, Math.min(position + delta, queue.length - 1));
  238. if (shouldTrigger) triggerListeners(this.location, from, {
  239. direction,
  240. delta
  241. });
  242. }
  243. };
  244. Object.defineProperty(routerHistory, "location", {
  245. enumerable: true,
  246. get: () => queue[position][0]
  247. });
  248. Object.defineProperty(routerHistory, "state", {
  249. enumerable: true,
  250. get: () => queue[position][1]
  251. });
  252. return routerHistory;
  253. }
  254. //#endregion
  255. //#region src/history/hash.ts
  256. /**
  257. * Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to
  258. * handle any URL is not possible.
  259. *
  260. * @param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `<base>` tag
  261. * in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState()
  262. * calls**, meaning that if you use a `<base>` tag, it's `href` value **has to match this parameter** (ignoring anything
  263. * after the `#`).
  264. *
  265. * @example
  266. * ```js
  267. * // at https://example.com/folder
  268. * createWebHashHistory() // gives a url of `https://example.com/folder#`
  269. * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
  270. * // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
  271. * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
  272. * // you should avoid doing this because it changes the original url and breaks copying urls
  273. * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
  274. *
  275. * // at file:///usr/etc/folder/index.html
  276. * // for locations with no `host`, the base is ignored
  277. * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
  278. * ```
  279. */
  280. function createWebHashHistory(base) {
  281. base = location.host ? base || location.pathname + location.search : "";
  282. if (!base.includes("#")) base += "#";
  283. if (process.env.NODE_ENV !== "production" && !base.endsWith("#/") && !base.endsWith("#")) warn$1(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, "#")}".`);
  284. return createWebHistory(base);
  285. }
  286. //#endregion
  287. //#region src/matcher/pathTokenizer.ts
  288. let TokenType = /* @__PURE__ */ function(TokenType$1) {
  289. TokenType$1[TokenType$1["Static"] = 0] = "Static";
  290. TokenType$1[TokenType$1["Param"] = 1] = "Param";
  291. TokenType$1[TokenType$1["Group"] = 2] = "Group";
  292. return TokenType$1;
  293. }({});
  294. var TokenizerState = /* @__PURE__ */ function(TokenizerState$1) {
  295. TokenizerState$1[TokenizerState$1["Static"] = 0] = "Static";
  296. TokenizerState$1[TokenizerState$1["Param"] = 1] = "Param";
  297. TokenizerState$1[TokenizerState$1["ParamRegExp"] = 2] = "ParamRegExp";
  298. TokenizerState$1[TokenizerState$1["ParamRegExpEnd"] = 3] = "ParamRegExpEnd";
  299. TokenizerState$1[TokenizerState$1["EscapeNext"] = 4] = "EscapeNext";
  300. return TokenizerState$1;
  301. }(TokenizerState || {});
  302. const ROOT_TOKEN = {
  303. type: TokenType.Static,
  304. value: ""
  305. };
  306. const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
  307. function tokenizePath(path) {
  308. if (!path) return [[]];
  309. if (path === "/") return [[ROOT_TOKEN]];
  310. if (!path.startsWith("/")) throw new Error(process.env.NODE_ENV !== "production" ? `Route paths should start with a "/": "${path}" should be "/${path}".` : `Invalid path "${path}"`);
  311. function crash(message) {
  312. throw new Error(`ERR (${state})/"${buffer}": ${message}`);
  313. }
  314. let state = TokenizerState.Static;
  315. let previousState = state;
  316. const tokens = [];
  317. let segment;
  318. function finalizeSegment() {
  319. if (segment) tokens.push(segment);
  320. segment = [];
  321. }
  322. let i = 0;
  323. let char;
  324. let buffer = "";
  325. let customRe = "";
  326. function consumeBuffer() {
  327. if (!buffer) return;
  328. if (state === TokenizerState.Static) segment.push({
  329. type: TokenType.Static,
  330. value: buffer
  331. });
  332. else if (state === TokenizerState.Param || state === TokenizerState.ParamRegExp || state === TokenizerState.ParamRegExpEnd) {
  333. if (segment.length > 1 && (char === "*" || char === "+")) crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
  334. segment.push({
  335. type: TokenType.Param,
  336. value: buffer,
  337. regexp: customRe,
  338. repeatable: char === "*" || char === "+",
  339. optional: char === "*" || char === "?"
  340. });
  341. } else crash("Invalid state to consume buffer");
  342. buffer = "";
  343. }
  344. function addCharToBuffer() {
  345. buffer += char;
  346. }
  347. while (i < path.length) {
  348. char = path[i++];
  349. if (char === "\\" && state !== TokenizerState.ParamRegExp) {
  350. previousState = state;
  351. state = TokenizerState.EscapeNext;
  352. continue;
  353. }
  354. switch (state) {
  355. case TokenizerState.Static:
  356. if (char === "/") {
  357. if (buffer) consumeBuffer();
  358. finalizeSegment();
  359. } else if (char === ":") {
  360. consumeBuffer();
  361. state = TokenizerState.Param;
  362. } else addCharToBuffer();
  363. break;
  364. case TokenizerState.EscapeNext:
  365. addCharToBuffer();
  366. state = previousState;
  367. break;
  368. case TokenizerState.Param:
  369. if (char === "(") state = TokenizerState.ParamRegExp;
  370. else if (VALID_PARAM_RE.test(char)) addCharToBuffer();
  371. else {
  372. consumeBuffer();
  373. state = TokenizerState.Static;
  374. if (char !== "*" && char !== "?" && char !== "+") i--;
  375. }
  376. break;
  377. case TokenizerState.ParamRegExp:
  378. if (char === ")") if (customRe[customRe.length - 1] == "\\") customRe = customRe.slice(0, -1) + char;
  379. else state = TokenizerState.ParamRegExpEnd;
  380. else customRe += char;
  381. break;
  382. case TokenizerState.ParamRegExpEnd:
  383. consumeBuffer();
  384. state = TokenizerState.Static;
  385. if (char !== "*" && char !== "?" && char !== "+") i--;
  386. customRe = "";
  387. break;
  388. default:
  389. crash("Unknown state");
  390. break;
  391. }
  392. }
  393. if (state === TokenizerState.ParamRegExp) crash(`Unfinished custom RegExp for param "${buffer}"`);
  394. consumeBuffer();
  395. finalizeSegment();
  396. return tokens;
  397. }
  398. //#endregion
  399. //#region src/matcher/pathParserRanker.ts
  400. const BASE_PARAM_PATTERN = "[^/]+?";
  401. const BASE_PATH_PARSER_OPTIONS = {
  402. sensitive: false,
  403. strict: false,
  404. start: true,
  405. end: true
  406. };
  407. var PathScore = /* @__PURE__ */ function(PathScore$1) {
  408. PathScore$1[PathScore$1["_multiplier"] = 10] = "_multiplier";
  409. PathScore$1[PathScore$1["Root"] = 90] = "Root";
  410. PathScore$1[PathScore$1["Segment"] = 40] = "Segment";
  411. PathScore$1[PathScore$1["SubSegment"] = 30] = "SubSegment";
  412. PathScore$1[PathScore$1["Static"] = 40] = "Static";
  413. PathScore$1[PathScore$1["Dynamic"] = 20] = "Dynamic";
  414. PathScore$1[PathScore$1["BonusCustomRegExp"] = 10] = "BonusCustomRegExp";
  415. PathScore$1[PathScore$1["BonusWildcard"] = -50] = "BonusWildcard";
  416. PathScore$1[PathScore$1["BonusRepeatable"] = -20] = "BonusRepeatable";
  417. PathScore$1[PathScore$1["BonusOptional"] = -8] = "BonusOptional";
  418. PathScore$1[PathScore$1["BonusStrict"] = .7000000000000001] = "BonusStrict";
  419. PathScore$1[PathScore$1["BonusCaseSensitive"] = .25] = "BonusCaseSensitive";
  420. return PathScore$1;
  421. }(PathScore || {});
  422. const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
  423. /**
  424. * Creates a path parser from an array of Segments (a segment is an array of Tokens)
  425. *
  426. * @param segments - array of segments returned by tokenizePath
  427. * @param extraOptions - optional options for the regexp
  428. * @returns a PathParser
  429. */
  430. function tokensToParser(segments, extraOptions) {
  431. const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
  432. const score = [];
  433. let pattern = options.start ? "^" : "";
  434. const keys = [];
  435. for (const segment of segments) {
  436. const segmentScores = segment.length ? [] : [PathScore.Root];
  437. if (options.strict && !segment.length) pattern += "/";
  438. for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
  439. const token = segment[tokenIndex];
  440. let subSegmentScore = PathScore.Segment + (options.sensitive ? PathScore.BonusCaseSensitive : 0);
  441. if (token.type === TokenType.Static) {
  442. if (!tokenIndex) pattern += "/";
  443. pattern += token.value.replace(REGEX_CHARS_RE, "\\$&");
  444. subSegmentScore += PathScore.Static;
  445. } else if (token.type === TokenType.Param) {
  446. const { value, repeatable, optional, regexp } = token;
  447. keys.push({
  448. name: value,
  449. repeatable,
  450. optional
  451. });
  452. const re$1 = regexp ? regexp : BASE_PARAM_PATTERN;
  453. if (re$1 !== BASE_PARAM_PATTERN) {
  454. subSegmentScore += PathScore.BonusCustomRegExp;
  455. try {
  456. `${re$1}`;
  457. } catch (err) {
  458. throw new Error(`Invalid custom RegExp for param "${value}" (${re$1}): ` + err.message);
  459. }
  460. }
  461. let subPattern = repeatable ? `((?:${re$1})(?:/(?:${re$1}))*)` : `(${re$1})`;
  462. if (!tokenIndex) subPattern = optional && segment.length < 2 ? `(?:/${subPattern})` : "/" + subPattern;
  463. if (optional) subPattern += "?";
  464. pattern += subPattern;
  465. subSegmentScore += PathScore.Dynamic;
  466. if (optional) subSegmentScore += PathScore.BonusOptional;
  467. if (repeatable) subSegmentScore += PathScore.BonusRepeatable;
  468. if (re$1 === ".*") subSegmentScore += PathScore.BonusWildcard;
  469. }
  470. segmentScores.push(subSegmentScore);
  471. }
  472. score.push(segmentScores);
  473. }
  474. if (options.strict && options.end) {
  475. const i = score.length - 1;
  476. score[i][score[i].length - 1] += PathScore.BonusStrict;
  477. }
  478. if (!options.strict) pattern += "/?";
  479. if (options.end) pattern += "$";
  480. else if (options.strict && !pattern.endsWith("/")) pattern += "(?:/|$)";
  481. const re = new RegExp(pattern, options.sensitive ? "" : "i");
  482. function parse(path) {
  483. const match = path.match(re);
  484. const params = {};
  485. if (!match) return null;
  486. for (let i = 1; i < match.length; i++) {
  487. const value = match[i] || "";
  488. const key = keys[i - 1];
  489. params[key.name] = value && key.repeatable ? value.split("/") : value;
  490. }
  491. return params;
  492. }
  493. function stringify(params) {
  494. let path = "";
  495. let avoidDuplicatedSlash = false;
  496. for (const segment of segments) {
  497. if (!avoidDuplicatedSlash || !path.endsWith("/")) path += "/";
  498. avoidDuplicatedSlash = false;
  499. for (const token of segment) if (token.type === TokenType.Static) path += token.value;
  500. else if (token.type === TokenType.Param) {
  501. const { value, repeatable, optional } = token;
  502. const param = value in params ? params[value] : "";
  503. if (isArray(param) && !repeatable) throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
  504. const text = isArray(param) ? param.join("/") : param;
  505. if (!text) if (optional) {
  506. if (segment.length < 2) if (path.endsWith("/")) path = path.slice(0, -1);
  507. else avoidDuplicatedSlash = true;
  508. } else throw new Error(`Missing required param "${value}"`);
  509. path += text;
  510. }
  511. }
  512. return path || "/";
  513. }
  514. return {
  515. re,
  516. score,
  517. keys,
  518. parse,
  519. stringify
  520. };
  521. }
  522. /**
  523. * Compares an array of numbers as used in PathParser.score and returns a
  524. * number. This function can be used to `sort` an array
  525. *
  526. * @param a - first array of numbers
  527. * @param b - second array of numbers
  528. * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
  529. * should be sorted first
  530. */
  531. function compareScoreArray(a, b) {
  532. let i = 0;
  533. while (i < a.length && i < b.length) {
  534. const diff = b[i] - a[i];
  535. if (diff) return diff;
  536. i++;
  537. }
  538. if (a.length < b.length) return a.length === 1 && a[0] === PathScore.Static + PathScore.Segment ? -1 : 1;
  539. else if (a.length > b.length) return b.length === 1 && b[0] === PathScore.Static + PathScore.Segment ? 1 : -1;
  540. return 0;
  541. }
  542. /**
  543. * Compare function that can be used with `sort` to sort an array of PathParser
  544. *
  545. * @param a - first PathParser
  546. * @param b - second PathParser
  547. * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
  548. */
  549. function comparePathParserScore(a, b) {
  550. let i = 0;
  551. const aScore = a.score;
  552. const bScore = b.score;
  553. while (i < aScore.length && i < bScore.length) {
  554. const comp = compareScoreArray(aScore[i], bScore[i]);
  555. if (comp) return comp;
  556. i++;
  557. }
  558. if (Math.abs(bScore.length - aScore.length) === 1) {
  559. if (isLastScoreNegative(aScore)) return 1;
  560. if (isLastScoreNegative(bScore)) return -1;
  561. }
  562. return bScore.length - aScore.length;
  563. }
  564. /**
  565. * This allows detecting splats at the end of a path: /home/:id(.*)*
  566. *
  567. * @param score - score to check
  568. * @returns true if the last entry is negative
  569. */
  570. function isLastScoreNegative(score) {
  571. const last = score[score.length - 1];
  572. return score.length > 0 && last[last.length - 1] < 0;
  573. }
  574. const PATH_PARSER_OPTIONS_DEFAULTS = {
  575. strict: false,
  576. end: true,
  577. sensitive: false
  578. };
  579. //#endregion
  580. //#region src/matcher/pathMatcher.ts
  581. function createRouteRecordMatcher(record, parent, options) {
  582. const parser = tokensToParser(tokenizePath(record.path), options);
  583. if (process.env.NODE_ENV !== "production") {
  584. const existingKeys = /* @__PURE__ */ new Set();
  585. for (const key of parser.keys) {
  586. if (existingKeys.has(key.name)) warn$1(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
  587. existingKeys.add(key.name);
  588. }
  589. }
  590. const matcher = assign(parser, {
  591. record,
  592. parent,
  593. children: [],
  594. alias: []
  595. });
  596. if (parent) {
  597. if (!matcher.record.aliasOf === !parent.record.aliasOf) parent.children.push(matcher);
  598. }
  599. return matcher;
  600. }
  601. //#endregion
  602. //#region src/matcher/index.ts
  603. /**
  604. * Creates a Router Matcher.
  605. *
  606. * @internal
  607. * @param routes - array of initial routes
  608. * @param globalOptions - global route options
  609. */
  610. function createRouterMatcher(routes, globalOptions) {
  611. const matchers = [];
  612. const matcherMap = /* @__PURE__ */ new Map();
  613. globalOptions = mergeOptions(PATH_PARSER_OPTIONS_DEFAULTS, globalOptions);
  614. function getRecordMatcher(name) {
  615. return matcherMap.get(name);
  616. }
  617. function addRoute(record, parent, originalRecord) {
  618. const isRootAdd = !originalRecord;
  619. const mainNormalizedRecord = normalizeRouteRecord(record);
  620. if (process.env.NODE_ENV !== "production") checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent);
  621. mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
  622. const options = mergeOptions(globalOptions, record);
  623. const normalizedRecords = [mainNormalizedRecord];
  624. if ("alias" in record) {
  625. const aliases = typeof record.alias === "string" ? [record.alias] : record.alias;
  626. for (const alias of aliases) normalizedRecords.push(normalizeRouteRecord(assign({}, mainNormalizedRecord, {
  627. components: originalRecord ? originalRecord.record.components : mainNormalizedRecord.components,
  628. path: alias,
  629. aliasOf: originalRecord ? originalRecord.record : mainNormalizedRecord
  630. })));
  631. }
  632. let matcher;
  633. let originalMatcher;
  634. for (const normalizedRecord of normalizedRecords) {
  635. const { path } = normalizedRecord;
  636. if (parent && path[0] !== "/") {
  637. const parentPath = parent.record.path;
  638. const connectingSlash = parentPath[parentPath.length - 1] === "/" ? "" : "/";
  639. normalizedRecord.path = parent.record.path + (path && connectingSlash + path);
  640. }
  641. if (process.env.NODE_ENV !== "production" && normalizedRecord.path === "*") throw new Error("Catch all routes (\"*\") must now be defined using a param with a custom regexp.\nSee more at https://router.vuejs.org/guide/migration/#Removed-star-or-catch-all-routes.");
  642. matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
  643. if (process.env.NODE_ENV !== "production" && parent && path[0] === "/") checkMissingParamsInAbsolutePath(matcher, parent);
  644. if (originalRecord) {
  645. originalRecord.alias.push(matcher);
  646. if (process.env.NODE_ENV !== "production") checkSameParams(originalRecord, matcher);
  647. } else {
  648. originalMatcher = originalMatcher || matcher;
  649. if (originalMatcher !== matcher) originalMatcher.alias.push(matcher);
  650. if (isRootAdd && record.name && !isAliasRecord(matcher)) {
  651. if (process.env.NODE_ENV !== "production") checkSameNameAsAncestor(record, parent);
  652. removeRoute(record.name);
  653. }
  654. }
  655. if (isMatchable(matcher)) insertMatcher(matcher);
  656. if (mainNormalizedRecord.children) {
  657. const children = mainNormalizedRecord.children;
  658. for (let i = 0; i < children.length; i++) addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
  659. }
  660. originalRecord = originalRecord || matcher;
  661. }
  662. return originalMatcher ? () => {
  663. removeRoute(originalMatcher);
  664. } : noop;
  665. }
  666. function removeRoute(matcherRef) {
  667. if (isRouteName(matcherRef)) {
  668. const matcher = matcherMap.get(matcherRef);
  669. if (matcher) {
  670. matcherMap.delete(matcherRef);
  671. matchers.splice(matchers.indexOf(matcher), 1);
  672. matcher.children.forEach(removeRoute);
  673. matcher.alias.forEach(removeRoute);
  674. }
  675. } else {
  676. const index = matchers.indexOf(matcherRef);
  677. if (index > -1) {
  678. matchers.splice(index, 1);
  679. if (matcherRef.record.name) matcherMap.delete(matcherRef.record.name);
  680. matcherRef.children.forEach(removeRoute);
  681. matcherRef.alias.forEach(removeRoute);
  682. }
  683. }
  684. }
  685. function getRoutes() {
  686. return matchers;
  687. }
  688. function insertMatcher(matcher) {
  689. const index = findInsertionIndex(matcher, matchers);
  690. matchers.splice(index, 0, matcher);
  691. if (matcher.record.name && !isAliasRecord(matcher)) matcherMap.set(matcher.record.name, matcher);
  692. }
  693. function resolve(location$1, currentLocation) {
  694. let matcher;
  695. let params = {};
  696. let path;
  697. let name;
  698. if ("name" in location$1 && location$1.name) {
  699. matcher = matcherMap.get(location$1.name);
  700. if (!matcher) throw createRouterError(ErrorTypes.MATCHER_NOT_FOUND, { location: location$1 });
  701. if (process.env.NODE_ENV !== "production") {
  702. const invalidParams = Object.keys(location$1.params || {}).filter((paramName) => !matcher.keys.find((k) => k.name === paramName));
  703. if (invalidParams.length) warn$1(`Discarded invalid param(s) "${invalidParams.join("\", \"")}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`);
  704. }
  705. name = matcher.record.name;
  706. params = assign(pickParams(currentLocation.params, matcher.keys.filter((k) => !k.optional).concat(matcher.parent ? matcher.parent.keys.filter((k) => k.optional) : []).map((k) => k.name)), location$1.params && pickParams(location$1.params, matcher.keys.map((k) => k.name)));
  707. path = matcher.stringify(params);
  708. } else if (location$1.path != null) {
  709. path = location$1.path;
  710. if (process.env.NODE_ENV !== "production" && !path.startsWith("/")) warn$1(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://github.com/vuejs/router/issues/new/choose.`);
  711. matcher = matchers.find((m) => m.re.test(path));
  712. if (matcher) {
  713. params = matcher.parse(path);
  714. name = matcher.record.name;
  715. }
  716. } else {
  717. matcher = currentLocation.name ? matcherMap.get(currentLocation.name) : matchers.find((m) => m.re.test(currentLocation.path));
  718. if (!matcher) throw createRouterError(ErrorTypes.MATCHER_NOT_FOUND, {
  719. location: location$1,
  720. currentLocation
  721. });
  722. name = matcher.record.name;
  723. params = assign({}, currentLocation.params, location$1.params);
  724. path = matcher.stringify(params);
  725. }
  726. const matched = [];
  727. let parentMatcher = matcher;
  728. while (parentMatcher) {
  729. matched.unshift(parentMatcher.record);
  730. parentMatcher = parentMatcher.parent;
  731. }
  732. return {
  733. name,
  734. path,
  735. params,
  736. matched,
  737. meta: mergeMetaFields(matched)
  738. };
  739. }
  740. routes.forEach((route) => addRoute(route));
  741. function clearRoutes() {
  742. matchers.length = 0;
  743. matcherMap.clear();
  744. }
  745. return {
  746. addRoute,
  747. resolve,
  748. removeRoute,
  749. clearRoutes,
  750. getRoutes,
  751. getRecordMatcher
  752. };
  753. }
  754. /**
  755. * Picks an object param to contain only specified keys.
  756. *
  757. * @param params - params object to pick from
  758. * @param keys - keys to pick
  759. */
  760. function pickParams(params, keys) {
  761. const newParams = {};
  762. for (const key of keys) if (key in params) newParams[key] = params[key];
  763. return newParams;
  764. }
  765. /**
  766. * Normalizes a RouteRecordRaw. Creates a copy
  767. *
  768. * @param record
  769. * @returns the normalized version
  770. */
  771. function normalizeRouteRecord(record) {
  772. const normalized = {
  773. path: record.path,
  774. redirect: record.redirect,
  775. name: record.name,
  776. meta: record.meta || {},
  777. aliasOf: record.aliasOf,
  778. beforeEnter: record.beforeEnter,
  779. props: normalizeRecordProps(record),
  780. children: record.children || [],
  781. instances: {},
  782. leaveGuards: /* @__PURE__ */ new Set(),
  783. updateGuards: /* @__PURE__ */ new Set(),
  784. enterCallbacks: {},
  785. components: "components" in record ? record.components || null : record.component && { default: record.component }
  786. };
  787. Object.defineProperty(normalized, "mods", { value: {} });
  788. return normalized;
  789. }
  790. /**
  791. * Normalize the optional `props` in a record to always be an object similar to
  792. * components. Also accept a boolean for components.
  793. * @param record
  794. */
  795. function normalizeRecordProps(record) {
  796. const propsObject = {};
  797. const props = record.props || false;
  798. if ("component" in record) propsObject.default = props;
  799. else for (const name in record.components) propsObject[name] = typeof props === "object" ? props[name] : props;
  800. return propsObject;
  801. }
  802. /**
  803. * Checks if a record or any of its parent is an alias
  804. * @param record
  805. */
  806. function isAliasRecord(record) {
  807. while (record) {
  808. if (record.record.aliasOf) return true;
  809. record = record.parent;
  810. }
  811. return false;
  812. }
  813. /**
  814. * Merge meta fields of an array of records
  815. *
  816. * @param matched - array of matched records
  817. */
  818. function mergeMetaFields(matched) {
  819. return matched.reduce((meta, record) => assign(meta, record.meta), {});
  820. }
  821. function isSameParam(a, b) {
  822. return a.name === b.name && a.optional === b.optional && a.repeatable === b.repeatable;
  823. }
  824. /**
  825. * Check if a path and its alias have the same required params
  826. *
  827. * @param a - original record
  828. * @param b - alias record
  829. */
  830. function checkSameParams(a, b) {
  831. for (const key of a.keys) if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) return warn$1(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
  832. for (const key of b.keys) if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) return warn$1(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
  833. }
  834. /**
  835. * A route with a name and a child with an empty path without a name should warn when adding the route
  836. *
  837. * @param mainNormalizedRecord - RouteRecordNormalized
  838. * @param parent - RouteRecordMatcher
  839. */
  840. function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) {
  841. if (parent && parent.record.name && !mainNormalizedRecord.name && !mainNormalizedRecord.path) warn$1(`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.`);
  842. }
  843. function checkSameNameAsAncestor(record, parent) {
  844. for (let ancestor = parent; ancestor; ancestor = ancestor.parent) if (ancestor.record.name === record.name) throw new Error(`A route named "${String(record.name)}" has been added as a ${parent === ancestor ? "child" : "descendant"} of a route with the same name. Route names must be unique and a nested route cannot use the same name as an ancestor.`);
  845. }
  846. function checkMissingParamsInAbsolutePath(record, parent) {
  847. for (const key of parent.keys) if (!record.keys.find(isSameParam.bind(null, key))) return warn$1(`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
  848. }
  849. /**
  850. * Performs a binary search to find the correct insertion index for a new matcher.
  851. *
  852. * Matchers are primarily sorted by their score. If scores are tied then we also consider parent/child relationships,
  853. * with descendants coming before ancestors. If there's still a tie, new routes are inserted after existing routes.
  854. *
  855. * @param matcher - new matcher to be inserted
  856. * @param matchers - existing matchers
  857. */
  858. function findInsertionIndex(matcher, matchers) {
  859. let lower = 0;
  860. let upper = matchers.length;
  861. while (lower !== upper) {
  862. const mid = lower + upper >> 1;
  863. if (comparePathParserScore(matcher, matchers[mid]) < 0) upper = mid;
  864. else lower = mid + 1;
  865. }
  866. const insertionAncestor = getInsertionAncestor(matcher);
  867. if (insertionAncestor) {
  868. upper = matchers.lastIndexOf(insertionAncestor, upper - 1);
  869. if (process.env.NODE_ENV !== "production" && upper < 0) warn$1(`Finding ancestor route "${insertionAncestor.record.path}" failed for "${matcher.record.path}"`);
  870. }
  871. return upper;
  872. }
  873. function getInsertionAncestor(matcher) {
  874. let ancestor = matcher;
  875. while (ancestor = ancestor.parent) if (isMatchable(ancestor) && comparePathParserScore(matcher, ancestor) === 0) return ancestor;
  876. }
  877. /**
  878. * Checks if a matcher can be reachable. This means if it's possible to reach it as a route. For example, routes without
  879. * a component, or name, or redirect, are just used to group other routes.
  880. * @param matcher
  881. * @param matcher.record record of the matcher
  882. * @returns
  883. */
  884. function isMatchable({ record }) {
  885. return !!(record.name || record.components && Object.keys(record.components).length || record.redirect);
  886. }
  887. //#endregion
  888. //#region src/RouterLink.ts
  889. /**
  890. * Returns the internal behavior of a {@link RouterLink} without the rendering part.
  891. *
  892. * @param props - a `to` location and an optional `replace` flag
  893. */
  894. function useLink(props) {
  895. const router = inject(routerKey);
  896. const currentRoute = inject(routeLocationKey);
  897. let hasPrevious = false;
  898. let previousTo = null;
  899. const route = computed(() => {
  900. const to = unref(props.to);
  901. if (process.env.NODE_ENV !== "production" && (!hasPrevious || to !== previousTo)) {
  902. if (!isRouteLocation(to)) if (hasPrevious) warn$1(`Invalid value for prop "to" in useLink()\n- to:`, to, `\n- previous to:`, previousTo, `\n- props:`, props);
  903. else warn$1(`Invalid value for prop "to" in useLink()\n- to:`, to, `\n- props:`, props);
  904. previousTo = to;
  905. hasPrevious = true;
  906. }
  907. return router.resolve(to);
  908. });
  909. const activeRecordIndex = computed(() => {
  910. const { matched } = route.value;
  911. const { length } = matched;
  912. const routeMatched = matched[length - 1];
  913. const currentMatched = currentRoute.matched;
  914. if (!routeMatched || !currentMatched.length) return -1;
  915. const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
  916. if (index > -1) return index;
  917. const parentRecordPath = getOriginalPath(matched[length - 2]);
  918. return length > 1 && getOriginalPath(routeMatched) === parentRecordPath && currentMatched[currentMatched.length - 1].path !== parentRecordPath ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) : index;
  919. });
  920. const isActive = computed(() => activeRecordIndex.value > -1 && includesParams(currentRoute.params, route.value.params));
  921. const isExactActive = computed(() => activeRecordIndex.value > -1 && activeRecordIndex.value === currentRoute.matched.length - 1 && isSameRouteLocationParams(currentRoute.params, route.value.params));
  922. function navigate(e = {}) {
  923. if (guardEvent(e)) {
  924. const p = router[unref(props.replace) ? "replace" : "push"](unref(props.to)).catch(noop);
  925. if (props.viewTransition && typeof document !== "undefined" && "startViewTransition" in document) document.startViewTransition(() => p);
  926. return p;
  927. }
  928. return Promise.resolve();
  929. }
  930. if ((process.env.NODE_ENV !== "production" || __VUE_PROD_DEVTOOLS__) && isBrowser) {
  931. const instance = getCurrentInstance();
  932. if (instance) {
  933. const linkContextDevtools = {
  934. route: route.value,
  935. isActive: isActive.value,
  936. isExactActive: isExactActive.value,
  937. error: null
  938. };
  939. instance.__vrl_devtools = instance.__vrl_devtools || [];
  940. instance.__vrl_devtools.push(linkContextDevtools);
  941. watchEffect(() => {
  942. linkContextDevtools.route = route.value;
  943. linkContextDevtools.isActive = isActive.value;
  944. linkContextDevtools.isExactActive = isExactActive.value;
  945. linkContextDevtools.error = isRouteLocation(unref(props.to)) ? null : "Invalid \"to\" value";
  946. }, { flush: "post" });
  947. }
  948. }
  949. /**
  950. * NOTE: update {@link _RouterLinkI}'s `$slots` type when updating this
  951. */
  952. return {
  953. route,
  954. href: computed(() => route.value.href),
  955. isActive,
  956. isExactActive,
  957. navigate
  958. };
  959. }
  960. function preferSingleVNode(vnodes) {
  961. return vnodes.length === 1 ? vnodes[0] : vnodes;
  962. }
  963. const RouterLinkImpl = /* @__PURE__ */ defineComponent({
  964. name: "RouterLink",
  965. compatConfig: { MODE: 3 },
  966. props: {
  967. to: {
  968. type: [String, Object],
  969. required: true
  970. },
  971. replace: Boolean,
  972. activeClass: String,
  973. exactActiveClass: String,
  974. custom: Boolean,
  975. ariaCurrentValue: {
  976. type: String,
  977. default: "page"
  978. },
  979. viewTransition: Boolean
  980. },
  981. useLink,
  982. setup(props, { slots }) {
  983. const link = reactive(useLink(props));
  984. const { options } = inject(routerKey);
  985. const elClass = computed(() => ({
  986. [getLinkClass(props.activeClass, options.linkActiveClass, "router-link-active")]: link.isActive,
  987. [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, "router-link-exact-active")]: link.isExactActive
  988. }));
  989. return () => {
  990. const children = slots.default && preferSingleVNode(slots.default(link));
  991. return props.custom ? children : h("a", {
  992. "aria-current": link.isExactActive ? props.ariaCurrentValue : null,
  993. href: link.href,
  994. onClick: link.navigate,
  995. class: elClass.value
  996. }, children);
  997. };
  998. }
  999. });
  1000. /**
  1001. * Component to render a link that triggers a navigation on click.
  1002. */
  1003. const RouterLink = RouterLinkImpl;
  1004. function guardEvent(e) {
  1005. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;
  1006. if (e.defaultPrevented) return;
  1007. if (e.button !== void 0 && e.button !== 0) return;
  1008. if (e.currentTarget && e.currentTarget.getAttribute) {
  1009. const target = e.currentTarget.getAttribute("target");
  1010. if (/\b_blank\b/i.test(target)) return;
  1011. }
  1012. if (e.preventDefault) e.preventDefault();
  1013. return true;
  1014. }
  1015. function includesParams(outer, inner) {
  1016. for (const key in inner) {
  1017. const innerValue = inner[key];
  1018. const outerValue = outer[key];
  1019. if (typeof innerValue === "string") {
  1020. if (innerValue !== outerValue) return false;
  1021. } else if (!isArray(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value !== outerValue[i])) return false;
  1022. }
  1023. return true;
  1024. }
  1025. /**
  1026. * Get the original path value of a record by following its aliasOf
  1027. * @param record
  1028. */
  1029. function getOriginalPath(record) {
  1030. return record ? record.aliasOf ? record.aliasOf.path : record.path : "";
  1031. }
  1032. /**
  1033. * Utility class to get the active class based on defaults.
  1034. * @param propClass
  1035. * @param globalClass
  1036. * @param defaultClass
  1037. */
  1038. const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null ? propClass : globalClass != null ? globalClass : defaultClass;
  1039. //#endregion
  1040. //#region src/RouterView.ts
  1041. const RouterViewImpl = /* @__PURE__ */ defineComponent({
  1042. name: "RouterView",
  1043. inheritAttrs: false,
  1044. props: {
  1045. name: {
  1046. type: String,
  1047. default: "default"
  1048. },
  1049. route: Object
  1050. },
  1051. compatConfig: { MODE: 3 },
  1052. setup(props, { attrs, slots }) {
  1053. process.env.NODE_ENV !== "production" && warnDeprecatedUsage();
  1054. const injectedRoute = inject(routerViewLocationKey);
  1055. const routeToDisplay = computed(() => props.route || injectedRoute.value);
  1056. const injectedDepth = inject(viewDepthKey, 0);
  1057. const depth = computed(() => {
  1058. let initialDepth = unref(injectedDepth);
  1059. const { matched } = routeToDisplay.value;
  1060. let matchedRoute;
  1061. while ((matchedRoute = matched[initialDepth]) && !matchedRoute.components) initialDepth++;
  1062. return initialDepth;
  1063. });
  1064. const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth.value]);
  1065. provide(viewDepthKey, computed(() => depth.value + 1));
  1066. provide(matchedRouteKey, matchedRouteRef);
  1067. provide(routerViewLocationKey, routeToDisplay);
  1068. const viewRef = ref();
  1069. watch(() => [
  1070. viewRef.value,
  1071. matchedRouteRef.value,
  1072. props.name
  1073. ], ([instance, to, name], [oldInstance, from, oldName]) => {
  1074. if (to) {
  1075. to.instances[name] = instance;
  1076. if (from && from !== to && instance && instance === oldInstance) {
  1077. if (!to.leaveGuards.size) to.leaveGuards = from.leaveGuards;
  1078. if (!to.updateGuards.size) to.updateGuards = from.updateGuards;
  1079. }
  1080. }
  1081. if (instance && to && (!from || !isSameRouteRecord(to, from) || !oldInstance)) (to.enterCallbacks[name] || []).forEach((callback) => callback(instance));
  1082. }, { flush: "post" });
  1083. return () => {
  1084. const route = routeToDisplay.value;
  1085. const currentName = props.name;
  1086. const matchedRoute = matchedRouteRef.value;
  1087. const ViewComponent = matchedRoute && matchedRoute.components[currentName];
  1088. if (!ViewComponent) return normalizeSlot(slots.default, {
  1089. Component: ViewComponent,
  1090. route
  1091. });
  1092. const routePropsOption = matchedRoute.props[currentName];
  1093. const routeProps = routePropsOption ? routePropsOption === true ? route.params : typeof routePropsOption === "function" ? routePropsOption(route) : routePropsOption : null;
  1094. const onVnodeUnmounted = (vnode) => {
  1095. if (vnode.component.isUnmounted) matchedRoute.instances[currentName] = null;
  1096. };
  1097. const component = h(ViewComponent, assign({}, routeProps, attrs, {
  1098. onVnodeUnmounted,
  1099. ref: viewRef
  1100. }));
  1101. if ((process.env.NODE_ENV !== "production" || __VUE_PROD_DEVTOOLS__) && isBrowser && component.ref) {
  1102. const info = {
  1103. depth: depth.value,
  1104. name: matchedRoute.name,
  1105. path: matchedRoute.path,
  1106. meta: matchedRoute.meta
  1107. };
  1108. (isArray(component.ref) ? component.ref.map((r) => r.i) : [component.ref.i]).forEach((instance) => {
  1109. instance.__vrv_devtools = info;
  1110. });
  1111. }
  1112. return normalizeSlot(slots.default, {
  1113. Component: component,
  1114. route
  1115. }) || component;
  1116. };
  1117. }
  1118. });
  1119. function normalizeSlot(slot, data) {
  1120. if (!slot) return null;
  1121. const slotContent = slot(data);
  1122. return slotContent.length === 1 ? slotContent[0] : slotContent;
  1123. }
  1124. /**
  1125. * Component to display the current route the user is at.
  1126. */
  1127. const RouterView = RouterViewImpl;
  1128. function warnDeprecatedUsage() {
  1129. const instance = getCurrentInstance();
  1130. const parentName = instance.parent && instance.parent.type.name;
  1131. const parentSubTreeType = instance.parent && instance.parent.subTree && instance.parent.subTree.type;
  1132. if (parentName && (parentName === "KeepAlive" || parentName.includes("Transition")) && typeof parentSubTreeType === "object" && parentSubTreeType.name === "RouterView") {
  1133. const comp = parentName === "KeepAlive" ? "keep-alive" : "transition";
  1134. warn$1(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.
  1135. Use slot props instead:
  1136. <router-view v-slot="{ Component }">
  1137. <${comp}>\n <component :is="Component" />\n </${comp}>\n</router-view>`);
  1138. }
  1139. }
  1140. //#endregion
  1141. //#region src/router.ts
  1142. /**
  1143. * Creates a Router instance that can be used by a Vue app.
  1144. *
  1145. * @param options - {@link RouterOptions}
  1146. */
  1147. function createRouter(options) {
  1148. const matcher = createRouterMatcher(options.routes, options);
  1149. const parseQuery$1 = options.parseQuery || parseQuery;
  1150. const stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
  1151. const routerHistory = options.history;
  1152. if (process.env.NODE_ENV !== "production" && !routerHistory) throw new Error("Provide the \"history\" option when calling \"createRouter()\": https://router.vuejs.org/api/interfaces/RouterOptions.html#history");
  1153. const beforeGuards = useCallbacks();
  1154. const beforeResolveGuards = useCallbacks();
  1155. const afterGuards = useCallbacks();
  1156. const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
  1157. let pendingLocation = START_LOCATION_NORMALIZED;
  1158. if (isBrowser && options.scrollBehavior && "scrollRestoration" in history) history.scrollRestoration = "manual";
  1159. const normalizeParams = applyToParams.bind(null, (paramValue) => "" + paramValue);
  1160. const encodeParams = applyToParams.bind(null, encodeParam);
  1161. const decodeParams = applyToParams.bind(null, decode);
  1162. function addRoute(parentOrRoute, route) {
  1163. let parent;
  1164. let record;
  1165. if (isRouteName(parentOrRoute)) {
  1166. parent = matcher.getRecordMatcher(parentOrRoute);
  1167. if (process.env.NODE_ENV !== "production" && !parent) warn$1(`Parent route "${String(parentOrRoute)}" not found when adding child route`, route);
  1168. record = route;
  1169. } else record = parentOrRoute;
  1170. return matcher.addRoute(record, parent);
  1171. }
  1172. function removeRoute(name) {
  1173. const recordMatcher = matcher.getRecordMatcher(name);
  1174. if (recordMatcher) matcher.removeRoute(recordMatcher);
  1175. else if (process.env.NODE_ENV !== "production") warn$1(`Cannot remove non-existent route "${String(name)}"`);
  1176. }
  1177. function getRoutes() {
  1178. return matcher.getRoutes().map((routeMatcher) => routeMatcher.record);
  1179. }
  1180. function hasRoute(name) {
  1181. return !!matcher.getRecordMatcher(name);
  1182. }
  1183. function resolve(rawLocation, currentLocation) {
  1184. currentLocation = assign({}, currentLocation || currentRoute.value);
  1185. if (typeof rawLocation === "string") {
  1186. const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
  1187. const matchedRoute$1 = matcher.resolve({ path: locationNormalized.path }, currentLocation);
  1188. const href$1 = routerHistory.createHref(locationNormalized.fullPath);
  1189. if (process.env.NODE_ENV !== "production") {
  1190. if (href$1.startsWith("//")) warn$1(`Location "${rawLocation}" resolved to "${href$1}". A resolved location cannot start with multiple slashes.`);
  1191. else if (!matchedRoute$1.matched.length) warn$1(`No match found for location with path "${rawLocation}"`);
  1192. }
  1193. return assign(locationNormalized, matchedRoute$1, {
  1194. params: decodeParams(matchedRoute$1.params),
  1195. hash: decode(locationNormalized.hash),
  1196. redirectedFrom: void 0,
  1197. href: href$1
  1198. });
  1199. }
  1200. if (process.env.NODE_ENV !== "production" && !isRouteLocation(rawLocation)) {
  1201. warn$1(`router.resolve() was passed an invalid location. This will fail in production.\n- Location:`, rawLocation);
  1202. return resolve({});
  1203. }
  1204. let matcherLocation;
  1205. if (rawLocation.path != null) {
  1206. if (process.env.NODE_ENV !== "production" && "params" in rawLocation && !("name" in rawLocation) && Object.keys(rawLocation.params).length) warn$1(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
  1207. matcherLocation = assign({}, rawLocation, { path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path });
  1208. } else {
  1209. const targetParams = assign({}, rawLocation.params);
  1210. for (const key in targetParams) if (targetParams[key] == null) delete targetParams[key];
  1211. matcherLocation = assign({}, rawLocation, { params: encodeParams(targetParams) });
  1212. currentLocation.params = encodeParams(currentLocation.params);
  1213. }
  1214. const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
  1215. const hash = rawLocation.hash || "";
  1216. if (process.env.NODE_ENV !== "production" && hash && !hash.startsWith("#")) warn$1(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
  1217. matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
  1218. const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
  1219. hash: encodeHash(hash),
  1220. path: matchedRoute.path
  1221. }));
  1222. const href = routerHistory.createHref(fullPath);
  1223. if (process.env.NODE_ENV !== "production") {
  1224. if (href.startsWith("//")) warn$1(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
  1225. else if (!matchedRoute.matched.length) warn$1(`No match found for location with path "${rawLocation.path != null ? rawLocation.path : rawLocation}"`);
  1226. }
  1227. return assign({
  1228. fullPath,
  1229. hash,
  1230. query: stringifyQuery$1 === stringifyQuery ? normalizeQuery(rawLocation.query) : rawLocation.query || {}
  1231. }, matchedRoute, {
  1232. redirectedFrom: void 0,
  1233. href
  1234. });
  1235. }
  1236. function locationAsObject(to) {
  1237. return typeof to === "string" ? parseURL(parseQuery$1, to, currentRoute.value.path) : assign({}, to);
  1238. }
  1239. function checkCanceledNavigation(to, from) {
  1240. if (pendingLocation !== to) return createRouterError(ErrorTypes.NAVIGATION_CANCELLED, {
  1241. from,
  1242. to
  1243. });
  1244. }
  1245. function push(to) {
  1246. return pushWithRedirect(to);
  1247. }
  1248. function replace(to) {
  1249. return push(assign(locationAsObject(to), { replace: true }));
  1250. }
  1251. function handleRedirectRecord(to, from) {
  1252. const lastMatched = to.matched[to.matched.length - 1];
  1253. if (lastMatched && lastMatched.redirect) {
  1254. const { redirect } = lastMatched;
  1255. let newTargetLocation = typeof redirect === "function" ? redirect(to, from) : redirect;
  1256. if (typeof newTargetLocation === "string") {
  1257. newTargetLocation = newTargetLocation.includes("?") || newTargetLocation.includes("#") ? newTargetLocation = locationAsObject(newTargetLocation) : { path: newTargetLocation };
  1258. newTargetLocation.params = {};
  1259. }
  1260. if (process.env.NODE_ENV !== "production" && newTargetLocation.path == null && !("name" in newTargetLocation)) {
  1261. warn$1(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
  1262. throw new Error("Invalid redirect");
  1263. }
  1264. return assign({
  1265. query: to.query,
  1266. hash: to.hash,
  1267. params: newTargetLocation.path != null ? {} : to.params
  1268. }, newTargetLocation);
  1269. }
  1270. }
  1271. function pushWithRedirect(to, redirectedFrom) {
  1272. const targetLocation = pendingLocation = resolve(to);
  1273. const from = currentRoute.value;
  1274. const data = to.state;
  1275. const force = to.force;
  1276. const replace$1 = to.replace === true;
  1277. const shouldRedirect = handleRedirectRecord(targetLocation, from);
  1278. if (shouldRedirect) return pushWithRedirect(assign(locationAsObject(shouldRedirect), {
  1279. state: typeof shouldRedirect === "object" ? assign({}, data, shouldRedirect.state) : data,
  1280. force,
  1281. replace: replace$1
  1282. }), redirectedFrom || targetLocation);
  1283. const toLocation = targetLocation;
  1284. toLocation.redirectedFrom = redirectedFrom;
  1285. let failure;
  1286. if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
  1287. failure = createRouterError(ErrorTypes.NAVIGATION_DUPLICATED, {
  1288. to: toLocation,
  1289. from
  1290. });
  1291. handleScroll(from, from, true, false);
  1292. }
  1293. return (failure ? Promise.resolve(failure) : navigate(toLocation, from)).catch((error) => isNavigationFailure(error) ? isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT) ? error : markAsReady(error) : triggerError(error, toLocation, from)).then((failure$1) => {
  1294. if (failure$1) {
  1295. if (isNavigationFailure(failure$1, ErrorTypes.NAVIGATION_GUARD_REDIRECT)) {
  1296. if (process.env.NODE_ENV !== "production" && isSameRouteLocation(stringifyQuery$1, resolve(failure$1.to), toLocation) && redirectedFrom && (redirectedFrom._count = redirectedFrom._count ? redirectedFrom._count + 1 : 1) > 30) {
  1297. warn$1(`Detected a possibly infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow.\n Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.`);
  1298. return Promise.reject(/* @__PURE__ */ new Error("Infinite redirect in navigation guard"));
  1299. }
  1300. return pushWithRedirect(assign({ replace: replace$1 }, locationAsObject(failure$1.to), {
  1301. state: typeof failure$1.to === "object" ? assign({}, data, failure$1.to.state) : data,
  1302. force
  1303. }), redirectedFrom || toLocation);
  1304. }
  1305. } else failure$1 = finalizeNavigation(toLocation, from, true, replace$1, data);
  1306. triggerAfterEach(toLocation, from, failure$1);
  1307. return failure$1;
  1308. });
  1309. }
  1310. /**
  1311. * Helper to reject and skip all navigation guards if a new navigation happened
  1312. * @param to
  1313. * @param from
  1314. */
  1315. function checkCanceledNavigationAndReject(to, from) {
  1316. const error = checkCanceledNavigation(to, from);
  1317. return error ? Promise.reject(error) : Promise.resolve();
  1318. }
  1319. function runWithContext(fn) {
  1320. const app = installedApps.values().next().value;
  1321. return app && typeof app.runWithContext === "function" ? app.runWithContext(fn) : fn();
  1322. }
  1323. function navigate(to, from) {
  1324. let guards;
  1325. const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from);
  1326. guards = extractComponentsGuards(leavingRecords.reverse(), "beforeRouteLeave", to, from);
  1327. for (const record of leavingRecords) record.leaveGuards.forEach((guard) => {
  1328. guards.push(guardToPromiseFn(guard, to, from));
  1329. });
  1330. const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
  1331. guards.push(canceledNavigationCheck);
  1332. return runGuardQueue(guards).then(() => {
  1333. guards = [];
  1334. for (const guard of beforeGuards.list()) guards.push(guardToPromiseFn(guard, to, from));
  1335. guards.push(canceledNavigationCheck);
  1336. return runGuardQueue(guards);
  1337. }).then(() => {
  1338. guards = extractComponentsGuards(updatingRecords, "beforeRouteUpdate", to, from);
  1339. for (const record of updatingRecords) record.updateGuards.forEach((guard) => {
  1340. guards.push(guardToPromiseFn(guard, to, from));
  1341. });
  1342. guards.push(canceledNavigationCheck);
  1343. return runGuardQueue(guards);
  1344. }).then(() => {
  1345. guards = [];
  1346. for (const record of enteringRecords) if (record.beforeEnter) if (isArray(record.beforeEnter)) for (const beforeEnter of record.beforeEnter) guards.push(guardToPromiseFn(beforeEnter, to, from));
  1347. else guards.push(guardToPromiseFn(record.beforeEnter, to, from));
  1348. guards.push(canceledNavigationCheck);
  1349. return runGuardQueue(guards);
  1350. }).then(() => {
  1351. to.matched.forEach((record) => record.enterCallbacks = {});
  1352. guards = extractComponentsGuards(enteringRecords, "beforeRouteEnter", to, from, runWithContext);
  1353. guards.push(canceledNavigationCheck);
  1354. return runGuardQueue(guards);
  1355. }).then(() => {
  1356. guards = [];
  1357. for (const guard of beforeResolveGuards.list()) guards.push(guardToPromiseFn(guard, to, from));
  1358. guards.push(canceledNavigationCheck);
  1359. return runGuardQueue(guards);
  1360. }).catch((err) => isNavigationFailure(err, ErrorTypes.NAVIGATION_CANCELLED) ? err : Promise.reject(err));
  1361. }
  1362. function triggerAfterEach(to, from, failure) {
  1363. afterGuards.list().forEach((guard) => runWithContext(() => guard(to, from, failure)));
  1364. }
  1365. /**
  1366. * - Cleans up any navigation guards
  1367. * - Changes the url if necessary
  1368. * - Calls the scrollBehavior
  1369. */
  1370. function finalizeNavigation(toLocation, from, isPush, replace$1, data) {
  1371. const error = checkCanceledNavigation(toLocation, from);
  1372. if (error) return error;
  1373. const isFirstNavigation = from === START_LOCATION_NORMALIZED;
  1374. const state = !isBrowser ? {} : history.state;
  1375. if (isPush) if (replace$1 || isFirstNavigation) routerHistory.replace(toLocation.fullPath, assign({ scroll: isFirstNavigation && state && state.scroll }, data));
  1376. else routerHistory.push(toLocation.fullPath, data);
  1377. currentRoute.value = toLocation;
  1378. handleScroll(toLocation, from, isPush, isFirstNavigation);
  1379. markAsReady();
  1380. }
  1381. let removeHistoryListener;
  1382. function setupListeners() {
  1383. if (removeHistoryListener) return;
  1384. removeHistoryListener = routerHistory.listen((to, _from, info) => {
  1385. if (!router.listening) return;
  1386. const toLocation = resolve(to);
  1387. const shouldRedirect = handleRedirectRecord(toLocation, router.currentRoute.value);
  1388. if (shouldRedirect) {
  1389. pushWithRedirect(assign(shouldRedirect, {
  1390. replace: true,
  1391. force: true
  1392. }), toLocation).catch(noop);
  1393. return;
  1394. }
  1395. pendingLocation = toLocation;
  1396. const from = currentRoute.value;
  1397. if (isBrowser) saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
  1398. navigate(toLocation, from).catch((error) => {
  1399. if (isNavigationFailure(error, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_CANCELLED)) return error;
  1400. if (isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT)) {
  1401. pushWithRedirect(assign(locationAsObject(error.to), { force: true }), toLocation).then((failure) => {
  1402. if (isNavigationFailure(failure, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED) && !info.delta && info.type === NavigationType.pop) routerHistory.go(-1, false);
  1403. }).catch(noop);
  1404. return Promise.reject();
  1405. }
  1406. if (info.delta) routerHistory.go(-info.delta, false);
  1407. return triggerError(error, toLocation, from);
  1408. }).then((failure) => {
  1409. failure = failure || finalizeNavigation(toLocation, from, false);
  1410. if (failure) {
  1411. if (info.delta && !isNavigationFailure(failure, ErrorTypes.NAVIGATION_CANCELLED)) routerHistory.go(-info.delta, false);
  1412. else if (info.type === NavigationType.pop && isNavigationFailure(failure, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED)) routerHistory.go(-1, false);
  1413. }
  1414. triggerAfterEach(toLocation, from, failure);
  1415. }).catch(noop);
  1416. });
  1417. }
  1418. let readyHandlers = useCallbacks();
  1419. let errorListeners = useCallbacks();
  1420. let ready;
  1421. /**
  1422. * Trigger errorListeners added via onError and throws the error as well
  1423. *
  1424. * @param error - error to throw
  1425. * @param to - location we were navigating to when the error happened
  1426. * @param from - location we were navigating from when the error happened
  1427. * @returns the error as a rejected promise
  1428. */
  1429. function triggerError(error, to, from) {
  1430. markAsReady(error);
  1431. const list = errorListeners.list();
  1432. if (list.length) list.forEach((handler) => handler(error, to, from));
  1433. else {
  1434. if (process.env.NODE_ENV !== "production") warn$1("uncaught error during route navigation:");
  1435. console.error(error);
  1436. }
  1437. return Promise.reject(error);
  1438. }
  1439. function isReady() {
  1440. if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) return Promise.resolve();
  1441. return new Promise((resolve$1, reject) => {
  1442. readyHandlers.add([resolve$1, reject]);
  1443. });
  1444. }
  1445. function markAsReady(err) {
  1446. if (!ready) {
  1447. ready = !err;
  1448. setupListeners();
  1449. readyHandlers.list().forEach(([resolve$1, reject]) => err ? reject(err) : resolve$1());
  1450. readyHandlers.reset();
  1451. }
  1452. return err;
  1453. }
  1454. function handleScroll(to, from, isPush, isFirstNavigation) {
  1455. const { scrollBehavior } = options;
  1456. if (!isBrowser || !scrollBehavior) return Promise.resolve();
  1457. const scrollPosition = !isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0)) || (isFirstNavigation || !isPush) && history.state && history.state.scroll || null;
  1458. return nextTick().then(() => scrollBehavior(to, from, scrollPosition)).then((position) => position && scrollToPosition(position)).catch((err) => triggerError(err, to, from));
  1459. }
  1460. const go = (delta) => routerHistory.go(delta);
  1461. let started;
  1462. const installedApps = /* @__PURE__ */ new Set();
  1463. const router = {
  1464. currentRoute,
  1465. listening: true,
  1466. addRoute,
  1467. removeRoute,
  1468. clearRoutes: matcher.clearRoutes,
  1469. hasRoute,
  1470. getRoutes,
  1471. resolve,
  1472. options,
  1473. push,
  1474. replace,
  1475. go,
  1476. back: () => go(-1),
  1477. forward: () => go(1),
  1478. beforeEach: beforeGuards.add,
  1479. beforeResolve: beforeResolveGuards.add,
  1480. afterEach: afterGuards.add,
  1481. onError: errorListeners.add,
  1482. isReady,
  1483. install(app) {
  1484. app.component("RouterLink", RouterLink);
  1485. app.component("RouterView", RouterView);
  1486. app.config.globalProperties.$router = router;
  1487. Object.defineProperty(app.config.globalProperties, "$route", {
  1488. enumerable: true,
  1489. get: () => unref(currentRoute)
  1490. });
  1491. if (isBrowser && !started && currentRoute.value === START_LOCATION_NORMALIZED) {
  1492. started = true;
  1493. push(routerHistory.location).catch((err) => {
  1494. if (process.env.NODE_ENV !== "production") warn$1("Unexpected error when starting the router:", err);
  1495. });
  1496. }
  1497. const reactiveRoute = {};
  1498. for (const key in START_LOCATION_NORMALIZED) Object.defineProperty(reactiveRoute, key, {
  1499. get: () => currentRoute.value[key],
  1500. enumerable: true
  1501. });
  1502. app.provide(routerKey, router);
  1503. app.provide(routeLocationKey, shallowReactive(reactiveRoute));
  1504. app.provide(routerViewLocationKey, currentRoute);
  1505. const unmountApp = app.unmount;
  1506. installedApps.add(app);
  1507. app.unmount = function() {
  1508. installedApps.delete(app);
  1509. if (installedApps.size < 1) {
  1510. pendingLocation = START_LOCATION_NORMALIZED;
  1511. removeHistoryListener && removeHistoryListener();
  1512. removeHistoryListener = null;
  1513. currentRoute.value = START_LOCATION_NORMALIZED;
  1514. started = false;
  1515. ready = false;
  1516. }
  1517. unmountApp();
  1518. };
  1519. if ((process.env.NODE_ENV !== "production" || __VUE_PROD_DEVTOOLS__) && isBrowser) addDevtools(app, router, matcher);
  1520. }
  1521. };
  1522. function runGuardQueue(guards) {
  1523. return guards.reduce((promise, guard) => promise.then(() => runWithContext(guard)), Promise.resolve());
  1524. }
  1525. return router;
  1526. }
  1527. //#endregion
  1528. //#region src/useApi.ts
  1529. /**
  1530. * Returns the router instance. Equivalent to using `$router` inside
  1531. * templates.
  1532. */
  1533. function useRouter() {
  1534. return inject(routerKey);
  1535. }
  1536. /**
  1537. * Returns the current route location. Equivalent to using `$route` inside
  1538. * templates.
  1539. */
  1540. function useRoute(_name) {
  1541. return inject(routeLocationKey);
  1542. }
  1543. //#endregion
  1544. export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, loadRouteLocation, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey };