vue-router.prod.cjs 107 KB

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