vue-router.prod.cjs 109 KB

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