UNPKG

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