vue-router.js 78 KB

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