vue-router.esm-browser.js 141 KB

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