vue-router.cjs.js 137 KB

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