vue-router.common.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140
  1. /*!
  2. * vue-router v3.5.1
  3. * (c) 2021 Evan You
  4. * @license MIT
  5. */
  6. 'use strict';
  7. /* */
  8. function assert (condition, message) {
  9. if (!condition) {
  10. throw new Error(("[vue-router] " + message))
  11. }
  12. }
  13. function warn (condition, message) {
  14. if (process.env.NODE_ENV !== 'production' && !condition) {
  15. typeof console !== 'undefined' && console.warn(("[vue-router] " + message));
  16. }
  17. }
  18. function extend (a, b) {
  19. for (var key in b) {
  20. a[key] = b[key];
  21. }
  22. return a
  23. }
  24. /* */
  25. var encodeReserveRE = /[!'()*]/g;
  26. var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
  27. var commaRE = /%2C/g;
  28. // fixed encodeURIComponent which is more conformant to RFC3986:
  29. // - escapes [!'()*]
  30. // - preserve commas
  31. var encode = function (str) { return encodeURIComponent(str)
  32. .replace(encodeReserveRE, encodeReserveReplacer)
  33. .replace(commaRE, ','); };
  34. function decode (str) {
  35. try {
  36. return decodeURIComponent(str)
  37. } catch (err) {
  38. if (process.env.NODE_ENV !== 'production') {
  39. warn(false, ("Error decoding \"" + str + "\". Leaving it intact."));
  40. }
  41. }
  42. return str
  43. }
  44. function resolveQuery (
  45. query,
  46. extraQuery,
  47. _parseQuery
  48. ) {
  49. if ( extraQuery === void 0 ) extraQuery = {};
  50. var parse = _parseQuery || parseQuery;
  51. var parsedQuery;
  52. try {
  53. parsedQuery = parse(query || '');
  54. } catch (e) {
  55. process.env.NODE_ENV !== 'production' && warn(false, e.message);
  56. parsedQuery = {};
  57. }
  58. for (var key in extraQuery) {
  59. var value = extraQuery[key];
  60. parsedQuery[key] = Array.isArray(value)
  61. ? value.map(castQueryParamValue)
  62. : castQueryParamValue(value);
  63. }
  64. return parsedQuery
  65. }
  66. var castQueryParamValue = function (value) { return (value == null || typeof value === 'object' ? value : String(value)); };
  67. function parseQuery (query) {
  68. var res = {};
  69. query = query.trim().replace(/^(\?|#|&)/, '');
  70. if (!query) {
  71. return res
  72. }
  73. query.split('&').forEach(function (param) {
  74. var parts = param.replace(/\+/g, ' ').split('=');
  75. var key = decode(parts.shift());
  76. var val = parts.length > 0 ? decode(parts.join('=')) : null;
  77. if (res[key] === undefined) {
  78. res[key] = val;
  79. } else if (Array.isArray(res[key])) {
  80. res[key].push(val);
  81. } else {
  82. res[key] = [res[key], val];
  83. }
  84. });
  85. return res
  86. }
  87. function stringifyQuery (obj) {
  88. var res = obj
  89. ? Object.keys(obj)
  90. .map(function (key) {
  91. var val = obj[key];
  92. if (val === undefined) {
  93. return ''
  94. }
  95. if (val === null) {
  96. return encode(key)
  97. }
  98. if (Array.isArray(val)) {
  99. var result = [];
  100. val.forEach(function (val2) {
  101. if (val2 === undefined) {
  102. return
  103. }
  104. if (val2 === null) {
  105. result.push(encode(key));
  106. } else {
  107. result.push(encode(key) + '=' + encode(val2));
  108. }
  109. });
  110. return result.join('&')
  111. }
  112. return encode(key) + '=' + encode(val)
  113. })
  114. .filter(function (x) { return x.length > 0; })
  115. .join('&')
  116. : null;
  117. return res ? ("?" + res) : ''
  118. }
  119. /* */
  120. var trailingSlashRE = /\/?$/;
  121. function createRoute (
  122. record,
  123. location,
  124. redirectedFrom,
  125. router
  126. ) {
  127. var stringifyQuery = router && router.options.stringifyQuery;
  128. var query = location.query || {};
  129. try {
  130. query = clone(query);
  131. } catch (e) {}
  132. var route = {
  133. name: location.name || (record && record.name),
  134. meta: (record && record.meta) || {},
  135. path: location.path || '/',
  136. hash: location.hash || '',
  137. query: query,
  138. params: location.params || {},
  139. fullPath: getFullPath(location, stringifyQuery),
  140. matched: record ? formatMatch(record) : []
  141. };
  142. if (redirectedFrom) {
  143. route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
  144. }
  145. return Object.freeze(route)
  146. }
  147. function clone (value) {
  148. if (Array.isArray(value)) {
  149. return value.map(clone)
  150. } else if (value && typeof value === 'object') {
  151. var res = {};
  152. for (var key in value) {
  153. res[key] = clone(value[key]);
  154. }
  155. return res
  156. } else {
  157. return value
  158. }
  159. }
  160. // the starting route that represents the initial state
  161. var START = createRoute(null, {
  162. path: '/'
  163. });
  164. function formatMatch (record) {
  165. var res = [];
  166. while (record) {
  167. res.unshift(record);
  168. record = record.parent;
  169. }
  170. return res
  171. }
  172. function getFullPath (
  173. ref,
  174. _stringifyQuery
  175. ) {
  176. var path = ref.path;
  177. var query = ref.query; if ( query === void 0 ) query = {};
  178. var hash = ref.hash; if ( hash === void 0 ) hash = '';
  179. var stringify = _stringifyQuery || stringifyQuery;
  180. return (path || '/') + stringify(query) + hash
  181. }
  182. function isSameRoute (a, b, onlyPath) {
  183. if (b === START) {
  184. return a === b
  185. } else if (!b) {
  186. return false
  187. } else if (a.path && b.path) {
  188. return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
  189. a.hash === b.hash &&
  190. isObjectEqual(a.query, b.query))
  191. } else if (a.name && b.name) {
  192. return (
  193. a.name === b.name &&
  194. (onlyPath || (
  195. a.hash === b.hash &&
  196. isObjectEqual(a.query, b.query) &&
  197. isObjectEqual(a.params, b.params))
  198. )
  199. )
  200. } else {
  201. return false
  202. }
  203. }
  204. function isObjectEqual (a, b) {
  205. if ( a === void 0 ) a = {};
  206. if ( b === void 0 ) b = {};
  207. // handle null value #1566
  208. if (!a || !b) { return a === b }
  209. var aKeys = Object.keys(a).sort();
  210. var bKeys = Object.keys(b).sort();
  211. if (aKeys.length !== bKeys.length) {
  212. return false
  213. }
  214. return aKeys.every(function (key, i) {
  215. var aVal = a[key];
  216. var bKey = bKeys[i];
  217. if (bKey !== key) { return false }
  218. var bVal = b[key];
  219. // query values can be null and undefined
  220. if (aVal == null || bVal == null) { return aVal === bVal }
  221. // check nested equality
  222. if (typeof aVal === 'object' && typeof bVal === 'object') {
  223. return isObjectEqual(aVal, bVal)
  224. }
  225. return String(aVal) === String(bVal)
  226. })
  227. }
  228. function isIncludedRoute (current, target) {
  229. return (
  230. current.path.replace(trailingSlashRE, '/').indexOf(
  231. target.path.replace(trailingSlashRE, '/')
  232. ) === 0 &&
  233. (!target.hash || current.hash === target.hash) &&
  234. queryIncludes(current.query, target.query)
  235. )
  236. }
  237. function queryIncludes (current, target) {
  238. for (var key in target) {
  239. if (!(key in current)) {
  240. return false
  241. }
  242. }
  243. return true
  244. }
  245. function handleRouteEntered (route) {
  246. for (var i = 0; i < route.matched.length; i++) {
  247. var record = route.matched[i];
  248. for (var name in record.instances) {
  249. var instance = record.instances[name];
  250. var cbs = record.enteredCbs[name];
  251. if (!instance || !cbs) { continue }
  252. delete record.enteredCbs[name];
  253. for (var i$1 = 0; i$1 < cbs.length; i$1++) {
  254. if (!instance._isBeingDestroyed) { cbs[i$1](instance); }
  255. }
  256. }
  257. }
  258. }
  259. var View = {
  260. name: 'RouterView',
  261. functional: true,
  262. props: {
  263. name: {
  264. type: String,
  265. default: 'default'
  266. }
  267. },
  268. render: function render (_, ref) {
  269. var props = ref.props;
  270. var children = ref.children;
  271. var parent = ref.parent;
  272. var data = ref.data;
  273. // used by devtools to display a router-view badge
  274. data.routerView = true;
  275. // directly use parent context's createElement() function
  276. // so that components rendered by router-view can resolve named slots
  277. var h = parent.$createElement;
  278. var name = props.name;
  279. var route = parent.$route;
  280. var cache = parent._routerViewCache || (parent._routerViewCache = {});
  281. // determine current view depth, also check to see if the tree
  282. // has been toggled inactive but kept-alive.
  283. var depth = 0;
  284. var inactive = false;
  285. while (parent && parent._routerRoot !== parent) {
  286. var vnodeData = parent.$vnode ? parent.$vnode.data : {};
  287. if (vnodeData.routerView) {
  288. depth++;
  289. }
  290. if (vnodeData.keepAlive && parent._directInactive && parent._inactive) {
  291. inactive = true;
  292. }
  293. parent = parent.$parent;
  294. }
  295. data.routerViewDepth = depth;
  296. // render previous view if the tree is inactive and kept-alive
  297. if (inactive) {
  298. var cachedData = cache[name];
  299. var cachedComponent = cachedData && cachedData.component;
  300. if (cachedComponent) {
  301. // #2301
  302. // pass props
  303. if (cachedData.configProps) {
  304. fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
  305. }
  306. return h(cachedComponent, data, children)
  307. } else {
  308. // render previous empty view
  309. return h()
  310. }
  311. }
  312. var matched = route.matched[depth];
  313. var component = matched && matched.components[name];
  314. // render empty node if no matched route or no config component
  315. if (!matched || !component) {
  316. cache[name] = null;
  317. return h()
  318. }
  319. // cache component
  320. cache[name] = { component: component };
  321. // attach instance registration hook
  322. // this will be called in the instance's injected lifecycle hooks
  323. data.registerRouteInstance = function (vm, val) {
  324. // val could be undefined for unregistration
  325. var current = matched.instances[name];
  326. if (
  327. (val && current !== vm) ||
  328. (!val && current === vm)
  329. ) {
  330. matched.instances[name] = val;
  331. }
  332. }
  333. // also register instance in prepatch hook
  334. // in case the same component instance is reused across different routes
  335. ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) {
  336. matched.instances[name] = vnode.componentInstance;
  337. };
  338. // register instance in init hook
  339. // in case kept-alive component be actived when routes changed
  340. data.hook.init = function (vnode) {
  341. if (vnode.data.keepAlive &&
  342. vnode.componentInstance &&
  343. vnode.componentInstance !== matched.instances[name]
  344. ) {
  345. matched.instances[name] = vnode.componentInstance;
  346. }
  347. // if the route transition has already been confirmed then we weren't
  348. // able to call the cbs during confirmation as the component was not
  349. // registered yet, so we call it here.
  350. handleRouteEntered(route);
  351. };
  352. var configProps = matched.props && matched.props[name];
  353. // save route and configProps in cache
  354. if (configProps) {
  355. extend(cache[name], {
  356. route: route,
  357. configProps: configProps
  358. });
  359. fillPropsinData(component, data, route, configProps);
  360. }
  361. return h(component, data, children)
  362. }
  363. };
  364. function fillPropsinData (component, data, route, configProps) {
  365. // resolve props
  366. var propsToPass = data.props = resolveProps(route, configProps);
  367. if (propsToPass) {
  368. // clone to prevent mutation
  369. propsToPass = data.props = extend({}, propsToPass);
  370. // pass non-declared props as attrs
  371. var attrs = data.attrs = data.attrs || {};
  372. for (var key in propsToPass) {
  373. if (!component.props || !(key in component.props)) {
  374. attrs[key] = propsToPass[key];
  375. delete propsToPass[key];
  376. }
  377. }
  378. }
  379. }
  380. function resolveProps (route, config) {
  381. switch (typeof config) {
  382. case 'undefined':
  383. return
  384. case 'object':
  385. return config
  386. case 'function':
  387. return config(route)
  388. case 'boolean':
  389. return config ? route.params : undefined
  390. default:
  391. if (process.env.NODE_ENV !== 'production') {
  392. warn(
  393. false,
  394. "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
  395. "expecting an object, function or boolean."
  396. );
  397. }
  398. }
  399. }
  400. /* */
  401. function resolvePath (
  402. relative,
  403. base,
  404. append
  405. ) {
  406. var firstChar = relative.charAt(0);
  407. if (firstChar === '/') {
  408. return relative
  409. }
  410. if (firstChar === '?' || firstChar === '#') {
  411. return base + relative
  412. }
  413. var stack = base.split('/');
  414. // remove trailing segment if:
  415. // - not appending
  416. // - appending to trailing slash (last segment is empty)
  417. if (!append || !stack[stack.length - 1]) {
  418. stack.pop();
  419. }
  420. // resolve relative path
  421. var segments = relative.replace(/^\//, '').split('/');
  422. for (var i = 0; i < segments.length; i++) {
  423. var segment = segments[i];
  424. if (segment === '..') {
  425. stack.pop();
  426. } else if (segment !== '.') {
  427. stack.push(segment);
  428. }
  429. }
  430. // ensure leading slash
  431. if (stack[0] !== '') {
  432. stack.unshift('');
  433. }
  434. return stack.join('/')
  435. }
  436. function parsePath (path) {
  437. var hash = '';
  438. var query = '';
  439. var hashIndex = path.indexOf('#');
  440. if (hashIndex >= 0) {
  441. hash = path.slice(hashIndex);
  442. path = path.slice(0, hashIndex);
  443. }
  444. var queryIndex = path.indexOf('?');
  445. if (queryIndex >= 0) {
  446. query = path.slice(queryIndex + 1);
  447. path = path.slice(0, queryIndex);
  448. }
  449. return {
  450. path: path,
  451. query: query,
  452. hash: hash
  453. }
  454. }
  455. function cleanPath (path) {
  456. return path.replace(/\/\//g, '/')
  457. }
  458. var isarray = Array.isArray || function (arr) {
  459. return Object.prototype.toString.call(arr) == '[object Array]';
  460. };
  461. /**
  462. * Expose `pathToRegexp`.
  463. */
  464. var pathToRegexp_1 = pathToRegexp;
  465. var parse_1 = parse;
  466. var compile_1 = compile;
  467. var tokensToFunction_1 = tokensToFunction;
  468. var tokensToRegExp_1 = tokensToRegExp;
  469. /**
  470. * The main path matching regexp utility.
  471. *
  472. * @type {RegExp}
  473. */
  474. var PATH_REGEXP = new RegExp([
  475. // Match escaped characters that would otherwise appear in future matches.
  476. // This allows the user to escape special characters that won't transform.
  477. '(\\\\.)',
  478. // Match Express-style parameters and un-named parameters with a prefix
  479. // and optional suffixes. Matches appear as:
  480. //
  481. // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  482. // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
  483. // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
  484. '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  485. ].join('|'), 'g');
  486. /**
  487. * Parse a string for the raw tokens.
  488. *
  489. * @param {string} str
  490. * @param {Object=} options
  491. * @return {!Array}
  492. */
  493. function parse (str, options) {
  494. var tokens = [];
  495. var key = 0;
  496. var index = 0;
  497. var path = '';
  498. var defaultDelimiter = options && options.delimiter || '/';
  499. var res;
  500. while ((res = PATH_REGEXP.exec(str)) != null) {
  501. var m = res[0];
  502. var escaped = res[1];
  503. var offset = res.index;
  504. path += str.slice(index, offset);
  505. index = offset + m.length;
  506. // Ignore already escaped sequences.
  507. if (escaped) {
  508. path += escaped[1];
  509. continue
  510. }
  511. var next = str[index];
  512. var prefix = res[2];
  513. var name = res[3];
  514. var capture = res[4];
  515. var group = res[5];
  516. var modifier = res[6];
  517. var asterisk = res[7];
  518. // Push the current path onto the tokens.
  519. if (path) {
  520. tokens.push(path);
  521. path = '';
  522. }
  523. var partial = prefix != null && next != null && next !== prefix;
  524. var repeat = modifier === '+' || modifier === '*';
  525. var optional = modifier === '?' || modifier === '*';
  526. var delimiter = res[2] || defaultDelimiter;
  527. var pattern = capture || group;
  528. tokens.push({
  529. name: name || key++,
  530. prefix: prefix || '',
  531. delimiter: delimiter,
  532. optional: optional,
  533. repeat: repeat,
  534. partial: partial,
  535. asterisk: !!asterisk,
  536. pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
  537. });
  538. }
  539. // Match any characters still remaining.
  540. if (index < str.length) {
  541. path += str.substr(index);
  542. }
  543. // If the path exists, push it onto the end.
  544. if (path) {
  545. tokens.push(path);
  546. }
  547. return tokens
  548. }
  549. /**
  550. * Compile a string to a template function for the path.
  551. *
  552. * @param {string} str
  553. * @param {Object=} options
  554. * @return {!function(Object=, Object=)}
  555. */
  556. function compile (str, options) {
  557. return tokensToFunction(parse(str, options), options)
  558. }
  559. /**
  560. * Prettier encoding of URI path segments.
  561. *
  562. * @param {string}
  563. * @return {string}
  564. */
  565. function encodeURIComponentPretty (str) {
  566. return encodeURI(str).replace(/[\/?#]/g, function (c) {
  567. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  568. })
  569. }
  570. /**
  571. * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
  572. *
  573. * @param {string}
  574. * @return {string}
  575. */
  576. function encodeAsterisk (str) {
  577. return encodeURI(str).replace(/[?#]/g, function (c) {
  578. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  579. })
  580. }
  581. /**
  582. * Expose a method for transforming tokens into the path function.
  583. */
  584. function tokensToFunction (tokens, options) {
  585. // Compile all the tokens into regexps.
  586. var matches = new Array(tokens.length);
  587. // Compile all the patterns before compilation.
  588. for (var i = 0; i < tokens.length; i++) {
  589. if (typeof tokens[i] === 'object') {
  590. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
  591. }
  592. }
  593. return function (obj, opts) {
  594. var path = '';
  595. var data = obj || {};
  596. var options = opts || {};
  597. var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
  598. for (var i = 0; i < tokens.length; i++) {
  599. var token = tokens[i];
  600. if (typeof token === 'string') {
  601. path += token;
  602. continue
  603. }
  604. var value = data[token.name];
  605. var segment;
  606. if (value == null) {
  607. if (token.optional) {
  608. // Prepend partial segment prefixes.
  609. if (token.partial) {
  610. path += token.prefix;
  611. }
  612. continue
  613. } else {
  614. throw new TypeError('Expected "' + token.name + '" to be defined')
  615. }
  616. }
  617. if (isarray(value)) {
  618. if (!token.repeat) {
  619. throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
  620. }
  621. if (value.length === 0) {
  622. if (token.optional) {
  623. continue
  624. } else {
  625. throw new TypeError('Expected "' + token.name + '" to not be empty')
  626. }
  627. }
  628. for (var j = 0; j < value.length; j++) {
  629. segment = encode(value[j]);
  630. if (!matches[i].test(segment)) {
  631. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
  632. }
  633. path += (j === 0 ? token.prefix : token.delimiter) + segment;
  634. }
  635. continue
  636. }
  637. segment = token.asterisk ? encodeAsterisk(value) : encode(value);
  638. if (!matches[i].test(segment)) {
  639. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
  640. }
  641. path += token.prefix + segment;
  642. }
  643. return path
  644. }
  645. }
  646. /**
  647. * Escape a regular expression string.
  648. *
  649. * @param {string} str
  650. * @return {string}
  651. */
  652. function escapeString (str) {
  653. return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
  654. }
  655. /**
  656. * Escape the capturing group by escaping special characters and meaning.
  657. *
  658. * @param {string} group
  659. * @return {string}
  660. */
  661. function escapeGroup (group) {
  662. return group.replace(/([=!:$\/()])/g, '\\$1')
  663. }
  664. /**
  665. * Attach the keys as a property of the regexp.
  666. *
  667. * @param {!RegExp} re
  668. * @param {Array} keys
  669. * @return {!RegExp}
  670. */
  671. function attachKeys (re, keys) {
  672. re.keys = keys;
  673. return re
  674. }
  675. /**
  676. * Get the flags for a regexp from the options.
  677. *
  678. * @param {Object} options
  679. * @return {string}
  680. */
  681. function flags (options) {
  682. return options && options.sensitive ? '' : 'i'
  683. }
  684. /**
  685. * Pull out keys from a regexp.
  686. *
  687. * @param {!RegExp} path
  688. * @param {!Array} keys
  689. * @return {!RegExp}
  690. */
  691. function regexpToRegexp (path, keys) {
  692. // Use a negative lookahead to match only capturing groups.
  693. var groups = path.source.match(/\((?!\?)/g);
  694. if (groups) {
  695. for (var i = 0; i < groups.length; i++) {
  696. keys.push({
  697. name: i,
  698. prefix: null,
  699. delimiter: null,
  700. optional: false,
  701. repeat: false,
  702. partial: false,
  703. asterisk: false,
  704. pattern: null
  705. });
  706. }
  707. }
  708. return attachKeys(path, keys)
  709. }
  710. /**
  711. * Transform an array into a regexp.
  712. *
  713. * @param {!Array} path
  714. * @param {Array} keys
  715. * @param {!Object} options
  716. * @return {!RegExp}
  717. */
  718. function arrayToRegexp (path, keys, options) {
  719. var parts = [];
  720. for (var i = 0; i < path.length; i++) {
  721. parts.push(pathToRegexp(path[i], keys, options).source);
  722. }
  723. var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
  724. return attachKeys(regexp, keys)
  725. }
  726. /**
  727. * Create a path regexp from string input.
  728. *
  729. * @param {string} path
  730. * @param {!Array} keys
  731. * @param {!Object} options
  732. * @return {!RegExp}
  733. */
  734. function stringToRegexp (path, keys, options) {
  735. return tokensToRegExp(parse(path, options), keys, options)
  736. }
  737. /**
  738. * Expose a function for taking tokens and returning a RegExp.
  739. *
  740. * @param {!Array} tokens
  741. * @param {(Array|Object)=} keys
  742. * @param {Object=} options
  743. * @return {!RegExp}
  744. */
  745. function tokensToRegExp (tokens, keys, options) {
  746. if (!isarray(keys)) {
  747. options = /** @type {!Object} */ (keys || options);
  748. keys = [];
  749. }
  750. options = options || {};
  751. var strict = options.strict;
  752. var end = options.end !== false;
  753. var route = '';
  754. // Iterate over the tokens and create our regexp string.
  755. for (var i = 0; i < tokens.length; i++) {
  756. var token = tokens[i];
  757. if (typeof token === 'string') {
  758. route += escapeString(token);
  759. } else {
  760. var prefix = escapeString(token.prefix);
  761. var capture = '(?:' + token.pattern + ')';
  762. keys.push(token);
  763. if (token.repeat) {
  764. capture += '(?:' + prefix + capture + ')*';
  765. }
  766. if (token.optional) {
  767. if (!token.partial) {
  768. capture = '(?:' + prefix + '(' + capture + '))?';
  769. } else {
  770. capture = prefix + '(' + capture + ')?';
  771. }
  772. } else {
  773. capture = prefix + '(' + capture + ')';
  774. }
  775. route += capture;
  776. }
  777. }
  778. var delimiter = escapeString(options.delimiter || '/');
  779. var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
  780. // In non-strict mode we allow a slash at the end of match. If the path to
  781. // match already ends with a slash, we remove it for consistency. The slash
  782. // is valid at the end of a path match, not in the middle. This is important
  783. // in non-ending mode, where "/test/" shouldn't match "/test//route".
  784. if (!strict) {
  785. route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
  786. }
  787. if (end) {
  788. route += '$';
  789. } else {
  790. // In non-ending mode, we need the capturing groups to match as much as
  791. // possible by using a positive lookahead to the end or next path segment.
  792. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
  793. }
  794. return attachKeys(new RegExp('^' + route, flags(options)), keys)
  795. }
  796. /**
  797. * Normalize the given path string, returning a regular expression.
  798. *
  799. * An empty array can be passed in for the keys, which will hold the
  800. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  801. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  802. *
  803. * @param {(string|RegExp|Array)} path
  804. * @param {(Array|Object)=} keys
  805. * @param {Object=} options
  806. * @return {!RegExp}
  807. */
  808. function pathToRegexp (path, keys, options) {
  809. if (!isarray(keys)) {
  810. options = /** @type {!Object} */ (keys || options);
  811. keys = [];
  812. }
  813. options = options || {};
  814. if (path instanceof RegExp) {
  815. return regexpToRegexp(path, /** @type {!Array} */ (keys))
  816. }
  817. if (isarray(path)) {
  818. return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
  819. }
  820. return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
  821. }
  822. pathToRegexp_1.parse = parse_1;
  823. pathToRegexp_1.compile = compile_1;
  824. pathToRegexp_1.tokensToFunction = tokensToFunction_1;
  825. pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
  826. /* */
  827. // $flow-disable-line
  828. var regexpCompileCache = Object.create(null);
  829. function fillParams (
  830. path,
  831. params,
  832. routeMsg
  833. ) {
  834. params = params || {};
  835. try {
  836. var filler =
  837. regexpCompileCache[path] ||
  838. (regexpCompileCache[path] = pathToRegexp_1.compile(path));
  839. // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
  840. // and fix #3106 so that you can work with location descriptor object having params.pathMatch equal to empty string
  841. if (typeof params.pathMatch === 'string') { params[0] = params.pathMatch; }
  842. return filler(params, { pretty: true })
  843. } catch (e) {
  844. if (process.env.NODE_ENV !== 'production') {
  845. // Fix #3072 no warn if `pathMatch` is string
  846. warn(typeof params.pathMatch === 'string', ("missing param for " + routeMsg + ": " + (e.message)));
  847. }
  848. return ''
  849. } finally {
  850. // delete the 0 if it was added
  851. delete params[0];
  852. }
  853. }
  854. /* */
  855. function normalizeLocation (
  856. raw,
  857. current,
  858. append,
  859. router
  860. ) {
  861. var next = typeof raw === 'string' ? { path: raw } : raw;
  862. // named target
  863. if (next._normalized) {
  864. return next
  865. } else if (next.name) {
  866. next = extend({}, raw);
  867. var params = next.params;
  868. if (params && typeof params === 'object') {
  869. next.params = extend({}, params);
  870. }
  871. return next
  872. }
  873. // relative params
  874. if (!next.path && next.params && current) {
  875. next = extend({}, next);
  876. next._normalized = true;
  877. var params$1 = extend(extend({}, current.params), next.params);
  878. if (current.name) {
  879. next.name = current.name;
  880. next.params = params$1;
  881. } else if (current.matched.length) {
  882. var rawPath = current.matched[current.matched.length - 1].path;
  883. next.path = fillParams(rawPath, params$1, ("path " + (current.path)));
  884. } else if (process.env.NODE_ENV !== 'production') {
  885. warn(false, "relative params navigation requires a current route.");
  886. }
  887. return next
  888. }
  889. var parsedPath = parsePath(next.path || '');
  890. var basePath = (current && current.path) || '/';
  891. var path = parsedPath.path
  892. ? resolvePath(parsedPath.path, basePath, append || next.append)
  893. : basePath;
  894. var query = resolveQuery(
  895. parsedPath.query,
  896. next.query,
  897. router && router.options.parseQuery
  898. );
  899. var hash = next.hash || parsedPath.hash;
  900. if (hash && hash.charAt(0) !== '#') {
  901. hash = "#" + hash;
  902. }
  903. return {
  904. _normalized: true,
  905. path: path,
  906. query: query,
  907. hash: hash
  908. }
  909. }
  910. /* */
  911. // work around weird flow bug
  912. var toTypes = [String, Object];
  913. var eventTypes = [String, Array];
  914. var noop = function () {};
  915. var warnedCustomSlot;
  916. var warnedTagProp;
  917. var warnedEventProp;
  918. var Link = {
  919. name: 'RouterLink',
  920. props: {
  921. to: {
  922. type: toTypes,
  923. required: true
  924. },
  925. tag: {
  926. type: String,
  927. default: 'a'
  928. },
  929. custom: Boolean,
  930. exact: Boolean,
  931. exactPath: Boolean,
  932. append: Boolean,
  933. replace: Boolean,
  934. activeClass: String,
  935. exactActiveClass: String,
  936. ariaCurrentValue: {
  937. type: String,
  938. default: 'page'
  939. },
  940. event: {
  941. type: eventTypes,
  942. default: 'click'
  943. }
  944. },
  945. render: function render (h) {
  946. var this$1 = this;
  947. var router = this.$router;
  948. var current = this.$route;
  949. var ref = router.resolve(
  950. this.to,
  951. current,
  952. this.append
  953. );
  954. var location = ref.location;
  955. var route = ref.route;
  956. var href = ref.href;
  957. var classes = {};
  958. var globalActiveClass = router.options.linkActiveClass;
  959. var globalExactActiveClass = router.options.linkExactActiveClass;
  960. // Support global empty active class
  961. var activeClassFallback =
  962. globalActiveClass == null ? 'router-link-active' : globalActiveClass;
  963. var exactActiveClassFallback =
  964. globalExactActiveClass == null
  965. ? 'router-link-exact-active'
  966. : globalExactActiveClass;
  967. var activeClass =
  968. this.activeClass == null ? activeClassFallback : this.activeClass;
  969. var exactActiveClass =
  970. this.exactActiveClass == null
  971. ? exactActiveClassFallback
  972. : this.exactActiveClass;
  973. var compareTarget = route.redirectedFrom
  974. ? createRoute(null, normalizeLocation(route.redirectedFrom), null, router)
  975. : route;
  976. classes[exactActiveClass] = isSameRoute(current, compareTarget, this.exactPath);
  977. classes[activeClass] = this.exact || this.exactPath
  978. ? classes[exactActiveClass]
  979. : isIncludedRoute(current, compareTarget);
  980. var ariaCurrentValue = classes[exactActiveClass] ? this.ariaCurrentValue : null;
  981. var handler = function (e) {
  982. if (guardEvent(e)) {
  983. if (this$1.replace) {
  984. router.replace(location, noop);
  985. } else {
  986. router.push(location, noop);
  987. }
  988. }
  989. };
  990. var on = { click: guardEvent };
  991. if (Array.isArray(this.event)) {
  992. this.event.forEach(function (e) {
  993. on[e] = handler;
  994. });
  995. } else {
  996. on[this.event] = handler;
  997. }
  998. var data = { class: classes };
  999. var scopedSlot =
  1000. !this.$scopedSlots.$hasNormal &&
  1001. this.$scopedSlots.default &&
  1002. this.$scopedSlots.default({
  1003. href: href,
  1004. route: route,
  1005. navigate: handler,
  1006. isActive: classes[activeClass],
  1007. isExactActive: classes[exactActiveClass]
  1008. });
  1009. if (scopedSlot) {
  1010. if (process.env.NODE_ENV !== 'production' && !this.custom) {
  1011. !warnedCustomSlot && warn(false, 'In Vue Router 4, the v-slot API will by default wrap its content with an <a> element. Use the custom prop to remove this warning:\n<router-link v-slot="{ navigate, href }" custom></router-link>\n');
  1012. warnedCustomSlot = true;
  1013. }
  1014. if (scopedSlot.length === 1) {
  1015. return scopedSlot[0]
  1016. } else if (scopedSlot.length > 1 || !scopedSlot.length) {
  1017. if (process.env.NODE_ENV !== 'production') {
  1018. warn(
  1019. false,
  1020. ("<router-link> with to=\"" + (this.to) + "\" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.")
  1021. );
  1022. }
  1023. return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
  1024. }
  1025. }
  1026. if (process.env.NODE_ENV !== 'production') {
  1027. if ('tag' in this.$options.propsData && !warnedTagProp) {
  1028. warn(
  1029. false,
  1030. "<router-link>'s tag prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link."
  1031. );
  1032. warnedTagProp = true;
  1033. }
  1034. if ('event' in this.$options.propsData && !warnedEventProp) {
  1035. warn(
  1036. false,
  1037. "<router-link>'s event prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link."
  1038. );
  1039. warnedEventProp = true;
  1040. }
  1041. }
  1042. if (this.tag === 'a') {
  1043. data.on = on;
  1044. data.attrs = { href: href, 'aria-current': ariaCurrentValue };
  1045. } else {
  1046. // find the first <a> child and apply listener and href
  1047. var a = findAnchor(this.$slots.default);
  1048. if (a) {
  1049. // in case the <a> is a static node
  1050. a.isStatic = false;
  1051. var aData = (a.data = extend({}, a.data));
  1052. aData.on = aData.on || {};
  1053. // transform existing events in both objects into arrays so we can push later
  1054. for (var event in aData.on) {
  1055. var handler$1 = aData.on[event];
  1056. if (event in on) {
  1057. aData.on[event] = Array.isArray(handler$1) ? handler$1 : [handler$1];
  1058. }
  1059. }
  1060. // append new listeners for router-link
  1061. for (var event$1 in on) {
  1062. if (event$1 in aData.on) {
  1063. // on[event] is always a function
  1064. aData.on[event$1].push(on[event$1]);
  1065. } else {
  1066. aData.on[event$1] = handler;
  1067. }
  1068. }
  1069. var aAttrs = (a.data.attrs = extend({}, a.data.attrs));
  1070. aAttrs.href = href;
  1071. aAttrs['aria-current'] = ariaCurrentValue;
  1072. } else {
  1073. // doesn't have <a> child, apply listener to self
  1074. data.on = on;
  1075. }
  1076. }
  1077. return h(this.tag, data, this.$slots.default)
  1078. }
  1079. };
  1080. function guardEvent (e) {
  1081. // don't redirect with control keys
  1082. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
  1083. // don't redirect when preventDefault called
  1084. if (e.defaultPrevented) { return }
  1085. // don't redirect on right click
  1086. if (e.button !== undefined && e.button !== 0) { return }
  1087. // don't redirect if `target="_blank"`
  1088. if (e.currentTarget && e.currentTarget.getAttribute) {
  1089. var target = e.currentTarget.getAttribute('target');
  1090. if (/\b_blank\b/i.test(target)) { return }
  1091. }
  1092. // this may be a Weex event which doesn't have this method
  1093. if (e.preventDefault) {
  1094. e.preventDefault();
  1095. }
  1096. return true
  1097. }
  1098. function findAnchor (children) {
  1099. if (children) {
  1100. var child;
  1101. for (var i = 0; i < children.length; i++) {
  1102. child = children[i];
  1103. if (child.tag === 'a') {
  1104. return child
  1105. }
  1106. if (child.children && (child = findAnchor(child.children))) {
  1107. return child
  1108. }
  1109. }
  1110. }
  1111. }
  1112. var _Vue;
  1113. function install (Vue) {
  1114. if (install.installed && _Vue === Vue) { return }
  1115. install.installed = true;
  1116. _Vue = Vue;
  1117. var isDef = function (v) { return v !== undefined; };
  1118. var registerInstance = function (vm, callVal) {
  1119. var i = vm.$options._parentVnode;
  1120. if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
  1121. i(vm, callVal);
  1122. }
  1123. };
  1124. Vue.mixin({
  1125. beforeCreate: function beforeCreate () {
  1126. if (isDef(this.$options.router)) {
  1127. this._routerRoot = this;
  1128. this._router = this.$options.router;
  1129. this._router.init(this);
  1130. Vue.util.defineReactive(this, '_route', this._router.history.current);
  1131. } else {
  1132. this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
  1133. }
  1134. registerInstance(this, this);
  1135. },
  1136. destroyed: function destroyed () {
  1137. registerInstance(this);
  1138. }
  1139. });
  1140. Object.defineProperty(Vue.prototype, '$router', {
  1141. get: function get () { return this._routerRoot._router }
  1142. });
  1143. Object.defineProperty(Vue.prototype, '$route', {
  1144. get: function get () { return this._routerRoot._route }
  1145. });
  1146. Vue.component('RouterView', View);
  1147. Vue.component('RouterLink', Link);
  1148. var strats = Vue.config.optionMergeStrategies;
  1149. // use the same hook merging strategy for route hooks
  1150. strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
  1151. }
  1152. /* */
  1153. var inBrowser = typeof window !== 'undefined';
  1154. /* */
  1155. function createRouteMap (
  1156. routes,
  1157. oldPathList,
  1158. oldPathMap,
  1159. oldNameMap,
  1160. parentRoute
  1161. ) {
  1162. // the path list is used to control path matching priority
  1163. var pathList = oldPathList || [];
  1164. // $flow-disable-line
  1165. var pathMap = oldPathMap || Object.create(null);
  1166. // $flow-disable-line
  1167. var nameMap = oldNameMap || Object.create(null);
  1168. routes.forEach(function (route) {
  1169. addRouteRecord(pathList, pathMap, nameMap, route, parentRoute);
  1170. });
  1171. // ensure wildcard routes are always at the end
  1172. for (var i = 0, l = pathList.length; i < l; i++) {
  1173. if (pathList[i] === '*') {
  1174. pathList.push(pathList.splice(i, 1)[0]);
  1175. l--;
  1176. i--;
  1177. }
  1178. }
  1179. if (process.env.NODE_ENV === 'development') {
  1180. // warn if routes do not include leading slashes
  1181. var found = pathList
  1182. // check for missing leading slash
  1183. .filter(function (path) { return path && path.charAt(0) !== '*' && path.charAt(0) !== '/'; });
  1184. if (found.length > 0) {
  1185. var pathNames = found.map(function (path) { return ("- " + path); }).join('\n');
  1186. warn(false, ("Non-nested routes must include a leading slash character. Fix the following routes: \n" + pathNames));
  1187. }
  1188. }
  1189. return {
  1190. pathList: pathList,
  1191. pathMap: pathMap,
  1192. nameMap: nameMap
  1193. }
  1194. }
  1195. function addRouteRecord (
  1196. pathList,
  1197. pathMap,
  1198. nameMap,
  1199. route,
  1200. parent,
  1201. matchAs
  1202. ) {
  1203. var path = route.path;
  1204. var name = route.name;
  1205. if (process.env.NODE_ENV !== 'production') {
  1206. assert(path != null, "\"path\" is required in a route configuration.");
  1207. assert(
  1208. typeof route.component !== 'string',
  1209. "route config \"component\" for path: " + (String(
  1210. path || name
  1211. )) + " cannot be a " + "string id. Use an actual component instead."
  1212. );
  1213. warn(
  1214. // eslint-disable-next-line no-control-regex
  1215. !/[^\u0000-\u007F]+/.test(path),
  1216. "Route with path \"" + path + "\" contains unencoded characters, make sure " +
  1217. "your path is correctly encoded before passing it to the router. Use " +
  1218. "encodeURI to encode static segments of your path."
  1219. );
  1220. }
  1221. var pathToRegexpOptions =
  1222. route.pathToRegexpOptions || {};
  1223. var normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
  1224. if (typeof route.caseSensitive === 'boolean') {
  1225. pathToRegexpOptions.sensitive = route.caseSensitive;
  1226. }
  1227. var record = {
  1228. path: normalizedPath,
  1229. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1230. components: route.components || { default: route.component },
  1231. alias: route.alias
  1232. ? typeof route.alias === 'string'
  1233. ? [route.alias]
  1234. : route.alias
  1235. : [],
  1236. instances: {},
  1237. enteredCbs: {},
  1238. name: name,
  1239. parent: parent,
  1240. matchAs: matchAs,
  1241. redirect: route.redirect,
  1242. beforeEnter: route.beforeEnter,
  1243. meta: route.meta || {},
  1244. props:
  1245. route.props == null
  1246. ? {}
  1247. : route.components
  1248. ? route.props
  1249. : { default: route.props }
  1250. };
  1251. if (route.children) {
  1252. // Warn if route is named, does not redirect and has a default child route.
  1253. // If users navigate to this route by name, the default child will
  1254. // not be rendered (GH Issue #629)
  1255. if (process.env.NODE_ENV !== 'production') {
  1256. if (
  1257. route.name &&
  1258. !route.redirect &&
  1259. route.children.some(function (child) { return /^\/?$/.test(child.path); })
  1260. ) {
  1261. warn(
  1262. false,
  1263. "Named Route '" + (route.name) + "' has a default child route. " +
  1264. "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
  1265. "the default child route will not be rendered. Remove the name from " +
  1266. "this route and use the name of the default child route for named " +
  1267. "links instead."
  1268. );
  1269. }
  1270. }
  1271. route.children.forEach(function (child) {
  1272. var childMatchAs = matchAs
  1273. ? cleanPath((matchAs + "/" + (child.path)))
  1274. : undefined;
  1275. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1276. });
  1277. }
  1278. if (!pathMap[record.path]) {
  1279. pathList.push(record.path);
  1280. pathMap[record.path] = record;
  1281. }
  1282. if (route.alias !== undefined) {
  1283. var aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
  1284. for (var i = 0; i < aliases.length; ++i) {
  1285. var alias = aliases[i];
  1286. if (process.env.NODE_ENV !== 'production' && alias === path) {
  1287. warn(
  1288. false,
  1289. ("Found an alias with the same value as the path: \"" + path + "\". You have to remove that alias. It will be ignored in development.")
  1290. );
  1291. // skip in dev to make it work
  1292. continue
  1293. }
  1294. var aliasRoute = {
  1295. path: alias,
  1296. children: route.children
  1297. };
  1298. addRouteRecord(
  1299. pathList,
  1300. pathMap,
  1301. nameMap,
  1302. aliasRoute,
  1303. parent,
  1304. record.path || '/' // matchAs
  1305. );
  1306. }
  1307. }
  1308. if (name) {
  1309. if (!nameMap[name]) {
  1310. nameMap[name] = record;
  1311. } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
  1312. warn(
  1313. false,
  1314. "Duplicate named routes definition: " +
  1315. "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
  1316. );
  1317. }
  1318. }
  1319. }
  1320. function compileRouteRegex (
  1321. path,
  1322. pathToRegexpOptions
  1323. ) {
  1324. var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1325. if (process.env.NODE_ENV !== 'production') {
  1326. var keys = Object.create(null);
  1327. regex.keys.forEach(function (key) {
  1328. warn(
  1329. !keys[key.name],
  1330. ("Duplicate param keys in route with path: \"" + path + "\"")
  1331. );
  1332. keys[key.name] = true;
  1333. });
  1334. }
  1335. return regex
  1336. }
  1337. function normalizePath (
  1338. path,
  1339. parent,
  1340. strict
  1341. ) {
  1342. if (!strict) { path = path.replace(/\/$/, ''); }
  1343. if (path[0] === '/') { return path }
  1344. if (parent == null) { return path }
  1345. return cleanPath(((parent.path) + "/" + path))
  1346. }
  1347. /* */
  1348. function createMatcher (
  1349. routes,
  1350. router
  1351. ) {
  1352. var ref = createRouteMap(routes);
  1353. var pathList = ref.pathList;
  1354. var pathMap = ref.pathMap;
  1355. var nameMap = ref.nameMap;
  1356. function addRoutes (routes) {
  1357. createRouteMap(routes, pathList, pathMap, nameMap);
  1358. }
  1359. function addRoute (parentOrRoute, route) {
  1360. var parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined;
  1361. // $flow-disable-line
  1362. createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent);
  1363. // add aliases of parent
  1364. if (parent) {
  1365. createRouteMap(
  1366. // $flow-disable-line route is defined if parent is
  1367. parent.alias.map(function (alias) { return ({ path: alias, children: [route] }); }),
  1368. pathList,
  1369. pathMap,
  1370. nameMap,
  1371. parent
  1372. );
  1373. }
  1374. }
  1375. function getRoutes () {
  1376. return pathList.map(function (path) { return pathMap[path]; })
  1377. }
  1378. function match (
  1379. raw,
  1380. currentRoute,
  1381. redirectedFrom
  1382. ) {
  1383. var location = normalizeLocation(raw, currentRoute, false, router);
  1384. var name = location.name;
  1385. if (name) {
  1386. var record = nameMap[name];
  1387. if (process.env.NODE_ENV !== 'production') {
  1388. warn(record, ("Route with name '" + name + "' does not exist"));
  1389. }
  1390. if (!record) { return _createRoute(null, location) }
  1391. var paramNames = record.regex.keys
  1392. .filter(function (key) { return !key.optional; })
  1393. .map(function (key) { return key.name; });
  1394. if (typeof location.params !== 'object') {
  1395. location.params = {};
  1396. }
  1397. if (currentRoute && typeof currentRoute.params === 'object') {
  1398. for (var key in currentRoute.params) {
  1399. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1400. location.params[key] = currentRoute.params[key];
  1401. }
  1402. }
  1403. }
  1404. location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
  1405. return _createRoute(record, location, redirectedFrom)
  1406. } else if (location.path) {
  1407. location.params = {};
  1408. for (var i = 0; i < pathList.length; i++) {
  1409. var path = pathList[i];
  1410. var record$1 = pathMap[path];
  1411. if (matchRoute(record$1.regex, location.path, location.params)) {
  1412. return _createRoute(record$1, location, redirectedFrom)
  1413. }
  1414. }
  1415. }
  1416. // no match
  1417. return _createRoute(null, location)
  1418. }
  1419. function redirect (
  1420. record,
  1421. location
  1422. ) {
  1423. var originalRedirect = record.redirect;
  1424. var redirect = typeof originalRedirect === 'function'
  1425. ? originalRedirect(createRoute(record, location, null, router))
  1426. : originalRedirect;
  1427. if (typeof redirect === 'string') {
  1428. redirect = { path: redirect };
  1429. }
  1430. if (!redirect || typeof redirect !== 'object') {
  1431. if (process.env.NODE_ENV !== 'production') {
  1432. warn(
  1433. false, ("invalid redirect option: " + (JSON.stringify(redirect)))
  1434. );
  1435. }
  1436. return _createRoute(null, location)
  1437. }
  1438. var re = redirect;
  1439. var name = re.name;
  1440. var path = re.path;
  1441. var query = location.query;
  1442. var hash = location.hash;
  1443. var params = location.params;
  1444. query = re.hasOwnProperty('query') ? re.query : query;
  1445. hash = re.hasOwnProperty('hash') ? re.hash : hash;
  1446. params = re.hasOwnProperty('params') ? re.params : params;
  1447. if (name) {
  1448. // resolved named direct
  1449. var targetRecord = nameMap[name];
  1450. if (process.env.NODE_ENV !== 'production') {
  1451. assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
  1452. }
  1453. return match({
  1454. _normalized: true,
  1455. name: name,
  1456. query: query,
  1457. hash: hash,
  1458. params: params
  1459. }, undefined, location)
  1460. } else if (path) {
  1461. // 1. resolve relative redirect
  1462. var rawPath = resolveRecordPath(path, record);
  1463. // 2. resolve params
  1464. var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
  1465. // 3. rematch with existing query and hash
  1466. return match({
  1467. _normalized: true,
  1468. path: resolvedPath,
  1469. query: query,
  1470. hash: hash
  1471. }, undefined, location)
  1472. } else {
  1473. if (process.env.NODE_ENV !== 'production') {
  1474. warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
  1475. }
  1476. return _createRoute(null, location)
  1477. }
  1478. }
  1479. function alias (
  1480. record,
  1481. location,
  1482. matchAs
  1483. ) {
  1484. var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
  1485. var aliasedMatch = match({
  1486. _normalized: true,
  1487. path: aliasedPath
  1488. });
  1489. if (aliasedMatch) {
  1490. var matched = aliasedMatch.matched;
  1491. var aliasedRecord = matched[matched.length - 1];
  1492. location.params = aliasedMatch.params;
  1493. return _createRoute(aliasedRecord, location)
  1494. }
  1495. return _createRoute(null, location)
  1496. }
  1497. function _createRoute (
  1498. record,
  1499. location,
  1500. redirectedFrom
  1501. ) {
  1502. if (record && record.redirect) {
  1503. return redirect(record, redirectedFrom || location)
  1504. }
  1505. if (record && record.matchAs) {
  1506. return alias(record, location, record.matchAs)
  1507. }
  1508. return createRoute(record, location, redirectedFrom, router)
  1509. }
  1510. return {
  1511. match: match,
  1512. addRoute: addRoute,
  1513. getRoutes: getRoutes,
  1514. addRoutes: addRoutes
  1515. }
  1516. }
  1517. function matchRoute (
  1518. regex,
  1519. path,
  1520. params
  1521. ) {
  1522. var m = path.match(regex);
  1523. if (!m) {
  1524. return false
  1525. } else if (!params) {
  1526. return true
  1527. }
  1528. for (var i = 1, len = m.length; i < len; ++i) {
  1529. var key = regex.keys[i - 1];
  1530. if (key) {
  1531. // Fix #1994: using * with props: true generates a param named 0
  1532. params[key.name || 'pathMatch'] = typeof m[i] === 'string' ? decode(m[i]) : m[i];
  1533. }
  1534. }
  1535. return true
  1536. }
  1537. function resolveRecordPath (path, record) {
  1538. return resolvePath(path, record.parent ? record.parent.path : '/', true)
  1539. }
  1540. /* */
  1541. // use User Timing api (if present) for more accurate key precision
  1542. var Time =
  1543. inBrowser && window.performance && window.performance.now
  1544. ? window.performance
  1545. : Date;
  1546. function genStateKey () {
  1547. return Time.now().toFixed(3)
  1548. }
  1549. var _key = genStateKey();
  1550. function getStateKey () {
  1551. return _key
  1552. }
  1553. function setStateKey (key) {
  1554. return (_key = key)
  1555. }
  1556. /* */
  1557. var positionStore = Object.create(null);
  1558. function setupScroll () {
  1559. // Prevent browser scroll behavior on History popstate
  1560. if ('scrollRestoration' in window.history) {
  1561. window.history.scrollRestoration = 'manual';
  1562. }
  1563. // Fix for #1585 for Firefox
  1564. // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
  1565. // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
  1566. // window.location.protocol + '//' + window.location.host
  1567. // location.host contains the port and location.hostname doesn't
  1568. var protocolAndPath = window.location.protocol + '//' + window.location.host;
  1569. var absolutePath = window.location.href.replace(protocolAndPath, '');
  1570. // preserve existing history state as it could be overriden by the user
  1571. var stateCopy = extend({}, window.history.state);
  1572. stateCopy.key = getStateKey();
  1573. window.history.replaceState(stateCopy, '', absolutePath);
  1574. window.addEventListener('popstate', handlePopState);
  1575. return function () {
  1576. window.removeEventListener('popstate', handlePopState);
  1577. }
  1578. }
  1579. function handleScroll (
  1580. router,
  1581. to,
  1582. from,
  1583. isPop
  1584. ) {
  1585. if (!router.app) {
  1586. return
  1587. }
  1588. var behavior = router.options.scrollBehavior;
  1589. if (!behavior) {
  1590. return
  1591. }
  1592. if (process.env.NODE_ENV !== 'production') {
  1593. assert(typeof behavior === 'function', "scrollBehavior must be a function");
  1594. }
  1595. // wait until re-render finishes before scrolling
  1596. router.app.$nextTick(function () {
  1597. var position = getScrollPosition();
  1598. var shouldScroll = behavior.call(
  1599. router,
  1600. to,
  1601. from,
  1602. isPop ? position : null
  1603. );
  1604. if (!shouldScroll) {
  1605. return
  1606. }
  1607. if (typeof shouldScroll.then === 'function') {
  1608. shouldScroll
  1609. .then(function (shouldScroll) {
  1610. scrollToPosition((shouldScroll), position);
  1611. })
  1612. .catch(function (err) {
  1613. if (process.env.NODE_ENV !== 'production') {
  1614. assert(false, err.toString());
  1615. }
  1616. });
  1617. } else {
  1618. scrollToPosition(shouldScroll, position);
  1619. }
  1620. });
  1621. }
  1622. function saveScrollPosition () {
  1623. var key = getStateKey();
  1624. if (key) {
  1625. positionStore[key] = {
  1626. x: window.pageXOffset,
  1627. y: window.pageYOffset
  1628. };
  1629. }
  1630. }
  1631. function handlePopState (e) {
  1632. saveScrollPosition();
  1633. if (e.state && e.state.key) {
  1634. setStateKey(e.state.key);
  1635. }
  1636. }
  1637. function getScrollPosition () {
  1638. var key = getStateKey();
  1639. if (key) {
  1640. return positionStore[key]
  1641. }
  1642. }
  1643. function getElementPosition (el, offset) {
  1644. var docEl = document.documentElement;
  1645. var docRect = docEl.getBoundingClientRect();
  1646. var elRect = el.getBoundingClientRect();
  1647. return {
  1648. x: elRect.left - docRect.left - offset.x,
  1649. y: elRect.top - docRect.top - offset.y
  1650. }
  1651. }
  1652. function isValidPosition (obj) {
  1653. return isNumber(obj.x) || isNumber(obj.y)
  1654. }
  1655. function normalizePosition (obj) {
  1656. return {
  1657. x: isNumber(obj.x) ? obj.x : window.pageXOffset,
  1658. y: isNumber(obj.y) ? obj.y : window.pageYOffset
  1659. }
  1660. }
  1661. function normalizeOffset (obj) {
  1662. return {
  1663. x: isNumber(obj.x) ? obj.x : 0,
  1664. y: isNumber(obj.y) ? obj.y : 0
  1665. }
  1666. }
  1667. function isNumber (v) {
  1668. return typeof v === 'number'
  1669. }
  1670. var hashStartsWithNumberRE = /^#\d/;
  1671. function scrollToPosition (shouldScroll, position) {
  1672. var isObject = typeof shouldScroll === 'object';
  1673. if (isObject && typeof shouldScroll.selector === 'string') {
  1674. // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
  1675. // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
  1676. var el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
  1677. ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
  1678. : document.querySelector(shouldScroll.selector);
  1679. if (el) {
  1680. var offset =
  1681. shouldScroll.offset && typeof shouldScroll.offset === 'object'
  1682. ? shouldScroll.offset
  1683. : {};
  1684. offset = normalizeOffset(offset);
  1685. position = getElementPosition(el, offset);
  1686. } else if (isValidPosition(shouldScroll)) {
  1687. position = normalizePosition(shouldScroll);
  1688. }
  1689. } else if (isObject && isValidPosition(shouldScroll)) {
  1690. position = normalizePosition(shouldScroll);
  1691. }
  1692. if (position) {
  1693. // $flow-disable-line
  1694. if ('scrollBehavior' in document.documentElement.style) {
  1695. window.scrollTo({
  1696. left: position.x,
  1697. top: position.y,
  1698. // $flow-disable-line
  1699. behavior: shouldScroll.behavior
  1700. });
  1701. } else {
  1702. window.scrollTo(position.x, position.y);
  1703. }
  1704. }
  1705. }
  1706. /* */
  1707. var supportsPushState =
  1708. inBrowser &&
  1709. (function () {
  1710. var ua = window.navigator.userAgent;
  1711. if (
  1712. (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
  1713. ua.indexOf('Mobile Safari') !== -1 &&
  1714. ua.indexOf('Chrome') === -1 &&
  1715. ua.indexOf('Windows Phone') === -1
  1716. ) {
  1717. return false
  1718. }
  1719. return window.history && typeof window.history.pushState === 'function'
  1720. })();
  1721. function pushState (url, replace) {
  1722. saveScrollPosition();
  1723. // try...catch the pushState call to get around Safari
  1724. // DOM Exception 18 where it limits to 100 pushState calls
  1725. var history = window.history;
  1726. try {
  1727. if (replace) {
  1728. // preserve existing history state as it could be overriden by the user
  1729. var stateCopy = extend({}, history.state);
  1730. stateCopy.key = getStateKey();
  1731. history.replaceState(stateCopy, '', url);
  1732. } else {
  1733. history.pushState({ key: setStateKey(genStateKey()) }, '', url);
  1734. }
  1735. } catch (e) {
  1736. window.location[replace ? 'replace' : 'assign'](url);
  1737. }
  1738. }
  1739. function replaceState (url) {
  1740. pushState(url, true);
  1741. }
  1742. /* */
  1743. function runQueue (queue, fn, cb) {
  1744. var step = function (index) {
  1745. if (index >= queue.length) {
  1746. cb();
  1747. } else {
  1748. if (queue[index]) {
  1749. fn(queue[index], function () {
  1750. step(index + 1);
  1751. });
  1752. } else {
  1753. step(index + 1);
  1754. }
  1755. }
  1756. };
  1757. step(0);
  1758. }
  1759. // When changing thing, also edit router.d.ts
  1760. var NavigationFailureType = {
  1761. redirected: 2,
  1762. aborted: 4,
  1763. cancelled: 8,
  1764. duplicated: 16
  1765. };
  1766. function createNavigationRedirectedError (from, to) {
  1767. return createRouterError(
  1768. from,
  1769. to,
  1770. NavigationFailureType.redirected,
  1771. ("Redirected when going from \"" + (from.fullPath) + "\" to \"" + (stringifyRoute(
  1772. to
  1773. )) + "\" via a navigation guard.")
  1774. )
  1775. }
  1776. function createNavigationDuplicatedError (from, to) {
  1777. var error = createRouterError(
  1778. from,
  1779. to,
  1780. NavigationFailureType.duplicated,
  1781. ("Avoided redundant navigation to current location: \"" + (from.fullPath) + "\".")
  1782. );
  1783. // backwards compatible with the first introduction of Errors
  1784. error.name = 'NavigationDuplicated';
  1785. return error
  1786. }
  1787. function createNavigationCancelledError (from, to) {
  1788. return createRouterError(
  1789. from,
  1790. to,
  1791. NavigationFailureType.cancelled,
  1792. ("Navigation cancelled from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" with a new navigation.")
  1793. )
  1794. }
  1795. function createNavigationAbortedError (from, to) {
  1796. return createRouterError(
  1797. from,
  1798. to,
  1799. NavigationFailureType.aborted,
  1800. ("Navigation aborted from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" via a navigation guard.")
  1801. )
  1802. }
  1803. function createRouterError (from, to, type, message) {
  1804. var error = new Error(message);
  1805. error._isRouter = true;
  1806. error.from = from;
  1807. error.to = to;
  1808. error.type = type;
  1809. return error
  1810. }
  1811. var propertiesToLog = ['params', 'query', 'hash'];
  1812. function stringifyRoute (to) {
  1813. if (typeof to === 'string') { return to }
  1814. if ('path' in to) { return to.path }
  1815. var location = {};
  1816. propertiesToLog.forEach(function (key) {
  1817. if (key in to) { location[key] = to[key]; }
  1818. });
  1819. return JSON.stringify(location, null, 2)
  1820. }
  1821. function isError (err) {
  1822. return Object.prototype.toString.call(err).indexOf('Error') > -1
  1823. }
  1824. function isNavigationFailure (err, errorType) {
  1825. return (
  1826. isError(err) &&
  1827. err._isRouter &&
  1828. (errorType == null || err.type === errorType)
  1829. )
  1830. }
  1831. /* */
  1832. function resolveAsyncComponents (matched) {
  1833. return function (to, from, next) {
  1834. var hasAsync = false;
  1835. var pending = 0;
  1836. var error = null;
  1837. flatMapComponents(matched, function (def, _, match, key) {
  1838. // if it's a function and doesn't have cid attached,
  1839. // assume it's an async component resolve function.
  1840. // we are not using Vue's default async resolving mechanism because
  1841. // we want to halt the navigation until the incoming component has been
  1842. // resolved.
  1843. if (typeof def === 'function' && def.cid === undefined) {
  1844. hasAsync = true;
  1845. pending++;
  1846. var resolve = once(function (resolvedDef) {
  1847. if (isESModule(resolvedDef)) {
  1848. resolvedDef = resolvedDef.default;
  1849. }
  1850. // save resolved on async factory in case it's used elsewhere
  1851. def.resolved = typeof resolvedDef === 'function'
  1852. ? resolvedDef
  1853. : _Vue.extend(resolvedDef);
  1854. match.components[key] = resolvedDef;
  1855. pending--;
  1856. if (pending <= 0) {
  1857. next();
  1858. }
  1859. });
  1860. var reject = once(function (reason) {
  1861. var msg = "Failed to resolve async component " + key + ": " + reason;
  1862. process.env.NODE_ENV !== 'production' && warn(false, msg);
  1863. if (!error) {
  1864. error = isError(reason)
  1865. ? reason
  1866. : new Error(msg);
  1867. next(error);
  1868. }
  1869. });
  1870. var res;
  1871. try {
  1872. res = def(resolve, reject);
  1873. } catch (e) {
  1874. reject(e);
  1875. }
  1876. if (res) {
  1877. if (typeof res.then === 'function') {
  1878. res.then(resolve, reject);
  1879. } else {
  1880. // new syntax in Vue 2.3
  1881. var comp = res.component;
  1882. if (comp && typeof comp.then === 'function') {
  1883. comp.then(resolve, reject);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. });
  1889. if (!hasAsync) { next(); }
  1890. }
  1891. }
  1892. function flatMapComponents (
  1893. matched,
  1894. fn
  1895. ) {
  1896. return flatten(matched.map(function (m) {
  1897. return Object.keys(m.components).map(function (key) { return fn(
  1898. m.components[key],
  1899. m.instances[key],
  1900. m, key
  1901. ); })
  1902. }))
  1903. }
  1904. function flatten (arr) {
  1905. return Array.prototype.concat.apply([], arr)
  1906. }
  1907. var hasSymbol =
  1908. typeof Symbol === 'function' &&
  1909. typeof Symbol.toStringTag === 'symbol';
  1910. function isESModule (obj) {
  1911. return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  1912. }
  1913. // in Webpack 2, require.ensure now also returns a Promise
  1914. // so the resolve/reject functions may get called an extra time
  1915. // if the user uses an arrow function shorthand that happens to
  1916. // return that Promise.
  1917. function once (fn) {
  1918. var called = false;
  1919. return function () {
  1920. var args = [], len = arguments.length;
  1921. while ( len-- ) args[ len ] = arguments[ len ];
  1922. if (called) { return }
  1923. called = true;
  1924. return fn.apply(this, args)
  1925. }
  1926. }
  1927. /* */
  1928. var History = function History (router, base) {
  1929. this.router = router;
  1930. this.base = normalizeBase(base);
  1931. // start with a route object that stands for "nowhere"
  1932. this.current = START;
  1933. this.pending = null;
  1934. this.ready = false;
  1935. this.readyCbs = [];
  1936. this.readyErrorCbs = [];
  1937. this.errorCbs = [];
  1938. this.listeners = [];
  1939. };
  1940. History.prototype.listen = function listen (cb) {
  1941. this.cb = cb;
  1942. };
  1943. History.prototype.onReady = function onReady (cb, errorCb) {
  1944. if (this.ready) {
  1945. cb();
  1946. } else {
  1947. this.readyCbs.push(cb);
  1948. if (errorCb) {
  1949. this.readyErrorCbs.push(errorCb);
  1950. }
  1951. }
  1952. };
  1953. History.prototype.onError = function onError (errorCb) {
  1954. this.errorCbs.push(errorCb);
  1955. };
  1956. History.prototype.transitionTo = function transitionTo (
  1957. location,
  1958. onComplete,
  1959. onAbort
  1960. ) {
  1961. var this$1 = this;
  1962. var route;
  1963. // catch redirect option https://github.com/vuejs/vue-router/issues/3201
  1964. try {
  1965. route = this.router.match(location, this.current);
  1966. } catch (e) {
  1967. this.errorCbs.forEach(function (cb) {
  1968. cb(e);
  1969. });
  1970. // Exception should still be thrown
  1971. throw e
  1972. }
  1973. var prev = this.current;
  1974. this.confirmTransition(
  1975. route,
  1976. function () {
  1977. this$1.updateRoute(route);
  1978. onComplete && onComplete(route);
  1979. this$1.ensureURL();
  1980. this$1.router.afterHooks.forEach(function (hook) {
  1981. hook && hook(route, prev);
  1982. });
  1983. // fire ready cbs once
  1984. if (!this$1.ready) {
  1985. this$1.ready = true;
  1986. this$1.readyCbs.forEach(function (cb) {
  1987. cb(route);
  1988. });
  1989. }
  1990. },
  1991. function (err) {
  1992. if (onAbort) {
  1993. onAbort(err);
  1994. }
  1995. if (err && !this$1.ready) {
  1996. // Initial redirection should not mark the history as ready yet
  1997. // because it's triggered by the redirection instead
  1998. // https://github.com/vuejs/vue-router/issues/3225
  1999. // https://github.com/vuejs/vue-router/issues/3331
  2000. if (!isNavigationFailure(err, NavigationFailureType.redirected) || prev !== START) {
  2001. this$1.ready = true;
  2002. this$1.readyErrorCbs.forEach(function (cb) {
  2003. cb(err);
  2004. });
  2005. }
  2006. }
  2007. }
  2008. );
  2009. };
  2010. History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
  2011. var this$1 = this;
  2012. var current = this.current;
  2013. this.pending = route;
  2014. var abort = function (err) {
  2015. // changed after adding errors with
  2016. // https://github.com/vuejs/vue-router/pull/3047 before that change,
  2017. // redirect and aborted navigation would produce an err == null
  2018. if (!isNavigationFailure(err) && isError(err)) {
  2019. if (this$1.errorCbs.length) {
  2020. this$1.errorCbs.forEach(function (cb) {
  2021. cb(err);
  2022. });
  2023. } else {
  2024. warn(false, 'uncaught error during route navigation:');
  2025. console.error(err);
  2026. }
  2027. }
  2028. onAbort && onAbort(err);
  2029. };
  2030. var lastRouteIndex = route.matched.length - 1;
  2031. var lastCurrentIndex = current.matched.length - 1;
  2032. if (
  2033. isSameRoute(route, current) &&
  2034. // in the case the route map has been dynamically appended to
  2035. lastRouteIndex === lastCurrentIndex &&
  2036. route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
  2037. ) {
  2038. this.ensureURL();
  2039. return abort(createNavigationDuplicatedError(current, route))
  2040. }
  2041. var ref = resolveQueue(
  2042. this.current.matched,
  2043. route.matched
  2044. );
  2045. var updated = ref.updated;
  2046. var deactivated = ref.deactivated;
  2047. var activated = ref.activated;
  2048. var queue = [].concat(
  2049. // in-component leave guards
  2050. extractLeaveGuards(deactivated),
  2051. // global before hooks
  2052. this.router.beforeHooks,
  2053. // in-component update hooks
  2054. extractUpdateHooks(updated),
  2055. // in-config enter guards
  2056. activated.map(function (m) { return m.beforeEnter; }),
  2057. // async components
  2058. resolveAsyncComponents(activated)
  2059. );
  2060. var iterator = function (hook, next) {
  2061. if (this$1.pending !== route) {
  2062. return abort(createNavigationCancelledError(current, route))
  2063. }
  2064. try {
  2065. hook(route, current, function (to) {
  2066. if (to === false) {
  2067. // next(false) -> abort navigation, ensure current URL
  2068. this$1.ensureURL(true);
  2069. abort(createNavigationAbortedError(current, route));
  2070. } else if (isError(to)) {
  2071. this$1.ensureURL(true);
  2072. abort(to);
  2073. } else if (
  2074. typeof to === 'string' ||
  2075. (typeof to === 'object' &&
  2076. (typeof to.path === 'string' || typeof to.name === 'string'))
  2077. ) {
  2078. // next('/') or next({ path: '/' }) -> redirect
  2079. abort(createNavigationRedirectedError(current, route));
  2080. if (typeof to === 'object' && to.replace) {
  2081. this$1.replace(to);
  2082. } else {
  2083. this$1.push(to);
  2084. }
  2085. } else {
  2086. // confirm transition and pass on the value
  2087. next(to);
  2088. }
  2089. });
  2090. } catch (e) {
  2091. abort(e);
  2092. }
  2093. };
  2094. runQueue(queue, iterator, function () {
  2095. // wait until async components are resolved before
  2096. // extracting in-component enter guards
  2097. var enterGuards = extractEnterGuards(activated);
  2098. var queue = enterGuards.concat(this$1.router.resolveHooks);
  2099. runQueue(queue, iterator, function () {
  2100. if (this$1.pending !== route) {
  2101. return abort(createNavigationCancelledError(current, route))
  2102. }
  2103. this$1.pending = null;
  2104. onComplete(route);
  2105. if (this$1.router.app) {
  2106. this$1.router.app.$nextTick(function () {
  2107. handleRouteEntered(route);
  2108. });
  2109. }
  2110. });
  2111. });
  2112. };
  2113. History.prototype.updateRoute = function updateRoute (route) {
  2114. this.current = route;
  2115. this.cb && this.cb(route);
  2116. };
  2117. History.prototype.setupListeners = function setupListeners () {
  2118. // Default implementation is empty
  2119. };
  2120. History.prototype.teardown = function teardown () {
  2121. // clean up event listeners
  2122. // https://github.com/vuejs/vue-router/issues/2341
  2123. this.listeners.forEach(function (cleanupListener) {
  2124. cleanupListener();
  2125. });
  2126. this.listeners = [];
  2127. // reset current history route
  2128. // https://github.com/vuejs/vue-router/issues/3294
  2129. this.current = START;
  2130. this.pending = null;
  2131. };
  2132. function normalizeBase (base) {
  2133. if (!base) {
  2134. if (inBrowser) {
  2135. // respect <base> tag
  2136. var baseEl = document.querySelector('base');
  2137. base = (baseEl && baseEl.getAttribute('href')) || '/';
  2138. // strip full URL origin
  2139. base = base.replace(/^https?:\/\/[^\/]+/, '');
  2140. } else {
  2141. base = '/';
  2142. }
  2143. }
  2144. // make sure there's the starting slash
  2145. if (base.charAt(0) !== '/') {
  2146. base = '/' + base;
  2147. }
  2148. // remove trailing slash
  2149. return base.replace(/\/$/, '')
  2150. }
  2151. function resolveQueue (
  2152. current,
  2153. next
  2154. ) {
  2155. var i;
  2156. var max = Math.max(current.length, next.length);
  2157. for (i = 0; i < max; i++) {
  2158. if (current[i] !== next[i]) {
  2159. break
  2160. }
  2161. }
  2162. return {
  2163. updated: next.slice(0, i),
  2164. activated: next.slice(i),
  2165. deactivated: current.slice(i)
  2166. }
  2167. }
  2168. function extractGuards (
  2169. records,
  2170. name,
  2171. bind,
  2172. reverse
  2173. ) {
  2174. var guards = flatMapComponents(records, function (def, instance, match, key) {
  2175. var guard = extractGuard(def, name);
  2176. if (guard) {
  2177. return Array.isArray(guard)
  2178. ? guard.map(function (guard) { return bind(guard, instance, match, key); })
  2179. : bind(guard, instance, match, key)
  2180. }
  2181. });
  2182. return flatten(reverse ? guards.reverse() : guards)
  2183. }
  2184. function extractGuard (
  2185. def,
  2186. key
  2187. ) {
  2188. if (typeof def !== 'function') {
  2189. // extend now so that global mixins are applied.
  2190. def = _Vue.extend(def);
  2191. }
  2192. return def.options[key]
  2193. }
  2194. function extractLeaveGuards (deactivated) {
  2195. return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
  2196. }
  2197. function extractUpdateHooks (updated) {
  2198. return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
  2199. }
  2200. function bindGuard (guard, instance) {
  2201. if (instance) {
  2202. return function boundRouteGuard () {
  2203. return guard.apply(instance, arguments)
  2204. }
  2205. }
  2206. }
  2207. function extractEnterGuards (
  2208. activated
  2209. ) {
  2210. return extractGuards(
  2211. activated,
  2212. 'beforeRouteEnter',
  2213. function (guard, _, match, key) {
  2214. return bindEnterGuard(guard, match, key)
  2215. }
  2216. )
  2217. }
  2218. function bindEnterGuard (
  2219. guard,
  2220. match,
  2221. key
  2222. ) {
  2223. return function routeEnterGuard (to, from, next) {
  2224. return guard(to, from, function (cb) {
  2225. if (typeof cb === 'function') {
  2226. if (!match.enteredCbs[key]) {
  2227. match.enteredCbs[key] = [];
  2228. }
  2229. match.enteredCbs[key].push(cb);
  2230. }
  2231. next(cb);
  2232. })
  2233. }
  2234. }
  2235. /* */
  2236. var HTML5History = /*@__PURE__*/(function (History) {
  2237. function HTML5History (router, base) {
  2238. History.call(this, router, base);
  2239. this._startLocation = getLocation(this.base);
  2240. }
  2241. if ( History ) HTML5History.__proto__ = History;
  2242. HTML5History.prototype = Object.create( History && History.prototype );
  2243. HTML5History.prototype.constructor = HTML5History;
  2244. HTML5History.prototype.setupListeners = function setupListeners () {
  2245. var this$1 = this;
  2246. if (this.listeners.length > 0) {
  2247. return
  2248. }
  2249. var router = this.router;
  2250. var expectScroll = router.options.scrollBehavior;
  2251. var supportsScroll = supportsPushState && expectScroll;
  2252. if (supportsScroll) {
  2253. this.listeners.push(setupScroll());
  2254. }
  2255. var handleRoutingEvent = function () {
  2256. var current = this$1.current;
  2257. // Avoiding first `popstate` event dispatched in some browsers but first
  2258. // history route not updated since async guard at the same time.
  2259. var location = getLocation(this$1.base);
  2260. if (this$1.current === START && location === this$1._startLocation) {
  2261. return
  2262. }
  2263. this$1.transitionTo(location, function (route) {
  2264. if (supportsScroll) {
  2265. handleScroll(router, route, current, true);
  2266. }
  2267. });
  2268. };
  2269. window.addEventListener('popstate', handleRoutingEvent);
  2270. this.listeners.push(function () {
  2271. window.removeEventListener('popstate', handleRoutingEvent);
  2272. });
  2273. };
  2274. HTML5History.prototype.go = function go (n) {
  2275. window.history.go(n);
  2276. };
  2277. HTML5History.prototype.push = function push (location, onComplete, onAbort) {
  2278. var this$1 = this;
  2279. var ref = this;
  2280. var fromRoute = ref.current;
  2281. this.transitionTo(location, function (route) {
  2282. pushState(cleanPath(this$1.base + route.fullPath));
  2283. handleScroll(this$1.router, route, fromRoute, false);
  2284. onComplete && onComplete(route);
  2285. }, onAbort);
  2286. };
  2287. HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
  2288. var this$1 = this;
  2289. var ref = this;
  2290. var fromRoute = ref.current;
  2291. this.transitionTo(location, function (route) {
  2292. replaceState(cleanPath(this$1.base + route.fullPath));
  2293. handleScroll(this$1.router, route, fromRoute, false);
  2294. onComplete && onComplete(route);
  2295. }, onAbort);
  2296. };
  2297. HTML5History.prototype.ensureURL = function ensureURL (push) {
  2298. if (getLocation(this.base) !== this.current.fullPath) {
  2299. var current = cleanPath(this.base + this.current.fullPath);
  2300. push ? pushState(current) : replaceState(current);
  2301. }
  2302. };
  2303. HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
  2304. return getLocation(this.base)
  2305. };
  2306. return HTML5History;
  2307. }(History));
  2308. function getLocation (base) {
  2309. var path = window.location.pathname;
  2310. if (base && path.toLowerCase().indexOf(base.toLowerCase()) === 0) {
  2311. path = path.slice(base.length);
  2312. }
  2313. return (path || '/') + window.location.search + window.location.hash
  2314. }
  2315. /* */
  2316. var HashHistory = /*@__PURE__*/(function (History) {
  2317. function HashHistory (router, base, fallback) {
  2318. History.call(this, router, base);
  2319. // check history fallback deeplinking
  2320. if (fallback && checkFallback(this.base)) {
  2321. return
  2322. }
  2323. ensureSlash();
  2324. }
  2325. if ( History ) HashHistory.__proto__ = History;
  2326. HashHistory.prototype = Object.create( History && History.prototype );
  2327. HashHistory.prototype.constructor = HashHistory;
  2328. // this is delayed until the app mounts
  2329. // to avoid the hashchange listener being fired too early
  2330. HashHistory.prototype.setupListeners = function setupListeners () {
  2331. var this$1 = this;
  2332. if (this.listeners.length > 0) {
  2333. return
  2334. }
  2335. var router = this.router;
  2336. var expectScroll = router.options.scrollBehavior;
  2337. var supportsScroll = supportsPushState && expectScroll;
  2338. if (supportsScroll) {
  2339. this.listeners.push(setupScroll());
  2340. }
  2341. var handleRoutingEvent = function () {
  2342. var current = this$1.current;
  2343. if (!ensureSlash()) {
  2344. return
  2345. }
  2346. this$1.transitionTo(getHash(), function (route) {
  2347. if (supportsScroll) {
  2348. handleScroll(this$1.router, route, current, true);
  2349. }
  2350. if (!supportsPushState) {
  2351. replaceHash(route.fullPath);
  2352. }
  2353. });
  2354. };
  2355. var eventType = supportsPushState ? 'popstate' : 'hashchange';
  2356. window.addEventListener(
  2357. eventType,
  2358. handleRoutingEvent
  2359. );
  2360. this.listeners.push(function () {
  2361. window.removeEventListener(eventType, handleRoutingEvent);
  2362. });
  2363. };
  2364. HashHistory.prototype.push = function push (location, onComplete, onAbort) {
  2365. var this$1 = this;
  2366. var ref = this;
  2367. var fromRoute = ref.current;
  2368. this.transitionTo(
  2369. location,
  2370. function (route) {
  2371. pushHash(route.fullPath);
  2372. handleScroll(this$1.router, route, fromRoute, false);
  2373. onComplete && onComplete(route);
  2374. },
  2375. onAbort
  2376. );
  2377. };
  2378. HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  2379. var this$1 = this;
  2380. var ref = this;
  2381. var fromRoute = ref.current;
  2382. this.transitionTo(
  2383. location,
  2384. function (route) {
  2385. replaceHash(route.fullPath);
  2386. handleScroll(this$1.router, route, fromRoute, false);
  2387. onComplete && onComplete(route);
  2388. },
  2389. onAbort
  2390. );
  2391. };
  2392. HashHistory.prototype.go = function go (n) {
  2393. window.history.go(n);
  2394. };
  2395. HashHistory.prototype.ensureURL = function ensureURL (push) {
  2396. var current = this.current.fullPath;
  2397. if (getHash() !== current) {
  2398. push ? pushHash(current) : replaceHash(current);
  2399. }
  2400. };
  2401. HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2402. return getHash()
  2403. };
  2404. return HashHistory;
  2405. }(History));
  2406. function checkFallback (base) {
  2407. var location = getLocation(base);
  2408. if (!/^\/#/.test(location)) {
  2409. window.location.replace(cleanPath(base + '/#' + location));
  2410. return true
  2411. }
  2412. }
  2413. function ensureSlash () {
  2414. var path = getHash();
  2415. if (path.charAt(0) === '/') {
  2416. return true
  2417. }
  2418. replaceHash('/' + path);
  2419. return false
  2420. }
  2421. function getHash () {
  2422. // We can't use window.location.hash here because it's not
  2423. // consistent across browsers - Firefox will pre-decode it!
  2424. var href = window.location.href;
  2425. var index = href.indexOf('#');
  2426. // empty path
  2427. if (index < 0) { return '' }
  2428. href = href.slice(index + 1);
  2429. return href
  2430. }
  2431. function getUrl (path) {
  2432. var href = window.location.href;
  2433. var i = href.indexOf('#');
  2434. var base = i >= 0 ? href.slice(0, i) : href;
  2435. return (base + "#" + path)
  2436. }
  2437. function pushHash (path) {
  2438. if (supportsPushState) {
  2439. pushState(getUrl(path));
  2440. } else {
  2441. window.location.hash = path;
  2442. }
  2443. }
  2444. function replaceHash (path) {
  2445. if (supportsPushState) {
  2446. replaceState(getUrl(path));
  2447. } else {
  2448. window.location.replace(getUrl(path));
  2449. }
  2450. }
  2451. /* */
  2452. var AbstractHistory = /*@__PURE__*/(function (History) {
  2453. function AbstractHistory (router, base) {
  2454. History.call(this, router, base);
  2455. this.stack = [];
  2456. this.index = -1;
  2457. }
  2458. if ( History ) AbstractHistory.__proto__ = History;
  2459. AbstractHistory.prototype = Object.create( History && History.prototype );
  2460. AbstractHistory.prototype.constructor = AbstractHistory;
  2461. AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
  2462. var this$1 = this;
  2463. this.transitionTo(
  2464. location,
  2465. function (route) {
  2466. this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
  2467. this$1.index++;
  2468. onComplete && onComplete(route);
  2469. },
  2470. onAbort
  2471. );
  2472. };
  2473. AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  2474. var this$1 = this;
  2475. this.transitionTo(
  2476. location,
  2477. function (route) {
  2478. this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
  2479. onComplete && onComplete(route);
  2480. },
  2481. onAbort
  2482. );
  2483. };
  2484. AbstractHistory.prototype.go = function go (n) {
  2485. var this$1 = this;
  2486. var targetIndex = this.index + n;
  2487. if (targetIndex < 0 || targetIndex >= this.stack.length) {
  2488. return
  2489. }
  2490. var route = this.stack[targetIndex];
  2491. this.confirmTransition(
  2492. route,
  2493. function () {
  2494. var prev = this$1.current;
  2495. this$1.index = targetIndex;
  2496. this$1.updateRoute(route);
  2497. this$1.router.afterHooks.forEach(function (hook) {
  2498. hook && hook(route, prev);
  2499. });
  2500. },
  2501. function (err) {
  2502. if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
  2503. this$1.index = targetIndex;
  2504. }
  2505. }
  2506. );
  2507. };
  2508. AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2509. var current = this.stack[this.stack.length - 1];
  2510. return current ? current.fullPath : '/'
  2511. };
  2512. AbstractHistory.prototype.ensureURL = function ensureURL () {
  2513. // noop
  2514. };
  2515. return AbstractHistory;
  2516. }(History));
  2517. /* */
  2518. var VueRouter = function VueRouter (options) {
  2519. if ( options === void 0 ) options = {};
  2520. this.app = null;
  2521. this.apps = [];
  2522. this.options = options;
  2523. this.beforeHooks = [];
  2524. this.resolveHooks = [];
  2525. this.afterHooks = [];
  2526. this.matcher = createMatcher(options.routes || [], this);
  2527. var mode = options.mode || 'hash';
  2528. this.fallback =
  2529. mode === 'history' && !supportsPushState && options.fallback !== false;
  2530. if (this.fallback) {
  2531. mode = 'hash';
  2532. }
  2533. if (!inBrowser) {
  2534. mode = 'abstract';
  2535. }
  2536. this.mode = mode;
  2537. switch (mode) {
  2538. case 'history':
  2539. this.history = new HTML5History(this, options.base);
  2540. break
  2541. case 'hash':
  2542. this.history = new HashHistory(this, options.base, this.fallback);
  2543. break
  2544. case 'abstract':
  2545. this.history = new AbstractHistory(this, options.base);
  2546. break
  2547. default:
  2548. if (process.env.NODE_ENV !== 'production') {
  2549. assert(false, ("invalid mode: " + mode));
  2550. }
  2551. }
  2552. };
  2553. var prototypeAccessors = { currentRoute: { configurable: true } };
  2554. VueRouter.prototype.match = function match (raw, current, redirectedFrom) {
  2555. return this.matcher.match(raw, current, redirectedFrom)
  2556. };
  2557. prototypeAccessors.currentRoute.get = function () {
  2558. return this.history && this.history.current
  2559. };
  2560. VueRouter.prototype.init = function init (app /* Vue component instance */) {
  2561. var this$1 = this;
  2562. process.env.NODE_ENV !== 'production' &&
  2563. assert(
  2564. install.installed,
  2565. "not installed. Make sure to call `Vue.use(VueRouter)` " +
  2566. "before creating root instance."
  2567. );
  2568. this.apps.push(app);
  2569. // set up app destroyed handler
  2570. // https://github.com/vuejs/vue-router/issues/2639
  2571. app.$once('hook:destroyed', function () {
  2572. // clean out app from this.apps array once destroyed
  2573. var index = this$1.apps.indexOf(app);
  2574. if (index > -1) { this$1.apps.splice(index, 1); }
  2575. // ensure we still have a main app or null if no apps
  2576. // we do not release the router so it can be reused
  2577. if (this$1.app === app) { this$1.app = this$1.apps[0] || null; }
  2578. if (!this$1.app) { this$1.history.teardown(); }
  2579. });
  2580. // main app previously initialized
  2581. // return as we don't need to set up new history listener
  2582. if (this.app) {
  2583. return
  2584. }
  2585. this.app = app;
  2586. var history = this.history;
  2587. if (history instanceof HTML5History || history instanceof HashHistory) {
  2588. var handleInitialScroll = function (routeOrError) {
  2589. var from = history.current;
  2590. var expectScroll = this$1.options.scrollBehavior;
  2591. var supportsScroll = supportsPushState && expectScroll;
  2592. if (supportsScroll && 'fullPath' in routeOrError) {
  2593. handleScroll(this$1, routeOrError, from, false);
  2594. }
  2595. };
  2596. var setupListeners = function (routeOrError) {
  2597. history.setupListeners();
  2598. handleInitialScroll(routeOrError);
  2599. };
  2600. history.transitionTo(
  2601. history.getCurrentLocation(),
  2602. setupListeners,
  2603. setupListeners
  2604. );
  2605. }
  2606. history.listen(function (route) {
  2607. this$1.apps.forEach(function (app) {
  2608. app._route = route;
  2609. });
  2610. });
  2611. };
  2612. VueRouter.prototype.beforeEach = function beforeEach (fn) {
  2613. return registerHook(this.beforeHooks, fn)
  2614. };
  2615. VueRouter.prototype.beforeResolve = function beforeResolve (fn) {
  2616. return registerHook(this.resolveHooks, fn)
  2617. };
  2618. VueRouter.prototype.afterEach = function afterEach (fn) {
  2619. return registerHook(this.afterHooks, fn)
  2620. };
  2621. VueRouter.prototype.onReady = function onReady (cb, errorCb) {
  2622. this.history.onReady(cb, errorCb);
  2623. };
  2624. VueRouter.prototype.onError = function onError (errorCb) {
  2625. this.history.onError(errorCb);
  2626. };
  2627. VueRouter.prototype.push = function push (location, onComplete, onAbort) {
  2628. var this$1 = this;
  2629. // $flow-disable-line
  2630. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  2631. return new Promise(function (resolve, reject) {
  2632. this$1.history.push(location, resolve, reject);
  2633. })
  2634. } else {
  2635. this.history.push(location, onComplete, onAbort);
  2636. }
  2637. };
  2638. VueRouter.prototype.replace = function replace (location, onComplete, onAbort) {
  2639. var this$1 = this;
  2640. // $flow-disable-line
  2641. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  2642. return new Promise(function (resolve, reject) {
  2643. this$1.history.replace(location, resolve, reject);
  2644. })
  2645. } else {
  2646. this.history.replace(location, onComplete, onAbort);
  2647. }
  2648. };
  2649. VueRouter.prototype.go = function go (n) {
  2650. this.history.go(n);
  2651. };
  2652. VueRouter.prototype.back = function back () {
  2653. this.go(-1);
  2654. };
  2655. VueRouter.prototype.forward = function forward () {
  2656. this.go(1);
  2657. };
  2658. VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
  2659. var route = to
  2660. ? to.matched
  2661. ? to
  2662. : this.resolve(to).route
  2663. : this.currentRoute;
  2664. if (!route) {
  2665. return []
  2666. }
  2667. return [].concat.apply(
  2668. [],
  2669. route.matched.map(function (m) {
  2670. return Object.keys(m.components).map(function (key) {
  2671. return m.components[key]
  2672. })
  2673. })
  2674. )
  2675. };
  2676. VueRouter.prototype.resolve = function resolve (
  2677. to,
  2678. current,
  2679. append
  2680. ) {
  2681. current = current || this.history.current;
  2682. var location = normalizeLocation(to, current, append, this);
  2683. var route = this.match(location, current);
  2684. var fullPath = route.redirectedFrom || route.fullPath;
  2685. var base = this.history.base;
  2686. var href = createHref(base, fullPath, this.mode);
  2687. return {
  2688. location: location,
  2689. route: route,
  2690. href: href,
  2691. // for backwards compat
  2692. normalizedTo: location,
  2693. resolved: route
  2694. }
  2695. };
  2696. VueRouter.prototype.getRoutes = function getRoutes () {
  2697. return this.matcher.getRoutes()
  2698. };
  2699. VueRouter.prototype.addRoute = function addRoute (parentOrRoute, route) {
  2700. this.matcher.addRoute(parentOrRoute, route);
  2701. if (this.history.current !== START) {
  2702. this.history.transitionTo(this.history.getCurrentLocation());
  2703. }
  2704. };
  2705. VueRouter.prototype.addRoutes = function addRoutes (routes) {
  2706. if (process.env.NODE_ENV !== 'production') {
  2707. warn(false, 'router.addRoutes() is deprecated and has been removed in Vue Router 4. Use router.addRoute() instead.');
  2708. }
  2709. this.matcher.addRoutes(routes);
  2710. if (this.history.current !== START) {
  2711. this.history.transitionTo(this.history.getCurrentLocation());
  2712. }
  2713. };
  2714. Object.defineProperties( VueRouter.prototype, prototypeAccessors );
  2715. function registerHook (list, fn) {
  2716. list.push(fn);
  2717. return function () {
  2718. var i = list.indexOf(fn);
  2719. if (i > -1) { list.splice(i, 1); }
  2720. }
  2721. }
  2722. function createHref (base, fullPath, mode) {
  2723. var path = mode === 'hash' ? '#' + fullPath : fullPath;
  2724. return base ? cleanPath(base + '/' + path) : path
  2725. }
  2726. VueRouter.install = install;
  2727. VueRouter.version = '3.5.1';
  2728. VueRouter.isNavigationFailure = isNavigationFailure;
  2729. VueRouter.NavigationFailureType = NavigationFailureType;
  2730. VueRouter.START_LOCATION = START;
  2731. if (inBrowser && window.Vue) {
  2732. window.Vue.use(VueRouter);
  2733. }
  2734. module.exports = VueRouter;