vue-router.prod.cjs 111 KB

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