vue-router.global.js 113 KB

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