vue-router.js 64 KB

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