vuex.esm-browser.prod.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. /*!
  2. * vuex v4.0.2
  3. * (c) 2021 Evan You
  4. * @license MIT
  5. */
  6. import { inject, reactive, watch } from 'vue';
  7. import { setupDevtoolsPlugin } from '@vue/devtools-api';
  8. var storeKey = 'store';
  9. function useStore (key) {
  10. if ( key === void 0 ) key = null;
  11. return inject(key !== null ? key : storeKey)
  12. }
  13. /**
  14. * Get the first item that pass the test
  15. * by second argument function
  16. *
  17. * @param {Array} list
  18. * @param {Function} f
  19. * @return {*}
  20. */
  21. function find (list, f) {
  22. return list.filter(f)[0]
  23. }
  24. /**
  25. * Deep copy the given object considering circular structure.
  26. * This function caches all nested objects and its copies.
  27. * If it detects circular structure, use cached copy to avoid infinite loop.
  28. *
  29. * @param {*} obj
  30. * @param {Array<Object>} cache
  31. * @return {*}
  32. */
  33. function deepCopy (obj, cache) {
  34. if ( cache === void 0 ) cache = [];
  35. // just return if obj is immutable value
  36. if (obj === null || typeof obj !== 'object') {
  37. return obj
  38. }
  39. // if obj is hit, it is in circular structure
  40. var hit = find(cache, function (c) { return c.original === obj; });
  41. if (hit) {
  42. return hit.copy
  43. }
  44. var copy = Array.isArray(obj) ? [] : {};
  45. // put the copy into cache at first
  46. // because we want to refer it in recursive deepCopy
  47. cache.push({
  48. original: obj,
  49. copy: copy
  50. });
  51. Object.keys(obj).forEach(function (key) {
  52. copy[key] = deepCopy(obj[key], cache);
  53. });
  54. return copy
  55. }
  56. /**
  57. * forEach for object
  58. */
  59. function forEachValue (obj, fn) {
  60. Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
  61. }
  62. function isObject (obj) {
  63. return obj !== null && typeof obj === 'object'
  64. }
  65. function isPromise (val) {
  66. return val && typeof val.then === 'function'
  67. }
  68. function partial (fn, arg) {
  69. return function () {
  70. return fn(arg)
  71. }
  72. }
  73. function genericSubscribe (fn, subs, options) {
  74. if (subs.indexOf(fn) < 0) {
  75. options && options.prepend
  76. ? subs.unshift(fn)
  77. : subs.push(fn);
  78. }
  79. return function () {
  80. var i = subs.indexOf(fn);
  81. if (i > -1) {
  82. subs.splice(i, 1);
  83. }
  84. }
  85. }
  86. function resetStore (store, hot) {
  87. store._actions = Object.create(null);
  88. store._mutations = Object.create(null);
  89. store._wrappedGetters = Object.create(null);
  90. store._modulesNamespaceMap = Object.create(null);
  91. var state = store.state;
  92. // init all modules
  93. installModule(store, state, [], store._modules.root, true);
  94. // reset state
  95. resetStoreState(store, state, hot);
  96. }
  97. function resetStoreState (store, state, hot) {
  98. var oldState = store._state;
  99. // bind store public getters
  100. store.getters = {};
  101. // reset local getters cache
  102. store._makeLocalGettersCache = Object.create(null);
  103. var wrappedGetters = store._wrappedGetters;
  104. var computedObj = {};
  105. forEachValue(wrappedGetters, function (fn, key) {
  106. // use computed to leverage its lazy-caching mechanism
  107. // direct inline function use will lead to closure preserving oldState.
  108. // using partial to return function with only arguments preserved in closure environment.
  109. computedObj[key] = partial(fn, store);
  110. Object.defineProperty(store.getters, key, {
  111. // TODO: use `computed` when it's possible. at the moment we can't due to
  112. // https://github.com/vuejs/vuex/pull/1883
  113. get: function () { return computedObj[key](); },
  114. enumerable: true // for local getters
  115. });
  116. });
  117. store._state = reactive({
  118. data: state
  119. });
  120. // enable strict mode for new state
  121. if (store.strict) {
  122. enableStrictMode(store);
  123. }
  124. if (oldState) {
  125. if (hot) {
  126. // dispatch changes in all subscribed watchers
  127. // to force getter re-evaluation for hot reloading.
  128. store._withCommit(function () {
  129. oldState.data = null;
  130. });
  131. }
  132. }
  133. }
  134. function installModule (store, rootState, path, module, hot) {
  135. var isRoot = !path.length;
  136. var namespace = store._modules.getNamespace(path);
  137. // register in namespace map
  138. if (module.namespaced) {
  139. if (store._modulesNamespaceMap[namespace] && false) {
  140. console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
  141. }
  142. store._modulesNamespaceMap[namespace] = module;
  143. }
  144. // set state
  145. if (!isRoot && !hot) {
  146. var parentState = getNestedState(rootState, path.slice(0, -1));
  147. var moduleName = path[path.length - 1];
  148. store._withCommit(function () {
  149. parentState[moduleName] = module.state;
  150. });
  151. }
  152. var local = module.context = makeLocalContext(store, namespace, path);
  153. module.forEachMutation(function (mutation, key) {
  154. var namespacedType = namespace + key;
  155. registerMutation(store, namespacedType, mutation, local);
  156. });
  157. module.forEachAction(function (action, key) {
  158. var type = action.root ? key : namespace + key;
  159. var handler = action.handler || action;
  160. registerAction(store, type, handler, local);
  161. });
  162. module.forEachGetter(function (getter, key) {
  163. var namespacedType = namespace + key;
  164. registerGetter(store, namespacedType, getter, local);
  165. });
  166. module.forEachChild(function (child, key) {
  167. installModule(store, rootState, path.concat(key), child, hot);
  168. });
  169. }
  170. /**
  171. * make localized dispatch, commit, getters and state
  172. * if there is no namespace, just use root ones
  173. */
  174. function makeLocalContext (store, namespace, path) {
  175. var noNamespace = namespace === '';
  176. var local = {
  177. dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
  178. var args = unifyObjectStyle(_type, _payload, _options);
  179. var payload = args.payload;
  180. var options = args.options;
  181. var type = args.type;
  182. if (!options || !options.root) {
  183. type = namespace + type;
  184. }
  185. return store.dispatch(type, payload)
  186. },
  187. commit: noNamespace ? store.commit : function (_type, _payload, _options) {
  188. var args = unifyObjectStyle(_type, _payload, _options);
  189. var payload = args.payload;
  190. var options = args.options;
  191. var type = args.type;
  192. if (!options || !options.root) {
  193. type = namespace + type;
  194. }
  195. store.commit(type, payload, options);
  196. }
  197. };
  198. // getters and state object must be gotten lazily
  199. // because they will be changed by state update
  200. Object.defineProperties(local, {
  201. getters: {
  202. get: noNamespace
  203. ? function () { return store.getters; }
  204. : function () { return makeLocalGetters(store, namespace); }
  205. },
  206. state: {
  207. get: function () { return getNestedState(store.state, path); }
  208. }
  209. });
  210. return local
  211. }
  212. function makeLocalGetters (store, namespace) {
  213. if (!store._makeLocalGettersCache[namespace]) {
  214. var gettersProxy = {};
  215. var splitPos = namespace.length;
  216. Object.keys(store.getters).forEach(function (type) {
  217. // skip if the target getter is not match this namespace
  218. if (type.slice(0, splitPos) !== namespace) { return }
  219. // extract local getter type
  220. var localType = type.slice(splitPos);
  221. // Add a port to the getters proxy.
  222. // Define as getter property because
  223. // we do not want to evaluate the getters in this time.
  224. Object.defineProperty(gettersProxy, localType, {
  225. get: function () { return store.getters[type]; },
  226. enumerable: true
  227. });
  228. });
  229. store._makeLocalGettersCache[namespace] = gettersProxy;
  230. }
  231. return store._makeLocalGettersCache[namespace]
  232. }
  233. function registerMutation (store, type, handler, local) {
  234. var entry = store._mutations[type] || (store._mutations[type] = []);
  235. entry.push(function wrappedMutationHandler (payload) {
  236. handler.call(store, local.state, payload);
  237. });
  238. }
  239. function registerAction (store, type, handler, local) {
  240. var entry = store._actions[type] || (store._actions[type] = []);
  241. entry.push(function wrappedActionHandler (payload) {
  242. var res = handler.call(store, {
  243. dispatch: local.dispatch,
  244. commit: local.commit,
  245. getters: local.getters,
  246. state: local.state,
  247. rootGetters: store.getters,
  248. rootState: store.state
  249. }, payload);
  250. if (!isPromise(res)) {
  251. res = Promise.resolve(res);
  252. }
  253. if (store._devtoolHook) {
  254. return res.catch(function (err) {
  255. store._devtoolHook.emit('vuex:error', err);
  256. throw err
  257. })
  258. } else {
  259. return res
  260. }
  261. });
  262. }
  263. function registerGetter (store, type, rawGetter, local) {
  264. if (store._wrappedGetters[type]) {
  265. return
  266. }
  267. store._wrappedGetters[type] = function wrappedGetter (store) {
  268. return rawGetter(
  269. local.state, // local state
  270. local.getters, // local getters
  271. store.state, // root state
  272. store.getters // root getters
  273. )
  274. };
  275. }
  276. function enableStrictMode (store) {
  277. watch(function () { return store._state.data; }, function () {
  278. }, { deep: true, flush: 'sync' });
  279. }
  280. function getNestedState (state, path) {
  281. return path.reduce(function (state, key) { return state[key]; }, state)
  282. }
  283. function unifyObjectStyle (type, payload, options) {
  284. if (isObject(type) && type.type) {
  285. options = payload;
  286. payload = type;
  287. type = type.type;
  288. }
  289. return { type: type, payload: payload, options: options }
  290. }
  291. var LABEL_VUEX_BINDINGS = 'vuex bindings';
  292. var MUTATIONS_LAYER_ID = 'vuex:mutations';
  293. var ACTIONS_LAYER_ID = 'vuex:actions';
  294. var INSPECTOR_ID = 'vuex';
  295. var actionId = 0;
  296. function addDevtools (app, store) {
  297. setupDevtoolsPlugin(
  298. {
  299. id: 'org.vuejs.vuex',
  300. app: app,
  301. label: 'Vuex',
  302. homepage: 'https://next.vuex.vuejs.org/',
  303. logo: 'https://vuejs.org/images/icons/favicon-96x96.png',
  304. packageName: 'vuex',
  305. componentStateTypes: [LABEL_VUEX_BINDINGS]
  306. },
  307. function (api) {
  308. api.addTimelineLayer({
  309. id: MUTATIONS_LAYER_ID,
  310. label: 'Vuex Mutations',
  311. color: COLOR_LIME_500
  312. });
  313. api.addTimelineLayer({
  314. id: ACTIONS_LAYER_ID,
  315. label: 'Vuex Actions',
  316. color: COLOR_LIME_500
  317. });
  318. api.addInspector({
  319. id: INSPECTOR_ID,
  320. label: 'Vuex',
  321. icon: 'storage',
  322. treeFilterPlaceholder: 'Filter stores...'
  323. });
  324. api.on.getInspectorTree(function (payload) {
  325. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  326. if (payload.filter) {
  327. var nodes = [];
  328. flattenStoreForInspectorTree(nodes, store._modules.root, payload.filter, '');
  329. payload.rootNodes = nodes;
  330. } else {
  331. payload.rootNodes = [
  332. formatStoreForInspectorTree(store._modules.root, '')
  333. ];
  334. }
  335. }
  336. });
  337. api.on.getInspectorState(function (payload) {
  338. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  339. var modulePath = payload.nodeId;
  340. makeLocalGetters(store, modulePath);
  341. payload.state = formatStoreForInspectorState(
  342. getStoreModule(store._modules, modulePath),
  343. modulePath === 'root' ? store.getters : store._makeLocalGettersCache,
  344. modulePath
  345. );
  346. }
  347. });
  348. api.on.editInspectorState(function (payload) {
  349. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  350. var modulePath = payload.nodeId;
  351. var path = payload.path;
  352. if (modulePath !== 'root') {
  353. path = modulePath.split('/').filter(Boolean).concat( path);
  354. }
  355. store._withCommit(function () {
  356. payload.set(store._state.data, path, payload.state.value);
  357. });
  358. }
  359. });
  360. store.subscribe(function (mutation, state) {
  361. var data = {};
  362. if (mutation.payload) {
  363. data.payload = mutation.payload;
  364. }
  365. data.state = state;
  366. api.notifyComponentUpdate();
  367. api.sendInspectorTree(INSPECTOR_ID);
  368. api.sendInspectorState(INSPECTOR_ID);
  369. api.addTimelineEvent({
  370. layerId: MUTATIONS_LAYER_ID,
  371. event: {
  372. time: Date.now(),
  373. title: mutation.type,
  374. data: data
  375. }
  376. });
  377. });
  378. store.subscribeAction({
  379. before: function (action, state) {
  380. var data = {};
  381. if (action.payload) {
  382. data.payload = action.payload;
  383. }
  384. action._id = actionId++;
  385. action._time = Date.now();
  386. data.state = state;
  387. api.addTimelineEvent({
  388. layerId: ACTIONS_LAYER_ID,
  389. event: {
  390. time: action._time,
  391. title: action.type,
  392. groupId: action._id,
  393. subtitle: 'start',
  394. data: data
  395. }
  396. });
  397. },
  398. after: function (action, state) {
  399. var data = {};
  400. var duration = Date.now() - action._time;
  401. data.duration = {
  402. _custom: {
  403. type: 'duration',
  404. display: (duration + "ms"),
  405. tooltip: 'Action duration',
  406. value: duration
  407. }
  408. };
  409. if (action.payload) {
  410. data.payload = action.payload;
  411. }
  412. data.state = state;
  413. api.addTimelineEvent({
  414. layerId: ACTIONS_LAYER_ID,
  415. event: {
  416. time: Date.now(),
  417. title: action.type,
  418. groupId: action._id,
  419. subtitle: 'end',
  420. data: data
  421. }
  422. });
  423. }
  424. });
  425. }
  426. );
  427. }
  428. // extracted from tailwind palette
  429. var COLOR_LIME_500 = 0x84cc16;
  430. var COLOR_DARK = 0x666666;
  431. var COLOR_WHITE = 0xffffff;
  432. var TAG_NAMESPACED = {
  433. label: 'namespaced',
  434. textColor: COLOR_WHITE,
  435. backgroundColor: COLOR_DARK
  436. };
  437. /**
  438. * @param {string} path
  439. */
  440. function extractNameFromPath (path) {
  441. return path && path !== 'root' ? path.split('/').slice(-2, -1)[0] : 'Root'
  442. }
  443. /**
  444. * @param {*} module
  445. * @return {import('@vue/devtools-api').CustomInspectorNode}
  446. */
  447. function formatStoreForInspectorTree (module, path) {
  448. return {
  449. id: path || 'root',
  450. // all modules end with a `/`, we want the last segment only
  451. // cart/ -> cart
  452. // nested/cart/ -> cart
  453. label: extractNameFromPath(path),
  454. tags: module.namespaced ? [TAG_NAMESPACED] : [],
  455. children: Object.keys(module._children).map(function (moduleName) { return formatStoreForInspectorTree(
  456. module._children[moduleName],
  457. path + moduleName + '/'
  458. ); }
  459. )
  460. }
  461. }
  462. /**
  463. * @param {import('@vue/devtools-api').CustomInspectorNode[]} result
  464. * @param {*} module
  465. * @param {string} filter
  466. * @param {string} path
  467. */
  468. function flattenStoreForInspectorTree (result, module, filter, path) {
  469. if (path.includes(filter)) {
  470. result.push({
  471. id: path || 'root',
  472. label: path.endsWith('/') ? path.slice(0, path.length - 1) : path || 'Root',
  473. tags: module.namespaced ? [TAG_NAMESPACED] : []
  474. });
  475. }
  476. Object.keys(module._children).forEach(function (moduleName) {
  477. flattenStoreForInspectorTree(result, module._children[moduleName], filter, path + moduleName + '/');
  478. });
  479. }
  480. /**
  481. * @param {*} module
  482. * @return {import('@vue/devtools-api').CustomInspectorState}
  483. */
  484. function formatStoreForInspectorState (module, getters, path) {
  485. getters = path === 'root' ? getters : getters[path];
  486. var gettersKeys = Object.keys(getters);
  487. var storeState = {
  488. state: Object.keys(module.state).map(function (key) { return ({
  489. key: key,
  490. editable: true,
  491. value: module.state[key]
  492. }); })
  493. };
  494. if (gettersKeys.length) {
  495. var tree = transformPathsToObjectTree(getters);
  496. storeState.getters = Object.keys(tree).map(function (key) { return ({
  497. key: key.endsWith('/') ? extractNameFromPath(key) : key,
  498. editable: false,
  499. value: canThrow(function () { return tree[key]; })
  500. }); });
  501. }
  502. return storeState
  503. }
  504. function transformPathsToObjectTree (getters) {
  505. var result = {};
  506. Object.keys(getters).forEach(function (key) {
  507. var path = key.split('/');
  508. if (path.length > 1) {
  509. var target = result;
  510. var leafKey = path.pop();
  511. path.forEach(function (p) {
  512. if (!target[p]) {
  513. target[p] = {
  514. _custom: {
  515. value: {},
  516. display: p,
  517. tooltip: 'Module',
  518. abstract: true
  519. }
  520. };
  521. }
  522. target = target[p]._custom.value;
  523. });
  524. target[leafKey] = canThrow(function () { return getters[key]; });
  525. } else {
  526. result[key] = canThrow(function () { return getters[key]; });
  527. }
  528. });
  529. return result
  530. }
  531. function getStoreModule (moduleMap, path) {
  532. var names = path.split('/').filter(function (n) { return n; });
  533. return names.reduce(
  534. function (module, moduleName, i) {
  535. var child = module[moduleName];
  536. if (!child) {
  537. throw new Error(("Missing module \"" + moduleName + "\" for path \"" + path + "\"."))
  538. }
  539. return i === names.length - 1 ? child : child._children
  540. },
  541. path === 'root' ? moduleMap : moduleMap.root._children
  542. )
  543. }
  544. function canThrow (cb) {
  545. try {
  546. return cb()
  547. } catch (e) {
  548. return e
  549. }
  550. }
  551. // Base data struct for store's module, package with some attribute and method
  552. var Module = function Module (rawModule, runtime) {
  553. this.runtime = runtime;
  554. // Store some children item
  555. this._children = Object.create(null);
  556. // Store the origin module object which passed by programmer
  557. this._rawModule = rawModule;
  558. var rawState = rawModule.state;
  559. // Store the origin module's state
  560. this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
  561. };
  562. var prototypeAccessors$1 = { namespaced: { configurable: true } };
  563. prototypeAccessors$1.namespaced.get = function () {
  564. return !!this._rawModule.namespaced
  565. };
  566. Module.prototype.addChild = function addChild (key, module) {
  567. this._children[key] = module;
  568. };
  569. Module.prototype.removeChild = function removeChild (key) {
  570. delete this._children[key];
  571. };
  572. Module.prototype.getChild = function getChild (key) {
  573. return this._children[key]
  574. };
  575. Module.prototype.hasChild = function hasChild (key) {
  576. return key in this._children
  577. };
  578. Module.prototype.update = function update (rawModule) {
  579. this._rawModule.namespaced = rawModule.namespaced;
  580. if (rawModule.actions) {
  581. this._rawModule.actions = rawModule.actions;
  582. }
  583. if (rawModule.mutations) {
  584. this._rawModule.mutations = rawModule.mutations;
  585. }
  586. if (rawModule.getters) {
  587. this._rawModule.getters = rawModule.getters;
  588. }
  589. };
  590. Module.prototype.forEachChild = function forEachChild (fn) {
  591. forEachValue(this._children, fn);
  592. };
  593. Module.prototype.forEachGetter = function forEachGetter (fn) {
  594. if (this._rawModule.getters) {
  595. forEachValue(this._rawModule.getters, fn);
  596. }
  597. };
  598. Module.prototype.forEachAction = function forEachAction (fn) {
  599. if (this._rawModule.actions) {
  600. forEachValue(this._rawModule.actions, fn);
  601. }
  602. };
  603. Module.prototype.forEachMutation = function forEachMutation (fn) {
  604. if (this._rawModule.mutations) {
  605. forEachValue(this._rawModule.mutations, fn);
  606. }
  607. };
  608. Object.defineProperties( Module.prototype, prototypeAccessors$1 );
  609. var ModuleCollection = function ModuleCollection (rawRootModule) {
  610. // register root module (Vuex.Store options)
  611. this.register([], rawRootModule, false);
  612. };
  613. ModuleCollection.prototype.get = function get (path) {
  614. return path.reduce(function (module, key) {
  615. return module.getChild(key)
  616. }, this.root)
  617. };
  618. ModuleCollection.prototype.getNamespace = function getNamespace (path) {
  619. var module = this.root;
  620. return path.reduce(function (namespace, key) {
  621. module = module.getChild(key);
  622. return namespace + (module.namespaced ? key + '/' : '')
  623. }, '')
  624. };
  625. ModuleCollection.prototype.update = function update$1 (rawRootModule) {
  626. update([], this.root, rawRootModule);
  627. };
  628. ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
  629. var this$1$1 = this;
  630. if ( runtime === void 0 ) runtime = true;
  631. var newModule = new Module(rawModule, runtime);
  632. if (path.length === 0) {
  633. this.root = newModule;
  634. } else {
  635. var parent = this.get(path.slice(0, -1));
  636. parent.addChild(path[path.length - 1], newModule);
  637. }
  638. // register nested modules
  639. if (rawModule.modules) {
  640. forEachValue(rawModule.modules, function (rawChildModule, key) {
  641. this$1$1.register(path.concat(key), rawChildModule, runtime);
  642. });
  643. }
  644. };
  645. ModuleCollection.prototype.unregister = function unregister (path) {
  646. var parent = this.get(path.slice(0, -1));
  647. var key = path[path.length - 1];
  648. var child = parent.getChild(key);
  649. if (!child) {
  650. return
  651. }
  652. if (!child.runtime) {
  653. return
  654. }
  655. parent.removeChild(key);
  656. };
  657. ModuleCollection.prototype.isRegistered = function isRegistered (path) {
  658. var parent = this.get(path.slice(0, -1));
  659. var key = path[path.length - 1];
  660. if (parent) {
  661. return parent.hasChild(key)
  662. }
  663. return false
  664. };
  665. function update (path, targetModule, newModule) {
  666. // update target module
  667. targetModule.update(newModule);
  668. // update nested modules
  669. if (newModule.modules) {
  670. for (var key in newModule.modules) {
  671. if (!targetModule.getChild(key)) {
  672. return
  673. }
  674. update(
  675. path.concat(key),
  676. targetModule.getChild(key),
  677. newModule.modules[key]
  678. );
  679. }
  680. }
  681. }
  682. function createStore (options) {
  683. return new Store(options)
  684. }
  685. var Store = function Store (options) {
  686. var this$1$1 = this;
  687. if ( options === void 0 ) options = {};
  688. var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
  689. var strict = options.strict; if ( strict === void 0 ) strict = false;
  690. var devtools = options.devtools;
  691. // store internal state
  692. this._committing = false;
  693. this._actions = Object.create(null);
  694. this._actionSubscribers = [];
  695. this._mutations = Object.create(null);
  696. this._wrappedGetters = Object.create(null);
  697. this._modules = new ModuleCollection(options);
  698. this._modulesNamespaceMap = Object.create(null);
  699. this._subscribers = [];
  700. this._makeLocalGettersCache = Object.create(null);
  701. this._devtools = devtools;
  702. // bind commit and dispatch to self
  703. var store = this;
  704. var ref = this;
  705. var dispatch = ref.dispatch;
  706. var commit = ref.commit;
  707. this.dispatch = function boundDispatch (type, payload) {
  708. return dispatch.call(store, type, payload)
  709. };
  710. this.commit = function boundCommit (type, payload, options) {
  711. return commit.call(store, type, payload, options)
  712. };
  713. // strict mode
  714. this.strict = strict;
  715. var state = this._modules.root.state;
  716. // init root module.
  717. // this also recursively registers all sub-modules
  718. // and collects all module getters inside this._wrappedGetters
  719. installModule(this, state, [], this._modules.root);
  720. // initialize the store state, which is responsible for the reactivity
  721. // (also registers _wrappedGetters as computed properties)
  722. resetStoreState(this, state);
  723. // apply plugins
  724. plugins.forEach(function (plugin) { return plugin(this$1$1); });
  725. };
  726. var prototypeAccessors = { state: { configurable: true } };
  727. Store.prototype.install = function install (app, injectKey) {
  728. app.provide(injectKey || storeKey, this);
  729. app.config.globalProperties.$store = this;
  730. var useDevtools = this._devtools !== undefined
  731. ? this._devtools
  732. : false;
  733. if (useDevtools) {
  734. addDevtools(app, this);
  735. }
  736. };
  737. prototypeAccessors.state.get = function () {
  738. return this._state.data
  739. };
  740. prototypeAccessors.state.set = function (v) {
  741. };
  742. Store.prototype.commit = function commit (_type, _payload, _options) {
  743. var this$1$1 = this;
  744. // check object-style commit
  745. var ref = unifyObjectStyle(_type, _payload, _options);
  746. var type = ref.type;
  747. var payload = ref.payload;
  748. var mutation = { type: type, payload: payload };
  749. var entry = this._mutations[type];
  750. if (!entry) {
  751. return
  752. }
  753. this._withCommit(function () {
  754. entry.forEach(function commitIterator (handler) {
  755. handler(payload);
  756. });
  757. });
  758. this._subscribers
  759. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  760. .forEach(function (sub) { return sub(mutation, this$1$1.state); });
  761. };
  762. Store.prototype.dispatch = function dispatch (_type, _payload) {
  763. var this$1$1 = this;
  764. // check object-style dispatch
  765. var ref = unifyObjectStyle(_type, _payload);
  766. var type = ref.type;
  767. var payload = ref.payload;
  768. var action = { type: type, payload: payload };
  769. var entry = this._actions[type];
  770. if (!entry) {
  771. return
  772. }
  773. try {
  774. this._actionSubscribers
  775. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  776. .filter(function (sub) { return sub.before; })
  777. .forEach(function (sub) { return sub.before(action, this$1$1.state); });
  778. } catch (e) {
  779. }
  780. var result = entry.length > 1
  781. ? Promise.all(entry.map(function (handler) { return handler(payload); }))
  782. : entry[0](payload);
  783. return new Promise(function (resolve, reject) {
  784. result.then(function (res) {
  785. try {
  786. this$1$1._actionSubscribers
  787. .filter(function (sub) { return sub.after; })
  788. .forEach(function (sub) { return sub.after(action, this$1$1.state); });
  789. } catch (e) {
  790. }
  791. resolve(res);
  792. }, function (error) {
  793. try {
  794. this$1$1._actionSubscribers
  795. .filter(function (sub) { return sub.error; })
  796. .forEach(function (sub) { return sub.error(action, this$1$1.state, error); });
  797. } catch (e) {
  798. }
  799. reject(error);
  800. });
  801. })
  802. };
  803. Store.prototype.subscribe = function subscribe (fn, options) {
  804. return genericSubscribe(fn, this._subscribers, options)
  805. };
  806. Store.prototype.subscribeAction = function subscribeAction (fn, options) {
  807. var subs = typeof fn === 'function' ? { before: fn } : fn;
  808. return genericSubscribe(subs, this._actionSubscribers, options)
  809. };
  810. Store.prototype.watch = function watch$1 (getter, cb, options) {
  811. var this$1$1 = this;
  812. return watch(function () { return getter(this$1$1.state, this$1$1.getters); }, cb, Object.assign({}, options))
  813. };
  814. Store.prototype.replaceState = function replaceState (state) {
  815. var this$1$1 = this;
  816. this._withCommit(function () {
  817. this$1$1._state.data = state;
  818. });
  819. };
  820. Store.prototype.registerModule = function registerModule (path, rawModule, options) {
  821. if ( options === void 0 ) options = {};
  822. if (typeof path === 'string') { path = [path]; }
  823. this._modules.register(path, rawModule);
  824. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  825. // reset store to update getters...
  826. resetStoreState(this, this.state);
  827. };
  828. Store.prototype.unregisterModule = function unregisterModule (path) {
  829. var this$1$1 = this;
  830. if (typeof path === 'string') { path = [path]; }
  831. this._modules.unregister(path);
  832. this._withCommit(function () {
  833. var parentState = getNestedState(this$1$1.state, path.slice(0, -1));
  834. delete parentState[path[path.length - 1]];
  835. });
  836. resetStore(this);
  837. };
  838. Store.prototype.hasModule = function hasModule (path) {
  839. if (typeof path === 'string') { path = [path]; }
  840. return this._modules.isRegistered(path)
  841. };
  842. Store.prototype.hotUpdate = function hotUpdate (newOptions) {
  843. this._modules.update(newOptions);
  844. resetStore(this, true);
  845. };
  846. Store.prototype._withCommit = function _withCommit (fn) {
  847. var committing = this._committing;
  848. this._committing = true;
  849. fn();
  850. this._committing = committing;
  851. };
  852. Object.defineProperties( Store.prototype, prototypeAccessors );
  853. /**
  854. * Reduce the code which written in Vue.js for getting the state.
  855. * @param {String} [namespace] - Module's namespace
  856. * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
  857. * @param {Object}
  858. */
  859. var mapState = normalizeNamespace(function (namespace, states) {
  860. var res = {};
  861. normalizeMap(states).forEach(function (ref) {
  862. var key = ref.key;
  863. var val = ref.val;
  864. res[key] = function mappedState () {
  865. var state = this.$store.state;
  866. var getters = this.$store.getters;
  867. if (namespace) {
  868. var module = getModuleByNamespace(this.$store, 'mapState', namespace);
  869. if (!module) {
  870. return
  871. }
  872. state = module.context.state;
  873. getters = module.context.getters;
  874. }
  875. return typeof val === 'function'
  876. ? val.call(this, state, getters)
  877. : state[val]
  878. };
  879. // mark vuex getter for devtools
  880. res[key].vuex = true;
  881. });
  882. return res
  883. });
  884. /**
  885. * Reduce the code which written in Vue.js for committing the mutation
  886. * @param {String} [namespace] - Module's namespace
  887. * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
  888. * @return {Object}
  889. */
  890. var mapMutations = normalizeNamespace(function (namespace, mutations) {
  891. var res = {};
  892. normalizeMap(mutations).forEach(function (ref) {
  893. var key = ref.key;
  894. var val = ref.val;
  895. res[key] = function mappedMutation () {
  896. var args = [], len = arguments.length;
  897. while ( len-- ) args[ len ] = arguments[ len ];
  898. // Get the commit method from store
  899. var commit = this.$store.commit;
  900. if (namespace) {
  901. var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
  902. if (!module) {
  903. return
  904. }
  905. commit = module.context.commit;
  906. }
  907. return typeof val === 'function'
  908. ? val.apply(this, [commit].concat(args))
  909. : commit.apply(this.$store, [val].concat(args))
  910. };
  911. });
  912. return res
  913. });
  914. /**
  915. * Reduce the code which written in Vue.js for getting the getters
  916. * @param {String} [namespace] - Module's namespace
  917. * @param {Object|Array} getters
  918. * @return {Object}
  919. */
  920. var mapGetters = normalizeNamespace(function (namespace, getters) {
  921. var res = {};
  922. normalizeMap(getters).forEach(function (ref) {
  923. var key = ref.key;
  924. var val = ref.val;
  925. // The namespace has been mutated by normalizeNamespace
  926. val = namespace + val;
  927. res[key] = function mappedGetter () {
  928. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  929. return
  930. }
  931. return this.$store.getters[val]
  932. };
  933. // mark vuex getter for devtools
  934. res[key].vuex = true;
  935. });
  936. return res
  937. });
  938. /**
  939. * Reduce the code which written in Vue.js for dispatch the action
  940. * @param {String} [namespace] - Module's namespace
  941. * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
  942. * @return {Object}
  943. */
  944. var mapActions = normalizeNamespace(function (namespace, actions) {
  945. var res = {};
  946. normalizeMap(actions).forEach(function (ref) {
  947. var key = ref.key;
  948. var val = ref.val;
  949. res[key] = function mappedAction () {
  950. var args = [], len = arguments.length;
  951. while ( len-- ) args[ len ] = arguments[ len ];
  952. // get dispatch function from store
  953. var dispatch = this.$store.dispatch;
  954. if (namespace) {
  955. var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
  956. if (!module) {
  957. return
  958. }
  959. dispatch = module.context.dispatch;
  960. }
  961. return typeof val === 'function'
  962. ? val.apply(this, [dispatch].concat(args))
  963. : dispatch.apply(this.$store, [val].concat(args))
  964. };
  965. });
  966. return res
  967. });
  968. /**
  969. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  970. * @param {String} namespace
  971. * @return {Object}
  972. */
  973. var createNamespacedHelpers = function (namespace) { return ({
  974. mapState: mapState.bind(null, namespace),
  975. mapGetters: mapGetters.bind(null, namespace),
  976. mapMutations: mapMutations.bind(null, namespace),
  977. mapActions: mapActions.bind(null, namespace)
  978. }); };
  979. /**
  980. * Normalize the map
  981. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  982. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  983. * @param {Array|Object} map
  984. * @return {Object}
  985. */
  986. function normalizeMap (map) {
  987. if (!isValidMap(map)) {
  988. return []
  989. }
  990. return Array.isArray(map)
  991. ? map.map(function (key) { return ({ key: key, val: key }); })
  992. : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
  993. }
  994. /**
  995. * Validate whether given map is valid or not
  996. * @param {*} map
  997. * @return {Boolean}
  998. */
  999. function isValidMap (map) {
  1000. return Array.isArray(map) || isObject(map)
  1001. }
  1002. /**
  1003. * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
  1004. * @param {Function} fn
  1005. * @return {Function}
  1006. */
  1007. function normalizeNamespace (fn) {
  1008. return function (namespace, map) {
  1009. if (typeof namespace !== 'string') {
  1010. map = namespace;
  1011. namespace = '';
  1012. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  1013. namespace += '/';
  1014. }
  1015. return fn(namespace, map)
  1016. }
  1017. }
  1018. /**
  1019. * Search a special module from store by namespace. if module not exist, print error message.
  1020. * @param {Object} store
  1021. * @param {String} helper
  1022. * @param {String} namespace
  1023. * @return {Object}
  1024. */
  1025. function getModuleByNamespace (store, helper, namespace) {
  1026. var module = store._modulesNamespaceMap[namespace];
  1027. return module
  1028. }
  1029. // Credits: borrowed code from fcomb/redux-logger
  1030. function createLogger (ref) {
  1031. if ( ref === void 0 ) ref = {};
  1032. var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true;
  1033. var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; };
  1034. var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; };
  1035. var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; };
  1036. var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; };
  1037. var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; };
  1038. var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true;
  1039. var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true;
  1040. var logger = ref.logger; if ( logger === void 0 ) logger = console;
  1041. return function (store) {
  1042. var prevState = deepCopy(store.state);
  1043. if (typeof logger === 'undefined') {
  1044. return
  1045. }
  1046. if (logMutations) {
  1047. store.subscribe(function (mutation, state) {
  1048. var nextState = deepCopy(state);
  1049. if (filter(mutation, prevState, nextState)) {
  1050. var formattedTime = getFormattedTime();
  1051. var formattedMutation = mutationTransformer(mutation);
  1052. var message = "mutation " + (mutation.type) + formattedTime;
  1053. startMessage(logger, message, collapsed);
  1054. logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState));
  1055. logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation);
  1056. logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState));
  1057. endMessage(logger);
  1058. }
  1059. prevState = nextState;
  1060. });
  1061. }
  1062. if (logActions) {
  1063. store.subscribeAction(function (action, state) {
  1064. if (actionFilter(action, state)) {
  1065. var formattedTime = getFormattedTime();
  1066. var formattedAction = actionTransformer(action);
  1067. var message = "action " + (action.type) + formattedTime;
  1068. startMessage(logger, message, collapsed);
  1069. logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction);
  1070. endMessage(logger);
  1071. }
  1072. });
  1073. }
  1074. }
  1075. }
  1076. function startMessage (logger, message, collapsed) {
  1077. var startMessage = collapsed
  1078. ? logger.groupCollapsed
  1079. : logger.group;
  1080. // render
  1081. try {
  1082. startMessage.call(logger, message);
  1083. } catch (e) {
  1084. logger.log(message);
  1085. }
  1086. }
  1087. function endMessage (logger) {
  1088. try {
  1089. logger.groupEnd();
  1090. } catch (e) {
  1091. logger.log('—— log end ——');
  1092. }
  1093. }
  1094. function getFormattedTime () {
  1095. var time = new Date();
  1096. return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)))
  1097. }
  1098. function repeat (str, times) {
  1099. return (new Array(times + 1)).join(str)
  1100. }
  1101. function pad (num, maxLength) {
  1102. return repeat('0', maxLength - num.toString().length) + num
  1103. }
  1104. var index = {
  1105. version: '4.0.2',
  1106. Store: Store,
  1107. storeKey: storeKey,
  1108. createStore: createStore,
  1109. useStore: useStore,
  1110. mapState: mapState,
  1111. mapMutations: mapMutations,
  1112. mapGetters: mapGetters,
  1113. mapActions: mapActions,
  1114. createNamespacedHelpers: createNamespacedHelpers,
  1115. createLogger: createLogger
  1116. };
  1117. export default index;
  1118. export { Store, createLogger, createNamespacedHelpers, createStore, mapActions, mapGetters, mapMutations, mapState, storeKey, useStore };