vue-router.cjs 144 KB

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