UNPKG

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