vue-router.js 103 KB

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