UNPKG

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