vue-router.common.js 73 KB

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