vue-router.prod.cjs 112 KB

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