vue-router.cjs.prod.js 106 KB

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