Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vue-router.common.js 66KB

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