From 42752e1a39cbb183beebe33819af5d1a7232ead8 Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Mon, 8 Apr 2019 15:52:16 -0400 Subject: [PATCH 1/8] Allow action subscribers to catch rejections. --- dist/vuex.common.js | 21 ++++++++++++--- src/store.js | 12 +++++++++ test/unit/modules.spec.js | 39 +++++++++++++++++++++++++++ types/index.d.ts | 2 ++ types/test/index.ts | 56 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 127 insertions(+), 3 deletions(-) diff --git a/dist/vuex.common.js b/dist/vuex.common.js index 88436c580..27a577884 100644 --- a/dist/vuex.common.js +++ b/dist/vuex.common.js @@ -41,9 +41,12 @@ function applyMixin (Vue) { } } -var devtoolHook = - typeof window !== 'undefined' && - window.__VUE_DEVTOOLS_GLOBAL_HOOK__; +var target = typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}; +var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; function devtoolPlugin (store) { if (!devtoolHook) { return } @@ -441,6 +444,18 @@ Store.prototype.dispatch = function dispatch (_type, _payload) { } } return res + }, function (e) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.catch; }) + .forEach(function (sub) { return sub.catch(action, this$1.state, e); }); + } catch (_e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in after action catch subscribers: "); + console.error(_e); + } + } + throw e }) }; diff --git a/src/store.js b/src/store.js index dfcc755f8..12c0e48c1 100644 --- a/src/store.js +++ b/src/store.js @@ -156,6 +156,18 @@ export class Store { } } return res + }, e => { + try { + this._actionSubscribers + .filter(sub => sub.catch) + .forEach(sub => sub.catch(action, this.state, e)) + } catch (_e) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`[vuex] error in after action catch subscribers: `) + console.error(_e) + } + } + throw e }) } diff --git a/test/unit/modules.spec.js b/test/unit/modules.spec.js index a776fb582..50885e06e 100644 --- a/test/unit/modules.spec.js +++ b/test/unit/modules.spec.js @@ -701,6 +701,45 @@ describe('Modules', () => { }) }) + it('action catch subscribers', (done) => { + const beforeSpy = jasmine.createSpy() + const afterSpy = jasmine.createSpy() + const catchSpy = jasmine.createSpy() + const error = new Error() + const store = new Vuex.Store({ + actions: { + [TEST]: () => Promise.reject(error) + }, + plugins: [ + store => { + store.subscribeAction({ + before: beforeSpy, + after: afterSpy, + catch: catchSpy + }) + } + ] + }) + store.dispatch(TEST, 2) + expect(beforeSpy).toHaveBeenCalledWith( + { type: TEST, payload: 2 }, + store.state + ) + expect(afterSpy).not.toHaveBeenCalled() + Vue.nextTick(() => { + expect(afterSpy).not.toHaveBeenCalledWith( + { type: TEST, payload: 2 }, + store.state + ) + expect(catchSpy).toHaveBeenCalledWith( + { type: TEST, payload: 2 }, + store.state, + error + ) + done() + }) + }) + it('asserts a mutation should be a function', () => { expect(() => { new Vuex.Store({ diff --git a/types/index.d.ts b/types/index.d.ts index 3cd40067a..e569724cb 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -70,10 +70,12 @@ export interface ActionPayload extends Payload { } export type ActionSubscriber = (action: P, state: S) => any; +export type ActionCatchSubscriber = (action: P, state: S, error: Error) => any; export interface ActionSubscribersObject { before?: ActionSubscriber; after?: ActionSubscriber; + catch?: ActionCatchSubscriber; } export type SubscribeActionOptions = ActionSubscriber | ActionSubscribersObject; diff --git a/types/test/index.ts b/types/test/index.ts index d6af9a4fa..fd7bc4e6c 100644 --- a/types/test/index.ts +++ b/types/test/index.ts @@ -66,11 +66,67 @@ namespace StoreInstance { } }); + store.subscribeAction({ + before(action, state) { + action.type; + action.payload; + state.value; + }, + catch(action, state, error) { + action.type; + action.payload; + state.value; + error; + } + }); + + store.subscribeAction({ + before(action, state) { + action.type; + action.payload; + state.value; + }, + after(action, state) { + action.type; + action.payload; + state.value; + }, + catch(action, state, error) { + action.type; + action.payload; + state.value; + error; + } + }); + + store.subscribeAction({ + after(action, state) { + action.type; + action.payload; + state.value; + } + }); + store.subscribeAction({ after(action, state) { action.type; action.payload; state.value; + }, + catch(action, state, error) { + action.type; + action.payload; + state.value; + error; + } + }); + + store.subscribeAction({ + catch(action, state, error) { + action.type; + action.payload; + state.value; + error; } }); From ab5e213f0e79d43e953c252ac1906388980d0af2 Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Tue, 28 Apr 2020 09:49:54 -0400 Subject: [PATCH 2/8] Removed dist folder and wrapped dispatch return in promise to allow for rejections without a throw. --- dist/logger.d.ts | 15 - dist/logger.js | 118 ----- dist/vuex.common.js | 1015 ------------------------------------- dist/vuex.esm.js | 999 ------------------------------------ dist/vuex.js | 1005 ------------------------------------ dist/vuex.min.js | 6 - src/store.js | 46 +- test/unit/modules.spec.js | 29 +- 8 files changed, 39 insertions(+), 3194 deletions(-) delete mode 100644 dist/logger.d.ts delete mode 100644 dist/logger.js delete mode 100644 dist/vuex.common.js delete mode 100644 dist/vuex.esm.js delete mode 100644 dist/vuex.js delete mode 100644 dist/vuex.min.js diff --git a/dist/logger.d.ts b/dist/logger.d.ts deleted file mode 100644 index ec52e727e..000000000 --- a/dist/logger.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Types for the logger plugin. - * This file must be put alongside the JavaScript file of the logger. - */ - -import { Payload, Plugin } from "../types/index"; - -export interface LoggerOption { - collapsed?: boolean; - filter?:

(mutation: P, stateBefore: S, stateAfter: S) => boolean; - transformer?: (state: S) => any; - mutationTransformer?:

(mutation: P) => any; -} - -export default function createLogger(option?: LoggerOption): Plugin; diff --git a/dist/logger.js b/dist/logger.js deleted file mode 100644 index 39a7c8888..000000000 --- a/dist/logger.js +++ /dev/null @@ -1,118 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.createVuexLogger = factory()); -}(this, function () { 'use strict'; - - /** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - function find (list, f) { - return list.filter(f)[0] - } - - /** - * Deep copy the given object considering circular structure. - * This function caches all nested objects and its copies. - * If it detects circular structure, use cached copy to avoid infinite loop. - * - * @param {*} obj - * @param {Array} cache - * @return {*} - */ - function deepCopy (obj, cache) { - if ( cache === void 0 ) cache = []; - - // just return if obj is immutable value - if (obj === null || typeof obj !== 'object') { - return obj - } - - // if obj is hit, it is in circular structure - var hit = find(cache, function (c) { return c.original === obj; }); - if (hit) { - return hit.copy - } - - var copy = Array.isArray(obj) ? [] : {}; - // put the copy into cache at first - // because we want to refer it in recursive deepCopy - cache.push({ - original: obj, - copy: copy - }); - - Object.keys(obj).forEach(function (key) { - copy[key] = deepCopy(obj[key], cache); - }); - - return copy - } - - // Credits: borrowed code from fcomb/redux-logger - - function createLogger (ref) { - if ( ref === void 0 ) ref = {}; - var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true; - var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; }; - var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; }; - var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; }; - var logger = ref.logger; if ( logger === void 0 ) logger = console; - - return function (store) { - var prevState = deepCopy(store.state); - - store.subscribe(function (mutation, state) { - if (typeof logger === 'undefined') { - return - } - var nextState = deepCopy(state); - - if (filter(mutation, prevState, nextState)) { - var time = new Date(); - var formattedTime = " @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)); - var formattedMutation = mutationTransformer(mutation); - var message = "mutation " + (mutation.type) + formattedTime; - var startMessage = collapsed - ? logger.groupCollapsed - : logger.group; - - // render - try { - startMessage.call(logger, message); - } catch (e) { - console.log(message); - } - - logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState)); - logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation); - logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState)); - - try { - logger.groupEnd(); - } catch (e) { - logger.log('—— log end ——'); - } - } - - prevState = nextState; - }); - } - } - - function repeat (str, times) { - return (new Array(times + 1)).join(str) - } - - function pad (num, maxLength) { - return repeat('0', maxLength - num.toString().length) + num - } - - return createLogger; - -})); diff --git a/dist/vuex.common.js b/dist/vuex.common.js deleted file mode 100644 index 27a577884..000000000 --- a/dist/vuex.common.js +++ /dev/null @@ -1,1015 +0,0 @@ -/** - * vuex v3.1.0 - * (c) 2019 Evan You - * @license MIT - */ -'use strict'; - -function applyMixin (Vue) { - var version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - var _init = Vue.prototype._init; - Vue.prototype._init = function (options) { - if ( options === void 0 ) options = {}; - - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - var options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -function update (path, targetModule, newModule) { - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - if (process.env.NODE_ENV !== 'production') { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -var Vue; // bind on install - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - if (process.env.NODE_ENV !== 'production') { - assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -prototypeAccessors$1.state.get = function () { - return this._vm._data.$$state -}; - -prototypeAccessors$1.state.set = function (v) { - if (process.env.NODE_ENV !== 'production') { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - process.env.NODE_ENV !== 'production' && - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - return res - }, function (e) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.catch; }) - .forEach(function (sub) { return sub.catch(action, this$1.state, e); }); - } catch (_e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in after action catch subscribers: "); - console.error(_e); - } - } - throw e - }) -}; - -Store.prototype.subscribe = function subscribe (fn) { - return genericSubscribe(fn, this._subscribers) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers) -}; - -Store.prototype.watch = function watch (getter, cb, options) { - var this$1 = this; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._vm._data.$$state = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs) { - if (subs.indexOf(fn) < 0) { - subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); -} - -function resetStoreVM (store, state, hot) { - var oldVm = store._vm; - - // bind store public getters - store.getters = {}; - var wrappedGetters = store._wrappedGetters; - var computed = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - computed[key] = function () { return fn(store); }; - Object.defineProperty(store.getters, key, { - get: function () { return store._vm[key]; }, - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - var silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed: computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(function () { return oldVm.$destroy(); }); - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - Vue.set(parentState, moduleName, module.state); - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - var gettersProxy = {}; - - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - - return gettersProxy -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload, cb) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload, cb); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, function () { - if (process.env.NODE_ENV !== 'production') { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, sync: true }); -} - -function getNestedState (state, path) { - return path.length - ? path.reduce(function (state, key) { return state[key]; }, state) - : state -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - if (process.env.NODE_ENV !== 'production') { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -function install (_Vue) { - if (Vue && _Vue === Vue) { - if (process.env.NODE_ENV !== 'production') { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * 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. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if (process.env.NODE_ENV !== 'production' && !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index = { - Store: Store, - install: install, - version: '3.1.0', - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -module.exports = index; diff --git a/dist/vuex.esm.js b/dist/vuex.esm.js deleted file mode 100644 index da94e9b59..000000000 --- a/dist/vuex.esm.js +++ /dev/null @@ -1,999 +0,0 @@ -/** - * vuex v3.1.0 - * (c) 2019 Evan You - * @license MIT - */ -function applyMixin (Vue) { - var version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - var _init = Vue.prototype._init; - Vue.prototype._init = function (options) { - if ( options === void 0 ) options = {}; - - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - var options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } -} - -var devtoolHook = - typeof window !== 'undefined' && - window.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -function update (path, targetModule, newModule) { - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - if (process.env.NODE_ENV !== 'production') { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -var Vue; // bind on install - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - if (process.env.NODE_ENV !== 'production') { - assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -prototypeAccessors$1.state.get = function () { - return this._vm._data.$$state -}; - -prototypeAccessors$1.state.set = function (v) { - if (process.env.NODE_ENV !== 'production') { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - process.env.NODE_ENV !== 'production' && - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - return res - }) -}; - -Store.prototype.subscribe = function subscribe (fn) { - return genericSubscribe(fn, this._subscribers) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers) -}; - -Store.prototype.watch = function watch (getter, cb, options) { - var this$1 = this; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._vm._data.$$state = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs) { - if (subs.indexOf(fn) < 0) { - subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); -} - -function resetStoreVM (store, state, hot) { - var oldVm = store._vm; - - // bind store public getters - store.getters = {}; - var wrappedGetters = store._wrappedGetters; - var computed = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - computed[key] = function () { return fn(store); }; - Object.defineProperty(store.getters, key, { - get: function () { return store._vm[key]; }, - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - var silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed: computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(function () { return oldVm.$destroy(); }); - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - Vue.set(parentState, moduleName, module.state); - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - var gettersProxy = {}; - - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - - return gettersProxy -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload, cb) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload, cb); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, function () { - if (process.env.NODE_ENV !== 'production') { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, sync: true }); -} - -function getNestedState (state, path) { - return path.length - ? path.reduce(function (state, key) { return state[key]; }, state) - : state -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - if (process.env.NODE_ENV !== 'production') { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -function install (_Vue) { - if (Vue && _Vue === Vue) { - if (process.env.NODE_ENV !== 'production') { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * 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. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if (process.env.NODE_ENV !== 'production' && !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index_esm = { - Store: Store, - install: install, - version: '3.1.0', - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -export default index_esm; -export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers }; diff --git a/dist/vuex.js b/dist/vuex.js deleted file mode 100644 index bae565303..000000000 --- a/dist/vuex.js +++ /dev/null @@ -1,1005 +0,0 @@ -/** - * vuex v3.1.0 - * (c) 2019 Evan You - * @license MIT - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.Vuex = factory()); -}(this, function () { 'use strict'; - - function applyMixin (Vue) { - var version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - var _init = Vue.prototype._init; - Vue.prototype._init = function (options) { - if ( options === void 0 ) options = {}; - - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - var options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } - } - - var devtoolHook = - typeof window !== 'undefined' && - window.__VUE_DEVTOOLS_GLOBAL_HOOK__; - - function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }); - } - - /** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - - /** - * forEach for object - */ - function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); - } - - function isObject (obj) { - return obj !== null && typeof obj === 'object' - } - - function isPromise (val) { - return val && typeof val.then === 'function' - } - - function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } - } - - // Base data struct for store's module, package with some attribute and method - var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; - }; - - var prototypeAccessors = { namespaced: { configurable: true } }; - - prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced - }; - - Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; - }; - - Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; - }; - - Module.prototype.getChild = function getChild (key) { - return this._children[key] - }; - - Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } - }; - - Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); - }; - - Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } - }; - - Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } - }; - - Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } - }; - - Object.defineProperties( Module.prototype, prototypeAccessors ); - - var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); - }; - - ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) - }; - - ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') - }; - - ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); - }; - - ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } - }; - - ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); - }; - - function update (path, targetModule, newModule) { - { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } - } - - var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' - }; - - var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' - }; - - var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert - }; - - function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); - } - - function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf - } - - var Vue; // bind on install - - var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - { - assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } - }; - - var prototypeAccessors$1 = { state: { configurable: true } }; - - prototypeAccessors$1.state.get = function () { - return this._vm._data.$$state - }; - - prototypeAccessors$1.state.set = function (v) { - { - assert(false, "use store.replaceState() to explicit replace store state."); - } - }; - - Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } - }; - - Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - return res - }) - }; - - Store.prototype.subscribe = function subscribe (fn) { - return genericSubscribe(fn, this._subscribers) - }; - - Store.prototype.subscribeAction = function subscribeAction (fn) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers) - }; - - Store.prototype.watch = function watch (getter, cb, options) { - var this$1 = this; - - { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) - }; - - Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._vm._data.$$state = state; - }); - }; - - Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); - }; - - Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); - }; - - Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); - }; - - Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; - }; - - Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - - function genericSubscribe (fn, subs) { - if (subs.indexOf(fn) < 0) { - subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } - } - - function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); - } - - function resetStoreVM (store, state, hot) { - var oldVm = store._vm; - - // bind store public getters - store.getters = {}; - var wrappedGetters = store._wrappedGetters; - var computed = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - computed[key] = function () { return fn(store); }; - Object.defineProperty(store.getters, key, { - get: function () { return store._vm[key]; }, - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - var silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed: computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(function () { return oldVm.$destroy(); }); - } - } - - function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - Vue.set(parentState, moduleName, module.state); - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); - } - - /** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ - function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (!store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (!store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local - } - - function makeLocalGetters (store, namespace) { - var gettersProxy = {}; - - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - - return gettersProxy - } - - function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); - } - - function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload, cb) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload, cb); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); - } - - function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; - } - - function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, function () { - { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, sync: true }); - } - - function getNestedState (state, path) { - return path.length - ? path.reduce(function (state, key) { return state[key]; }, state) - : state - } - - function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } - } - - function install (_Vue) { - if (Vue && _Vue === Vue) { - { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); - } - - /** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ - var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ - var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ - var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (!(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ - var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res - }); - - /** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ - var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) - }); }; - - /** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ - function normalizeMap (map) { - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) - } - - /** - * 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. - * @param {Function} fn - * @return {Function} - */ - function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } - } - - /** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ - function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if (!module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module - } - - var index = { - Store: Store, - install: install, - version: '3.1.0', - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers - }; - - return index; - -})); diff --git a/dist/vuex.min.js b/dist/vuex.min.js deleted file mode 100644 index 15b9039cc..000000000 --- a/dist/vuex.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/** - * vuex v3.1.0 - * (c) 2019 Evan You - * @license MIT - */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Vuex=e()}(this,function(){"use strict";var u="undefined"!=typeof window&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function a(e,n){Object.keys(e).forEach(function(t){return n(e[t],t)})}var r=function(t,e){this.runtime=e,this._children=Object.create(null);var n=(this._rawModule=t).state;this.state=("function"==typeof n?n():n)||{}},t={namespaced:{configurable:!0}};t.namespaced.get=function(){return!!this._rawModule.namespaced},r.prototype.addChild=function(t,e){this._children[t]=e},r.prototype.removeChild=function(t){delete this._children[t]},r.prototype.getChild=function(t){return this._children[t]},r.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},r.prototype.forEachChild=function(t){a(this._children,t)},r.prototype.forEachGetter=function(t){this._rawModule.getters&&a(this._rawModule.getters,t)},r.prototype.forEachAction=function(t){this._rawModule.actions&&a(this._rawModule.actions,t)},r.prototype.forEachMutation=function(t){this._rawModule.mutations&&a(this._rawModule.mutations,t)},Object.defineProperties(r.prototype,t);var m,f=function(t){this.register([],t,!1)};f.prototype.get=function(t){return t.reduce(function(t,e){return t.getChild(e)},this.root)},f.prototype.getNamespace=function(t){var n=this.root;return t.reduce(function(t,e){return t+((n=n.getChild(e)).namespaced?e+"/":"")},"")},f.prototype.update=function(t){!function t(e,n,o){n.update(o);if(o.modules)for(var i in o.modules){if(!n.getChild(i))return;t(e.concat(i),n.getChild(i),o.modules[i])}}([],this.root,t)},f.prototype.register=function(n,t,o){var i=this;void 0===o&&(o=!0);var e=new r(t,o);0===n.length?this.root=e:this.get(n.slice(0,-1)).addChild(n[n.length-1],e);t.modules&&a(t.modules,function(t,e){i.register(n.concat(e),t,o)})},f.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];e.getChild(n).runtime&&e.removeChild(n)};var e=function(t){var e=this;void 0===t&&(t={}),!m&&"undefined"!=typeof window&&window.Vue&&p(window.Vue);var n=t.plugins;void 0===n&&(n=[]);var o=t.strict;void 0===o&&(o=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new f(t),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new m;var i=this,r=this.dispatch,s=this.commit;this.dispatch=function(t,e){return r.call(i,t,e)},this.commit=function(t,e,n){return s.call(i,t,e,n)},this.strict=o;var a,c=this._modules.root.state;v(this,c,[],this._modules.root),h(this,c),n.forEach(function(t){return t(e)}),(void 0!==t.devtools?t.devtools:m.config.devtools)&&(a=this,u&&((a._devtoolHook=u).emit("vuex:init",a),u.on("vuex:travel-to-state",function(t){a.replaceState(t)}),a.subscribe(function(t,e){u.emit("vuex:mutation",t,e)})))},n={state:{configurable:!0}};function o(e,n){return n.indexOf(e)<0&&n.push(e),function(){var t=n.indexOf(e);-1 handler(payload))) : entry[0](payload) - return result.then(res => { - try { - this._actionSubscribers - .filter(sub => sub.after) - .forEach(sub => sub.after(action, this.state)) - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn(`[vuex] error in after action subscribers: `) - console.error(e) + return new Promise((resolve, reject) => { + result.then(res => { + try { + this._actionSubscribers + .filter(sub => sub.after) + .forEach(sub => sub.after(action, this.state)) + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`[vuex] error in after action subscribers: `) + console.error(e) + } } - } - return res - }, e => { - try { - this._actionSubscribers - .filter(sub => sub.catch) - .forEach(sub => sub.catch(action, this.state, e)) - } catch (_e) { - if (process.env.NODE_ENV !== 'production') { - console.warn(`[vuex] error in after action catch subscribers: `) - console.error(_e) + resolve(res) + }, e => { + try { + this._actionSubscribers + .filter(sub => sub.catch) + .forEach(sub => sub.catch(action, this.state, e)) + } catch (_e) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`[vuex] error in after action catch subscribers: `) + console.error(_e) + } } - } - throw e + reject(e) + }) }) } diff --git a/test/unit/modules.spec.js b/test/unit/modules.spec.js index 50885e06e..1387ccf7a 100644 --- a/test/unit/modules.spec.js +++ b/test/unit/modules.spec.js @@ -720,23 +720,24 @@ describe('Modules', () => { } ] }) - store.dispatch(TEST, 2) - expect(beforeSpy).toHaveBeenCalledWith( - { type: TEST, payload: 2 }, - store.state - ) - expect(afterSpy).not.toHaveBeenCalled() - Vue.nextTick(() => { - expect(afterSpy).not.toHaveBeenCalledWith( + store.dispatch(TEST, 2).catch(() => { + expect(beforeSpy).toHaveBeenCalledWith( { type: TEST, payload: 2 }, store.state ) - expect(catchSpy).toHaveBeenCalledWith( - { type: TEST, payload: 2 }, - store.state, - error - ) - done() + expect(afterSpy).not.toHaveBeenCalled() + Vue.nextTick(() => { + expect(afterSpy).not.toHaveBeenCalledWith( + { type: TEST, payload: 2 }, + store.state + ) + expect(catchSpy).toHaveBeenCalledWith( + { type: TEST, payload: 2 }, + store.state, + error + ) + done() + }) }) }) From 9b2dcce7a6ff4884a0778a9c084204ed91569bf2 Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Tue, 28 Apr 2020 10:24:13 -0400 Subject: [PATCH 3/8] Fixed missing dist folder that breaks test suite. --- dist/logger.d.ts | 15 + dist/logger.js | 118 +++++ dist/vuex.common.js | 1017 +++++++++++++++++++++++++++++++++++++++++++ dist/vuex.esm.js | 999 ++++++++++++++++++++++++++++++++++++++++++ dist/vuex.js | 1005 ++++++++++++++++++++++++++++++++++++++++++ dist/vuex.min.js | 6 + 6 files changed, 3160 insertions(+) create mode 100644 dist/logger.d.ts create mode 100644 dist/logger.js create mode 100644 dist/vuex.common.js create mode 100644 dist/vuex.esm.js create mode 100644 dist/vuex.js create mode 100644 dist/vuex.min.js diff --git a/dist/logger.d.ts b/dist/logger.d.ts new file mode 100644 index 000000000..ec52e727e --- /dev/null +++ b/dist/logger.d.ts @@ -0,0 +1,15 @@ +/** + * Types for the logger plugin. + * This file must be put alongside the JavaScript file of the logger. + */ + +import { Payload, Plugin } from "../types/index"; + +export interface LoggerOption { + collapsed?: boolean; + filter?:

(mutation: P, stateBefore: S, stateAfter: S) => boolean; + transformer?: (state: S) => any; + mutationTransformer?:

(mutation: P) => any; +} + +export default function createLogger(option?: LoggerOption): Plugin; diff --git a/dist/logger.js b/dist/logger.js new file mode 100644 index 000000000..39a7c8888 --- /dev/null +++ b/dist/logger.js @@ -0,0 +1,118 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.createVuexLogger = factory()); +}(this, function () { 'use strict'; + + /** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + function find (list, f) { + return list.filter(f)[0] + } + + /** + * Deep copy the given object considering circular structure. + * This function caches all nested objects and its copies. + * If it detects circular structure, use cached copy to avoid infinite loop. + * + * @param {*} obj + * @param {Array} cache + * @return {*} + */ + function deepCopy (obj, cache) { + if ( cache === void 0 ) cache = []; + + // just return if obj is immutable value + if (obj === null || typeof obj !== 'object') { + return obj + } + + // if obj is hit, it is in circular structure + var hit = find(cache, function (c) { return c.original === obj; }); + if (hit) { + return hit.copy + } + + var copy = Array.isArray(obj) ? [] : {}; + // put the copy into cache at first + // because we want to refer it in recursive deepCopy + cache.push({ + original: obj, + copy: copy + }); + + Object.keys(obj).forEach(function (key) { + copy[key] = deepCopy(obj[key], cache); + }); + + return copy + } + + // Credits: borrowed code from fcomb/redux-logger + + function createLogger (ref) { + if ( ref === void 0 ) ref = {}; + var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true; + var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; }; + var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; }; + var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; }; + var logger = ref.logger; if ( logger === void 0 ) logger = console; + + return function (store) { + var prevState = deepCopy(store.state); + + store.subscribe(function (mutation, state) { + if (typeof logger === 'undefined') { + return + } + var nextState = deepCopy(state); + + if (filter(mutation, prevState, nextState)) { + var time = new Date(); + var formattedTime = " @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)); + var formattedMutation = mutationTransformer(mutation); + var message = "mutation " + (mutation.type) + formattedTime; + var startMessage = collapsed + ? logger.groupCollapsed + : logger.group; + + // render + try { + startMessage.call(logger, message); + } catch (e) { + console.log(message); + } + + logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState)); + logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation); + logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState)); + + try { + logger.groupEnd(); + } catch (e) { + logger.log('—— log end ——'); + } + } + + prevState = nextState; + }); + } + } + + function repeat (str, times) { + return (new Array(times + 1)).join(str) + } + + function pad (num, maxLength) { + return repeat('0', maxLength - num.toString().length) + num + } + + return createLogger; + +})); diff --git a/dist/vuex.common.js b/dist/vuex.common.js new file mode 100644 index 000000000..0b4aca688 --- /dev/null +++ b/dist/vuex.common.js @@ -0,0 +1,1017 @@ +/** + * vuex v3.1.0 + * (c) 2020 Evan You + * @license MIT + */ +'use strict'; + +function applyMixin (Vue) { + var version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + var _init = Vue.prototype._init; + Vue.prototype._init = function (options) { + if ( options === void 0 ) options = {}; + + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + var options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } +} + +var target = typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}; +var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; + +function devtoolPlugin (store) { + if (!devtoolHook) { return } + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', function (targetState) { + store.replaceState(targetState); + }); + + store.subscribe(function (mutation, state) { + devtoolHook.emit('vuex:mutation', mutation, state); + }); +} + +/** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + +/** + * forEach for object + */ +function forEachValue (obj, fn) { + Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); +} + +function isObject (obj) { + return obj !== null && typeof obj === 'object' +} + +function isPromise (val) { + return val && typeof val.then === 'function' +} + +function assert (condition, msg) { + if (!condition) { throw new Error(("[vuex] " + msg)) } +} + +// Base data struct for store's module, package with some attribute and method +var Module = function Module (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + var rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; +}; + +var prototypeAccessors = { namespaced: { configurable: true } }; + +prototypeAccessors.namespaced.get = function () { + return !!this._rawModule.namespaced +}; + +Module.prototype.addChild = function addChild (key, module) { + this._children[key] = module; +}; + +Module.prototype.removeChild = function removeChild (key) { + delete this._children[key]; +}; + +Module.prototype.getChild = function getChild (key) { + return this._children[key] +}; + +Module.prototype.update = function update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } +}; + +Module.prototype.forEachChild = function forEachChild (fn) { + forEachValue(this._children, fn); +}; + +Module.prototype.forEachGetter = function forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } +}; + +Module.prototype.forEachAction = function forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } +}; + +Module.prototype.forEachMutation = function forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } +}; + +Object.defineProperties( Module.prototype, prototypeAccessors ); + +var ModuleCollection = function ModuleCollection (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); +}; + +ModuleCollection.prototype.get = function get (path) { + return path.reduce(function (module, key) { + return module.getChild(key) + }, this.root) +}; + +ModuleCollection.prototype.getNamespace = function getNamespace (path) { + var module = this.root; + return path.reduce(function (namespace, key) { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') +}; + +ModuleCollection.prototype.update = function update$1 (rawRootModule) { + update([], this.root, rawRootModule); +}; + +ModuleCollection.prototype.register = function register (path, rawModule, runtime) { + var this$1 = this; + if ( runtime === void 0 ) runtime = true; + + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, rawModule); + } + + var newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + var parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, function (rawChildModule, key) { + this$1.register(path.concat(key), rawChildModule, runtime); + }); + } +}; + +ModuleCollection.prototype.unregister = function unregister (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + if (!parent.getChild(key).runtime) { return } + + parent.removeChild(key); +}; + +function update (path, targetModule, newModule) { + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (var key in newModule.modules) { + if (!targetModule.getChild(key)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + "[vuex] trying to add a new module '" + key + "' on hot reloading, " + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } +} + +var functionAssert = { + assert: function (value) { return typeof value === 'function'; }, + expected: 'function' +}; + +var objectAssert = { + assert: function (value) { return typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'); }, + expected: 'function or object with "handler" function' +}; + +var assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert +}; + +function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(function (key) { + if (!rawModule[key]) { return } + + var assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], function (value, type) { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); +} + +function makeAssertionMessage (path, key, type, value, expected) { + var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; + if (path.length > 0) { + buf += " in module \"" + (path.join('.')) + "\""; + } + buf += " is " + (JSON.stringify(value)) + "."; + return buf +} + +var Vue; // bind on install + +var Store = function Store (options) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + if (process.env.NODE_ENV !== 'production') { + assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); + assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); + assert(this instanceof Store, "store must be called with the new operator."); + } + + var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; + var strict = options.strict; if ( strict === void 0 ) strict = false; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + + // bind commit and dispatch to self + var store = this; + var ref = this; + var dispatch = ref.dispatch; + var commit = ref.commit; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + var state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(function (plugin) { return plugin(this$1); }); + + var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } +}; + +var prototypeAccessors$1 = { state: { configurable: true } }; + +prototypeAccessors$1.state.get = function () { + return this._vm._data.$$state +}; + +prototypeAccessors$1.state.set = function (v) { + if (process.env.NODE_ENV !== 'production') { + assert(false, "use store.replaceState() to explicit replace store state."); + } +}; + +Store.prototype.commit = function commit (_type, _payload, _options) { + var this$1 = this; + + // check object-style commit + var ref = unifyObjectStyle(_type, _payload, _options); + var type = ref.type; + var payload = ref.payload; + var options = ref.options; + + var mutation = { type: type, payload: payload }; + var entry = this._mutations[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown mutation type: " + type)); + } + return + } + this._withCommit(function () { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); }); + + if ( + process.env.NODE_ENV !== 'production' && + options && options.silent + ) { + console.warn( + "[vuex] mutation type: " + type + ". Silent option has been removed. " + + 'Use the filter functionality in the vue-devtools' + ); + } +}; + +Store.prototype.dispatch = function dispatch (_type, _payload) { + var this$1 = this; + + // check object-style dispatch + var ref = unifyObjectStyle(_type, _payload); + var type = ref.type; + var payload = ref.payload; + + var action = { type: type, payload: payload }; + var entry = this._actions[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown action type: " + type)); + } + return + } + + try { + this._actionSubscribers + .filter(function (sub) { return sub.before; }) + .forEach(function (sub) { return sub.before(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in before action subscribers: "); + console.error(e); + } + } + + var result = entry.length > 1 + ? Promise.all(entry.map(function (handler) { return handler(payload); })) + : entry[0](payload); + + return new Promise(function (resolve, reject) { + result.then(function (res) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.after; }) + .forEach(function (sub) { return sub.after(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in after action subscribers: "); + console.error(e); + } + } + resolve(res); + }, function (e) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.catch; }) + .forEach(function (sub) { return sub.catch(action, this$1.state, e); }); + } catch (_e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in after action catch subscribers: "); + console.error(_e); + } + } + reject(e); + }); + }) +}; + +Store.prototype.subscribe = function subscribe (fn) { + return genericSubscribe(fn, this._subscribers) +}; + +Store.prototype.subscribeAction = function subscribeAction (fn) { + var subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers) +}; + +Store.prototype.watch = function watch (getter, cb, options) { + var this$1 = this; + + if (process.env.NODE_ENV !== 'production') { + assert(typeof getter === 'function', "store.watch only accepts a function."); + } + return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) +}; + +Store.prototype.replaceState = function replaceState (state) { + var this$1 = this; + + this._withCommit(function () { + this$1._vm._data.$$state = state; + }); +}; + +Store.prototype.registerModule = function registerModule (path, rawModule, options) { + if ( options === void 0 ) options = {}; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); +}; + +Store.prototype.unregisterModule = function unregisterModule (path) { + var this$1 = this; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + this._modules.unregister(path); + this._withCommit(function () { + var parentState = getNestedState(this$1.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); +}; + +Store.prototype.hotUpdate = function hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); +}; + +Store.prototype._withCommit = function _withCommit (fn) { + var committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; +}; + +Object.defineProperties( Store.prototype, prototypeAccessors$1 ); + +function genericSubscribe (fn, subs) { + if (subs.indexOf(fn) < 0) { + subs.push(fn); + } + return function () { + var i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } +} + +function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + var state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); +} + +function resetStoreVM (store, state, hot) { + var oldVm = store._vm; + + // bind store public getters + store.getters = {}; + var wrappedGetters = store._wrappedGetters; + var computed = {}; + forEachValue(wrappedGetters, function (fn, key) { + // use computed to leverage its lazy-caching mechanism + computed[key] = function () { return fn(store); }; + Object.defineProperty(store.getters, key, { + get: function () { return store._vm[key]; }, + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + var silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed: computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(function () { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(function () { return oldVm.$destroy(); }); + } +} + +function installModule (store, rootState, path, module, hot) { + var isRoot = !path.length; + var namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + var parentState = getNestedState(rootState, path.slice(0, -1)); + var moduleName = path[path.length - 1]; + store._withCommit(function () { + Vue.set(parentState, moduleName, module.state); + }); + } + + var local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation(function (mutation, key) { + var namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction(function (action, key) { + var type = action.root ? key : namespace + key; + var handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter(function (getter, key) { + var namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild(function (child, key) { + installModule(store, rootState, path.concat(key), child, hot); + }); +} + +/** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ +function makeLocalContext (store, namespace, path) { + var noNamespace = namespace === ''; + + var local = { + dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { + console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { + console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? function () { return store.getters; } + : function () { return makeLocalGetters(store, namespace); } + }, + state: { + get: function () { return getNestedState(store.state, path); } + } + }); + + return local +} + +function makeLocalGetters (store, namespace) { + var gettersProxy = {}; + + var splitPos = namespace.length; + Object.keys(store.getters).forEach(function (type) { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) { return } + + // extract local getter type + var localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: function () { return store.getters[type]; }, + enumerable: true + }); + }); + + return gettersProxy +} + +function registerMutation (store, type, handler, local) { + var entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); +} + +function registerAction (store, type, handler, local) { + var entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload, cb) { + var res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload, cb); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(function (err) { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); +} + +function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] duplicate getter key: " + type)); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; +} + +function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, function () { + if (process.env.NODE_ENV !== 'production') { + assert(store._committing, "do not mutate vuex store state outside mutation handlers."); + } + }, { deep: true, sync: true }); +} + +function getNestedState (state, path) { + return path.length + ? path.reduce(function (state, key) { return state[key]; }, state) + : state +} + +function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + if (process.env.NODE_ENV !== 'production') { + assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); + } + + return { type: type, payload: payload, options: options } +} + +function install (_Vue) { + if (Vue && _Vue === Vue) { + if (process.env.NODE_ENV !== 'production') { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); +} + +/** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ +var mapState = normalizeNamespace(function (namespace, states) { + var res = {}; + normalizeMap(states).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedState () { + var state = this.$store.state; + var getters = this.$store.getters; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapMutations = normalizeNamespace(function (namespace, mutations) { + var res = {}; + normalizeMap(mutations).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedMutation () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // Get the commit method from store + var commit = this.$store.commit; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ +var mapGetters = normalizeNamespace(function (namespace, getters) { + var res = {}; + normalizeMap(getters).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { + console.error(("[vuex] unknown getter: " + val)); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapActions = normalizeNamespace(function (namespace, actions) { + var res = {}; + normalizeMap(actions).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // get dispatch function from store + var dispatch = this.$store.dispatch; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ +var createNamespacedHelpers = function (namespace) { return ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) +}); }; + +/** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ +function normalizeMap (map) { + return Array.isArray(map) + ? map.map(function (key) { return ({ key: key, val: key }); }) + : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) +} + +/** + * 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. + * @param {Function} fn + * @return {Function} + */ +function normalizeNamespace (fn) { + return function (namespace, map) { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } +} + +/** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ +function getModuleByNamespace (store, helper, namespace) { + var module = store._modulesNamespaceMap[namespace]; + if (process.env.NODE_ENV !== 'production' && !module) { + console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); + } + return module +} + +var index = { + Store: Store, + install: install, + version: '3.1.0', + mapState: mapState, + mapMutations: mapMutations, + mapGetters: mapGetters, + mapActions: mapActions, + createNamespacedHelpers: createNamespacedHelpers +}; + +module.exports = index; diff --git a/dist/vuex.esm.js b/dist/vuex.esm.js new file mode 100644 index 000000000..da94e9b59 --- /dev/null +++ b/dist/vuex.esm.js @@ -0,0 +1,999 @@ +/** + * vuex v3.1.0 + * (c) 2019 Evan You + * @license MIT + */ +function applyMixin (Vue) { + var version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + var _init = Vue.prototype._init; + Vue.prototype._init = function (options) { + if ( options === void 0 ) options = {}; + + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + var options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } +} + +var devtoolHook = + typeof window !== 'undefined' && + window.__VUE_DEVTOOLS_GLOBAL_HOOK__; + +function devtoolPlugin (store) { + if (!devtoolHook) { return } + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', function (targetState) { + store.replaceState(targetState); + }); + + store.subscribe(function (mutation, state) { + devtoolHook.emit('vuex:mutation', mutation, state); + }); +} + +/** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + +/** + * forEach for object + */ +function forEachValue (obj, fn) { + Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); +} + +function isObject (obj) { + return obj !== null && typeof obj === 'object' +} + +function isPromise (val) { + return val && typeof val.then === 'function' +} + +function assert (condition, msg) { + if (!condition) { throw new Error(("[vuex] " + msg)) } +} + +// Base data struct for store's module, package with some attribute and method +var Module = function Module (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + var rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; +}; + +var prototypeAccessors = { namespaced: { configurable: true } }; + +prototypeAccessors.namespaced.get = function () { + return !!this._rawModule.namespaced +}; + +Module.prototype.addChild = function addChild (key, module) { + this._children[key] = module; +}; + +Module.prototype.removeChild = function removeChild (key) { + delete this._children[key]; +}; + +Module.prototype.getChild = function getChild (key) { + return this._children[key] +}; + +Module.prototype.update = function update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } +}; + +Module.prototype.forEachChild = function forEachChild (fn) { + forEachValue(this._children, fn); +}; + +Module.prototype.forEachGetter = function forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } +}; + +Module.prototype.forEachAction = function forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } +}; + +Module.prototype.forEachMutation = function forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } +}; + +Object.defineProperties( Module.prototype, prototypeAccessors ); + +var ModuleCollection = function ModuleCollection (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); +}; + +ModuleCollection.prototype.get = function get (path) { + return path.reduce(function (module, key) { + return module.getChild(key) + }, this.root) +}; + +ModuleCollection.prototype.getNamespace = function getNamespace (path) { + var module = this.root; + return path.reduce(function (namespace, key) { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') +}; + +ModuleCollection.prototype.update = function update$1 (rawRootModule) { + update([], this.root, rawRootModule); +}; + +ModuleCollection.prototype.register = function register (path, rawModule, runtime) { + var this$1 = this; + if ( runtime === void 0 ) runtime = true; + + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, rawModule); + } + + var newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + var parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, function (rawChildModule, key) { + this$1.register(path.concat(key), rawChildModule, runtime); + }); + } +}; + +ModuleCollection.prototype.unregister = function unregister (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + if (!parent.getChild(key).runtime) { return } + + parent.removeChild(key); +}; + +function update (path, targetModule, newModule) { + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (var key in newModule.modules) { + if (!targetModule.getChild(key)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + "[vuex] trying to add a new module '" + key + "' on hot reloading, " + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } +} + +var functionAssert = { + assert: function (value) { return typeof value === 'function'; }, + expected: 'function' +}; + +var objectAssert = { + assert: function (value) { return typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'); }, + expected: 'function or object with "handler" function' +}; + +var assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert +}; + +function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(function (key) { + if (!rawModule[key]) { return } + + var assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], function (value, type) { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); +} + +function makeAssertionMessage (path, key, type, value, expected) { + var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; + if (path.length > 0) { + buf += " in module \"" + (path.join('.')) + "\""; + } + buf += " is " + (JSON.stringify(value)) + "."; + return buf +} + +var Vue; // bind on install + +var Store = function Store (options) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + if (process.env.NODE_ENV !== 'production') { + assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); + assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); + assert(this instanceof Store, "store must be called with the new operator."); + } + + var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; + var strict = options.strict; if ( strict === void 0 ) strict = false; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + + // bind commit and dispatch to self + var store = this; + var ref = this; + var dispatch = ref.dispatch; + var commit = ref.commit; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + var state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(function (plugin) { return plugin(this$1); }); + + var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } +}; + +var prototypeAccessors$1 = { state: { configurable: true } }; + +prototypeAccessors$1.state.get = function () { + return this._vm._data.$$state +}; + +prototypeAccessors$1.state.set = function (v) { + if (process.env.NODE_ENV !== 'production') { + assert(false, "use store.replaceState() to explicit replace store state."); + } +}; + +Store.prototype.commit = function commit (_type, _payload, _options) { + var this$1 = this; + + // check object-style commit + var ref = unifyObjectStyle(_type, _payload, _options); + var type = ref.type; + var payload = ref.payload; + var options = ref.options; + + var mutation = { type: type, payload: payload }; + var entry = this._mutations[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown mutation type: " + type)); + } + return + } + this._withCommit(function () { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); }); + + if ( + process.env.NODE_ENV !== 'production' && + options && options.silent + ) { + console.warn( + "[vuex] mutation type: " + type + ". Silent option has been removed. " + + 'Use the filter functionality in the vue-devtools' + ); + } +}; + +Store.prototype.dispatch = function dispatch (_type, _payload) { + var this$1 = this; + + // check object-style dispatch + var ref = unifyObjectStyle(_type, _payload); + var type = ref.type; + var payload = ref.payload; + + var action = { type: type, payload: payload }; + var entry = this._actions[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown action type: " + type)); + } + return + } + + try { + this._actionSubscribers + .filter(function (sub) { return sub.before; }) + .forEach(function (sub) { return sub.before(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in before action subscribers: "); + console.error(e); + } + } + + var result = entry.length > 1 + ? Promise.all(entry.map(function (handler) { return handler(payload); })) + : entry[0](payload); + + return result.then(function (res) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.after; }) + .forEach(function (sub) { return sub.after(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in after action subscribers: "); + console.error(e); + } + } + return res + }) +}; + +Store.prototype.subscribe = function subscribe (fn) { + return genericSubscribe(fn, this._subscribers) +}; + +Store.prototype.subscribeAction = function subscribeAction (fn) { + var subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers) +}; + +Store.prototype.watch = function watch (getter, cb, options) { + var this$1 = this; + + if (process.env.NODE_ENV !== 'production') { + assert(typeof getter === 'function', "store.watch only accepts a function."); + } + return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) +}; + +Store.prototype.replaceState = function replaceState (state) { + var this$1 = this; + + this._withCommit(function () { + this$1._vm._data.$$state = state; + }); +}; + +Store.prototype.registerModule = function registerModule (path, rawModule, options) { + if ( options === void 0 ) options = {}; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); +}; + +Store.prototype.unregisterModule = function unregisterModule (path) { + var this$1 = this; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + this._modules.unregister(path); + this._withCommit(function () { + var parentState = getNestedState(this$1.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); +}; + +Store.prototype.hotUpdate = function hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); +}; + +Store.prototype._withCommit = function _withCommit (fn) { + var committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; +}; + +Object.defineProperties( Store.prototype, prototypeAccessors$1 ); + +function genericSubscribe (fn, subs) { + if (subs.indexOf(fn) < 0) { + subs.push(fn); + } + return function () { + var i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } +} + +function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + var state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); +} + +function resetStoreVM (store, state, hot) { + var oldVm = store._vm; + + // bind store public getters + store.getters = {}; + var wrappedGetters = store._wrappedGetters; + var computed = {}; + forEachValue(wrappedGetters, function (fn, key) { + // use computed to leverage its lazy-caching mechanism + computed[key] = function () { return fn(store); }; + Object.defineProperty(store.getters, key, { + get: function () { return store._vm[key]; }, + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + var silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed: computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(function () { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(function () { return oldVm.$destroy(); }); + } +} + +function installModule (store, rootState, path, module, hot) { + var isRoot = !path.length; + var namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + var parentState = getNestedState(rootState, path.slice(0, -1)); + var moduleName = path[path.length - 1]; + store._withCommit(function () { + Vue.set(parentState, moduleName, module.state); + }); + } + + var local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation(function (mutation, key) { + var namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction(function (action, key) { + var type = action.root ? key : namespace + key; + var handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter(function (getter, key) { + var namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild(function (child, key) { + installModule(store, rootState, path.concat(key), child, hot); + }); +} + +/** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ +function makeLocalContext (store, namespace, path) { + var noNamespace = namespace === ''; + + var local = { + dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { + console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { + console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? function () { return store.getters; } + : function () { return makeLocalGetters(store, namespace); } + }, + state: { + get: function () { return getNestedState(store.state, path); } + } + }); + + return local +} + +function makeLocalGetters (store, namespace) { + var gettersProxy = {}; + + var splitPos = namespace.length; + Object.keys(store.getters).forEach(function (type) { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) { return } + + // extract local getter type + var localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: function () { return store.getters[type]; }, + enumerable: true + }); + }); + + return gettersProxy +} + +function registerMutation (store, type, handler, local) { + var entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); +} + +function registerAction (store, type, handler, local) { + var entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload, cb) { + var res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload, cb); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(function (err) { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); +} + +function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] duplicate getter key: " + type)); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; +} + +function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, function () { + if (process.env.NODE_ENV !== 'production') { + assert(store._committing, "do not mutate vuex store state outside mutation handlers."); + } + }, { deep: true, sync: true }); +} + +function getNestedState (state, path) { + return path.length + ? path.reduce(function (state, key) { return state[key]; }, state) + : state +} + +function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + if (process.env.NODE_ENV !== 'production') { + assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); + } + + return { type: type, payload: payload, options: options } +} + +function install (_Vue) { + if (Vue && _Vue === Vue) { + if (process.env.NODE_ENV !== 'production') { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); +} + +/** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ +var mapState = normalizeNamespace(function (namespace, states) { + var res = {}; + normalizeMap(states).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedState () { + var state = this.$store.state; + var getters = this.$store.getters; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapMutations = normalizeNamespace(function (namespace, mutations) { + var res = {}; + normalizeMap(mutations).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedMutation () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // Get the commit method from store + var commit = this.$store.commit; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ +var mapGetters = normalizeNamespace(function (namespace, getters) { + var res = {}; + normalizeMap(getters).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { + console.error(("[vuex] unknown getter: " + val)); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapActions = normalizeNamespace(function (namespace, actions) { + var res = {}; + normalizeMap(actions).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // get dispatch function from store + var dispatch = this.$store.dispatch; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ +var createNamespacedHelpers = function (namespace) { return ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) +}); }; + +/** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ +function normalizeMap (map) { + return Array.isArray(map) + ? map.map(function (key) { return ({ key: key, val: key }); }) + : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) +} + +/** + * 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. + * @param {Function} fn + * @return {Function} + */ +function normalizeNamespace (fn) { + return function (namespace, map) { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } +} + +/** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ +function getModuleByNamespace (store, helper, namespace) { + var module = store._modulesNamespaceMap[namespace]; + if (process.env.NODE_ENV !== 'production' && !module) { + console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); + } + return module +} + +var index_esm = { + Store: Store, + install: install, + version: '3.1.0', + mapState: mapState, + mapMutations: mapMutations, + mapGetters: mapGetters, + mapActions: mapActions, + createNamespacedHelpers: createNamespacedHelpers +}; + +export default index_esm; +export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers }; diff --git a/dist/vuex.js b/dist/vuex.js new file mode 100644 index 000000000..bae565303 --- /dev/null +++ b/dist/vuex.js @@ -0,0 +1,1005 @@ +/** + * vuex v3.1.0 + * (c) 2019 Evan You + * @license MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.Vuex = factory()); +}(this, function () { 'use strict'; + + function applyMixin (Vue) { + var version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + var _init = Vue.prototype._init; + Vue.prototype._init = function (options) { + if ( options === void 0 ) options = {}; + + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + var options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } + } + + var devtoolHook = + typeof window !== 'undefined' && + window.__VUE_DEVTOOLS_GLOBAL_HOOK__; + + function devtoolPlugin (store) { + if (!devtoolHook) { return } + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', function (targetState) { + store.replaceState(targetState); + }); + + store.subscribe(function (mutation, state) { + devtoolHook.emit('vuex:mutation', mutation, state); + }); + } + + /** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + + /** + * forEach for object + */ + function forEachValue (obj, fn) { + Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); + } + + function isObject (obj) { + return obj !== null && typeof obj === 'object' + } + + function isPromise (val) { + return val && typeof val.then === 'function' + } + + function assert (condition, msg) { + if (!condition) { throw new Error(("[vuex] " + msg)) } + } + + // Base data struct for store's module, package with some attribute and method + var Module = function Module (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + var rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; + }; + + var prototypeAccessors = { namespaced: { configurable: true } }; + + prototypeAccessors.namespaced.get = function () { + return !!this._rawModule.namespaced + }; + + Module.prototype.addChild = function addChild (key, module) { + this._children[key] = module; + }; + + Module.prototype.removeChild = function removeChild (key) { + delete this._children[key]; + }; + + Module.prototype.getChild = function getChild (key) { + return this._children[key] + }; + + Module.prototype.update = function update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } + }; + + Module.prototype.forEachChild = function forEachChild (fn) { + forEachValue(this._children, fn); + }; + + Module.prototype.forEachGetter = function forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } + }; + + Module.prototype.forEachAction = function forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } + }; + + Module.prototype.forEachMutation = function forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } + }; + + Object.defineProperties( Module.prototype, prototypeAccessors ); + + var ModuleCollection = function ModuleCollection (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); + }; + + ModuleCollection.prototype.get = function get (path) { + return path.reduce(function (module, key) { + return module.getChild(key) + }, this.root) + }; + + ModuleCollection.prototype.getNamespace = function getNamespace (path) { + var module = this.root; + return path.reduce(function (namespace, key) { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') + }; + + ModuleCollection.prototype.update = function update$1 (rawRootModule) { + update([], this.root, rawRootModule); + }; + + ModuleCollection.prototype.register = function register (path, rawModule, runtime) { + var this$1 = this; + if ( runtime === void 0 ) runtime = true; + + { + assertRawModule(path, rawModule); + } + + var newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + var parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, function (rawChildModule, key) { + this$1.register(path.concat(key), rawChildModule, runtime); + }); + } + }; + + ModuleCollection.prototype.unregister = function unregister (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + if (!parent.getChild(key).runtime) { return } + + parent.removeChild(key); + }; + + function update (path, targetModule, newModule) { + { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (var key in newModule.modules) { + if (!targetModule.getChild(key)) { + { + console.warn( + "[vuex] trying to add a new module '" + key + "' on hot reloading, " + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } + } + + var functionAssert = { + assert: function (value) { return typeof value === 'function'; }, + expected: 'function' + }; + + var objectAssert = { + assert: function (value) { return typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'); }, + expected: 'function or object with "handler" function' + }; + + var assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert + }; + + function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(function (key) { + if (!rawModule[key]) { return } + + var assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], function (value, type) { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); + } + + function makeAssertionMessage (path, key, type, value, expected) { + var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; + if (path.length > 0) { + buf += " in module \"" + (path.join('.')) + "\""; + } + buf += " is " + (JSON.stringify(value)) + "."; + return buf + } + + var Vue; // bind on install + + var Store = function Store (options) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + { + assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); + assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); + assert(this instanceof Store, "store must be called with the new operator."); + } + + var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; + var strict = options.strict; if ( strict === void 0 ) strict = false; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + + // bind commit and dispatch to self + var store = this; + var ref = this; + var dispatch = ref.dispatch; + var commit = ref.commit; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + var state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(function (plugin) { return plugin(this$1); }); + + var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } + }; + + var prototypeAccessors$1 = { state: { configurable: true } }; + + prototypeAccessors$1.state.get = function () { + return this._vm._data.$$state + }; + + prototypeAccessors$1.state.set = function (v) { + { + assert(false, "use store.replaceState() to explicit replace store state."); + } + }; + + Store.prototype.commit = function commit (_type, _payload, _options) { + var this$1 = this; + + // check object-style commit + var ref = unifyObjectStyle(_type, _payload, _options); + var type = ref.type; + var payload = ref.payload; + var options = ref.options; + + var mutation = { type: type, payload: payload }; + var entry = this._mutations[type]; + if (!entry) { + { + console.error(("[vuex] unknown mutation type: " + type)); + } + return + } + this._withCommit(function () { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); }); + + if ( + options && options.silent + ) { + console.warn( + "[vuex] mutation type: " + type + ". Silent option has been removed. " + + 'Use the filter functionality in the vue-devtools' + ); + } + }; + + Store.prototype.dispatch = function dispatch (_type, _payload) { + var this$1 = this; + + // check object-style dispatch + var ref = unifyObjectStyle(_type, _payload); + var type = ref.type; + var payload = ref.payload; + + var action = { type: type, payload: payload }; + var entry = this._actions[type]; + if (!entry) { + { + console.error(("[vuex] unknown action type: " + type)); + } + return + } + + try { + this._actionSubscribers + .filter(function (sub) { return sub.before; }) + .forEach(function (sub) { return sub.before(action, this$1.state); }); + } catch (e) { + { + console.warn("[vuex] error in before action subscribers: "); + console.error(e); + } + } + + var result = entry.length > 1 + ? Promise.all(entry.map(function (handler) { return handler(payload); })) + : entry[0](payload); + + return result.then(function (res) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.after; }) + .forEach(function (sub) { return sub.after(action, this$1.state); }); + } catch (e) { + { + console.warn("[vuex] error in after action subscribers: "); + console.error(e); + } + } + return res + }) + }; + + Store.prototype.subscribe = function subscribe (fn) { + return genericSubscribe(fn, this._subscribers) + }; + + Store.prototype.subscribeAction = function subscribeAction (fn) { + var subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers) + }; + + Store.prototype.watch = function watch (getter, cb, options) { + var this$1 = this; + + { + assert(typeof getter === 'function', "store.watch only accepts a function."); + } + return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) + }; + + Store.prototype.replaceState = function replaceState (state) { + var this$1 = this; + + this._withCommit(function () { + this$1._vm._data.$$state = state; + }); + }; + + Store.prototype.registerModule = function registerModule (path, rawModule, options) { + if ( options === void 0 ) options = {}; + + if (typeof path === 'string') { path = [path]; } + + { + assert(Array.isArray(path), "module path must be a string or an Array."); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); + }; + + Store.prototype.unregisterModule = function unregisterModule (path) { + var this$1 = this; + + if (typeof path === 'string') { path = [path]; } + + { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + this._modules.unregister(path); + this._withCommit(function () { + var parentState = getNestedState(this$1.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); + }; + + Store.prototype.hotUpdate = function hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); + }; + + Store.prototype._withCommit = function _withCommit (fn) { + var committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; + }; + + Object.defineProperties( Store.prototype, prototypeAccessors$1 ); + + function genericSubscribe (fn, subs) { + if (subs.indexOf(fn) < 0) { + subs.push(fn); + } + return function () { + var i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } + } + + function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + var state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); + } + + function resetStoreVM (store, state, hot) { + var oldVm = store._vm; + + // bind store public getters + store.getters = {}; + var wrappedGetters = store._wrappedGetters; + var computed = {}; + forEachValue(wrappedGetters, function (fn, key) { + // use computed to leverage its lazy-caching mechanism + computed[key] = function () { return fn(store); }; + Object.defineProperty(store.getters, key, { + get: function () { return store._vm[key]; }, + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + var silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed: computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(function () { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(function () { return oldVm.$destroy(); }); + } + } + + function installModule (store, rootState, path, module, hot) { + var isRoot = !path.length; + var namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + var parentState = getNestedState(rootState, path.slice(0, -1)); + var moduleName = path[path.length - 1]; + store._withCommit(function () { + Vue.set(parentState, moduleName, module.state); + }); + } + + var local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation(function (mutation, key) { + var namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction(function (action, key) { + var type = action.root ? key : namespace + key; + var handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter(function (getter, key) { + var namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild(function (child, key) { + installModule(store, rootState, path.concat(key), child, hot); + }); + } + + /** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ + function makeLocalContext (store, namespace, path) { + var noNamespace = namespace === ''; + + var local = { + dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (!store._actions[type]) { + console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (!store._mutations[type]) { + console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? function () { return store.getters; } + : function () { return makeLocalGetters(store, namespace); } + }, + state: { + get: function () { return getNestedState(store.state, path); } + } + }); + + return local + } + + function makeLocalGetters (store, namespace) { + var gettersProxy = {}; + + var splitPos = namespace.length; + Object.keys(store.getters).forEach(function (type) { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) { return } + + // extract local getter type + var localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: function () { return store.getters[type]; }, + enumerable: true + }); + }); + + return gettersProxy + } + + function registerMutation (store, type, handler, local) { + var entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); + } + + function registerAction (store, type, handler, local) { + var entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload, cb) { + var res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload, cb); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(function (err) { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); + } + + function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + { + console.error(("[vuex] duplicate getter key: " + type)); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; + } + + function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, function () { + { + assert(store._committing, "do not mutate vuex store state outside mutation handlers."); + } + }, { deep: true, sync: true }); + } + + function getNestedState (state, path) { + return path.length + ? path.reduce(function (state, key) { return state[key]; }, state) + : state + } + + function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + { + assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); + } + + return { type: type, payload: payload, options: options } + } + + function install (_Vue) { + if (Vue && _Vue === Vue) { + { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); + } + + /** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ + var mapState = normalizeNamespace(function (namespace, states) { + var res = {}; + normalizeMap(states).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedState () { + var state = this.$store.state; + var getters = this.$store.getters; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res + }); + + /** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ + var mapMutations = normalizeNamespace(function (namespace, mutations) { + var res = {}; + normalizeMap(mutations).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedMutation () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // Get the commit method from store + var commit = this.$store.commit; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res + }); + + /** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ + var mapGetters = normalizeNamespace(function (namespace, getters) { + var res = {}; + normalizeMap(getters).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (!(val in this.$store.getters)) { + console.error(("[vuex] unknown getter: " + val)); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res + }); + + /** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ + var mapActions = normalizeNamespace(function (namespace, actions) { + var res = {}; + normalizeMap(actions).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // get dispatch function from store + var dispatch = this.$store.dispatch; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res + }); + + /** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ + var createNamespacedHelpers = function (namespace) { return ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) + }); }; + + /** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ + function normalizeMap (map) { + return Array.isArray(map) + ? map.map(function (key) { return ({ key: key, val: key }); }) + : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) + } + + /** + * 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. + * @param {Function} fn + * @return {Function} + */ + function normalizeNamespace (fn) { + return function (namespace, map) { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } + } + + /** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ + function getModuleByNamespace (store, helper, namespace) { + var module = store._modulesNamespaceMap[namespace]; + if (!module) { + console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); + } + return module + } + + var index = { + Store: Store, + install: install, + version: '3.1.0', + mapState: mapState, + mapMutations: mapMutations, + mapGetters: mapGetters, + mapActions: mapActions, + createNamespacedHelpers: createNamespacedHelpers + }; + + return index; + +})); diff --git a/dist/vuex.min.js b/dist/vuex.min.js new file mode 100644 index 000000000..15b9039cc --- /dev/null +++ b/dist/vuex.min.js @@ -0,0 +1,6 @@ +/** + * vuex v3.1.0 + * (c) 2019 Evan You + * @license MIT + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Vuex=e()}(this,function(){"use strict";var u="undefined"!=typeof window&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function a(e,n){Object.keys(e).forEach(function(t){return n(e[t],t)})}var r=function(t,e){this.runtime=e,this._children=Object.create(null);var n=(this._rawModule=t).state;this.state=("function"==typeof n?n():n)||{}},t={namespaced:{configurable:!0}};t.namespaced.get=function(){return!!this._rawModule.namespaced},r.prototype.addChild=function(t,e){this._children[t]=e},r.prototype.removeChild=function(t){delete this._children[t]},r.prototype.getChild=function(t){return this._children[t]},r.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},r.prototype.forEachChild=function(t){a(this._children,t)},r.prototype.forEachGetter=function(t){this._rawModule.getters&&a(this._rawModule.getters,t)},r.prototype.forEachAction=function(t){this._rawModule.actions&&a(this._rawModule.actions,t)},r.prototype.forEachMutation=function(t){this._rawModule.mutations&&a(this._rawModule.mutations,t)},Object.defineProperties(r.prototype,t);var m,f=function(t){this.register([],t,!1)};f.prototype.get=function(t){return t.reduce(function(t,e){return t.getChild(e)},this.root)},f.prototype.getNamespace=function(t){var n=this.root;return t.reduce(function(t,e){return t+((n=n.getChild(e)).namespaced?e+"/":"")},"")},f.prototype.update=function(t){!function t(e,n,o){n.update(o);if(o.modules)for(var i in o.modules){if(!n.getChild(i))return;t(e.concat(i),n.getChild(i),o.modules[i])}}([],this.root,t)},f.prototype.register=function(n,t,o){var i=this;void 0===o&&(o=!0);var e=new r(t,o);0===n.length?this.root=e:this.get(n.slice(0,-1)).addChild(n[n.length-1],e);t.modules&&a(t.modules,function(t,e){i.register(n.concat(e),t,o)})},f.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];e.getChild(n).runtime&&e.removeChild(n)};var e=function(t){var e=this;void 0===t&&(t={}),!m&&"undefined"!=typeof window&&window.Vue&&p(window.Vue);var n=t.plugins;void 0===n&&(n=[]);var o=t.strict;void 0===o&&(o=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new f(t),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new m;var i=this,r=this.dispatch,s=this.commit;this.dispatch=function(t,e){return r.call(i,t,e)},this.commit=function(t,e,n){return s.call(i,t,e,n)},this.strict=o;var a,c=this._modules.root.state;v(this,c,[],this._modules.root),h(this,c),n.forEach(function(t){return t(e)}),(void 0!==t.devtools?t.devtools:m.config.devtools)&&(a=this,u&&((a._devtoolHook=u).emit("vuex:init",a),u.on("vuex:travel-to-state",function(t){a.replaceState(t)}),a.subscribe(function(t,e){u.emit("vuex:mutation",t,e)})))},n={state:{configurable:!0}};function o(e,n){return n.indexOf(e)<0&&n.push(e),function(){var t=n.indexOf(e);-1 Date: Thu, 30 Apr 2020 16:25:35 -0400 Subject: [PATCH 4/8] Updated ActionSubscriberObject.catch to ActionSubscriberObject.error --- src/store.js | 4 ++-- test/unit/modules.spec.js | 8 ++++---- types/index.d.ts | 4 ++-- types/test/index.ts | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/store.js b/src/store.js index 0c682696c..2f5b6ab01 100644 --- a/src/store.js +++ b/src/store.js @@ -165,8 +165,8 @@ export class Store { }, e => { try { this._actionSubscribers - .filter(sub => sub.catch) - .forEach(sub => sub.catch(action, this.state, e)) + .filter(sub => sub.error) + .forEach(sub => sub.error(action, this.state, e)) } catch (_e) { if (process.env.NODE_ENV !== 'production') { console.warn(`[vuex] error in after action catch subscribers: `) diff --git a/test/unit/modules.spec.js b/test/unit/modules.spec.js index 4dd10db57..30c088683 100644 --- a/test/unit/modules.spec.js +++ b/test/unit/modules.spec.js @@ -733,10 +733,10 @@ describe('Modules', () => { }) }) - it('action catch subscribers', (done) => { + it('action error subscribers', (done) => { const beforeSpy = jasmine.createSpy() const afterSpy = jasmine.createSpy() - const catchSpy = jasmine.createSpy() + const errorSpy = jasmine.createSpy() const error = new Error() const store = new Vuex.Store({ actions: { @@ -747,7 +747,7 @@ describe('Modules', () => { store.subscribeAction({ before: beforeSpy, after: afterSpy, - catch: catchSpy + error: errorSpy }) } ] @@ -763,7 +763,7 @@ describe('Modules', () => { { type: TEST, payload: 2 }, store.state ) - expect(catchSpy).toHaveBeenCalledWith( + expect(errorSpy).toHaveBeenCalledWith( { type: TEST, payload: 2 }, store.state, error diff --git a/types/index.d.ts b/types/index.d.ts index 75887137a..46b928af7 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -77,12 +77,12 @@ export interface SubscribeOptions { } export type ActionSubscriber = (action: P, state: S) => any; -export type ActionCatchSubscriber = (action: P, state: S, error: Error) => any; +export type ActionErrorSubscriber = (action: P, state: S, error: Error) => any; export interface ActionSubscribersObject { before?: ActionSubscriber; after?: ActionSubscriber; - catch?: ActionCatchSubscriber; + error?: ActionErrorSubscriber; } export type SubscribeActionOptions = ActionSubscriber | ActionSubscribersObject; diff --git a/types/test/index.ts b/types/test/index.ts index 4ee767c93..92e138cb9 100644 --- a/types/test/index.ts +++ b/types/test/index.ts @@ -74,7 +74,7 @@ namespace StoreInstance { action.payload; state.value; }, - catch(action, state, error) { + error(action, state, error) { action.type; action.payload; state.value; @@ -93,7 +93,7 @@ namespace StoreInstance { action.payload; state.value; }, - catch(action, state, error) { + error(action, state, error) { action.type; action.payload; state.value; @@ -115,7 +115,7 @@ namespace StoreInstance { action.payload; state.value; }, - catch(action, state, error) { + error(action, state, error) { action.type; action.payload; state.value; @@ -124,7 +124,7 @@ namespace StoreInstance { }); store.subscribeAction({ - catch(action, state, error) { + error(action, state, error) { action.type; action.payload; state.value; From dccfee55c277ef96e5a7114919ed7ae12592940c Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Thu, 30 Apr 2020 16:27:03 -0400 Subject: [PATCH 5/8] Replaced explicit process.env checks with environment variable --- src/store.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/store.js b/src/store.js index 2f5b6ab01..6966700fb 100644 --- a/src/store.js +++ b/src/store.js @@ -156,7 +156,7 @@ export class Store { .filter(sub => sub.after) .forEach(sub => sub.after(action, this.state)) } catch (e) { - if (process.env.NODE_ENV !== 'production') { + if (__DEV__) { console.warn(`[vuex] error in after action subscribers: `) console.error(e) } @@ -168,7 +168,7 @@ export class Store { .filter(sub => sub.error) .forEach(sub => sub.error(action, this.state, e)) } catch (_e) { - if (process.env.NODE_ENV !== 'production') { + if (__DEV__) { console.warn(`[vuex] error in after action catch subscribers: `) console.error(_e) } From 90bc4d71f2a443fae23f31ee544a78c35063e4e9 Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Fri, 1 May 2020 08:38:03 -0400 Subject: [PATCH 6/8] Removing dist folder. --- dist/logger.d.ts | 17 - dist/logger.js | 150 ----- dist/vuex.common.js | 1093 ---------------------------------- dist/vuex.esm.browser.js | 1037 -------------------------------- dist/vuex.esm.browser.min.js | 6 - dist/vuex.esm.js | 1078 --------------------------------- dist/vuex.js | 1084 --------------------------------- dist/vuex.min.js | 6 - 8 files changed, 4471 deletions(-) delete mode 100644 dist/logger.d.ts delete mode 100644 dist/logger.js delete mode 100644 dist/vuex.common.js delete mode 100644 dist/vuex.esm.browser.js delete mode 100644 dist/vuex.esm.browser.min.js delete mode 100644 dist/vuex.esm.js delete mode 100644 dist/vuex.js delete mode 100644 dist/vuex.min.js diff --git a/dist/logger.d.ts b/dist/logger.d.ts deleted file mode 100644 index 8ee43089c..000000000 --- a/dist/logger.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Types for the logger plugin. This file must be put alongside the bundled -// JavaScript file of the logger. - -import { Payload, Plugin } from "../types/index"; - -export interface LoggerOption { - collapsed?: boolean; - filter?:

(mutation: P, stateBefore: S, stateAfter: S) => boolean; - transformer?: (state: S) => any; - mutationTransformer?:

(mutation: P) => any; - actionFilter?:

(action: P, state: S) => boolean; - actionTransformer?:

(action: P) => any; - logMutations?: boolean; - logActions?: boolean; -} - -export default function createLogger(option?: LoggerOption): Plugin; diff --git a/dist/logger.js b/dist/logger.js deleted file mode 100644 index cdcde6763..000000000 --- a/dist/logger.js +++ /dev/null @@ -1,150 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.createVuexLogger = factory()); -}(this, function () { 'use strict'; - - /** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - function find (list, f) { - return list.filter(f)[0] - } - - /** - * Deep copy the given object considering circular structure. - * This function caches all nested objects and its copies. - * If it detects circular structure, use cached copy to avoid infinite loop. - * - * @param {*} obj - * @param {Array} cache - * @return {*} - */ - function deepCopy (obj, cache) { - if ( cache === void 0 ) cache = []; - - // just return if obj is immutable value - if (obj === null || typeof obj !== 'object') { - return obj - } - - // if obj is hit, it is in circular structure - var hit = find(cache, function (c) { return c.original === obj; }); - if (hit) { - return hit.copy - } - - var copy = Array.isArray(obj) ? [] : {}; - // put the copy into cache at first - // because we want to refer it in recursive deepCopy - cache.push({ - original: obj, - copy: copy - }); - - Object.keys(obj).forEach(function (key) { - copy[key] = deepCopy(obj[key], cache); - }); - - return copy - } - - // Credits: borrowed code from fcomb/redux-logger - - function createLogger (ref) { - if ( ref === void 0 ) ref = {}; - var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true; - var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; }; - var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; }; - var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; }; - var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; }; - var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; }; - var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true; - var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true; - var logger = ref.logger; if ( logger === void 0 ) logger = console; - - return function (store) { - var prevState = deepCopy(store.state); - - if (typeof logger === 'undefined') { - return - } - - if (logMutations) { - store.subscribe(function (mutation, state) { - var nextState = deepCopy(state); - - if (filter(mutation, prevState, nextState)) { - var formattedTime = getFormattedTime(); - var formattedMutation = mutationTransformer(mutation); - var message = "mutation " + (mutation.type) + formattedTime; - - startMessage(logger, message, collapsed); - logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState)); - logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation); - logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState)); - endMessage(logger); - } - - prevState = nextState; - }); - } - - if (logActions) { - store.subscribeAction(function (action, state) { - if (actionFilter(action, state)) { - var formattedTime = getFormattedTime(); - var formattedAction = actionTransformer(action); - var message = "action " + (action.type) + formattedTime; - - startMessage(logger, message, collapsed); - logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction); - endMessage(logger); - } - }); - } - } - } - - function startMessage (logger, message, collapsed) { - var startMessage = collapsed - ? logger.groupCollapsed - : logger.group; - - // render - try { - startMessage.call(logger, message); - } catch (e) { - logger.log(message); - } - } - - function endMessage (logger) { - try { - logger.groupEnd(); - } catch (e) { - logger.log('—— log end ——'); - } - } - - function getFormattedTime () { - var time = new Date(); - return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3))) - } - - function repeat (str, times) { - return (new Array(times + 1)).join(str) - } - - function pad (num, maxLength) { - return repeat('0', maxLength - num.toString().length) + num - } - - return createLogger; - -})); diff --git a/dist/vuex.common.js b/dist/vuex.common.js deleted file mode 100644 index d6934254c..000000000 --- a/dist/vuex.common.js +++ /dev/null @@ -1,1093 +0,0 @@ -/** - * vuex v3.3.0 - * (c) 2020 Evan You - * @license MIT - */ -'use strict'; - -function applyMixin (Vue) { - var version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - var _init = Vue.prototype._init; - Vue.prototype._init = function (options) { - if ( options === void 0 ) options = {}; - - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - var options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.hasChild = function hasChild (key) { - return key in this._children -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) -}; - -function update (path, targetModule, newModule) { - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - if (process.env.NODE_ENV !== 'production') { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -var Vue; // bind on install - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - if (process.env.NODE_ENV !== 'production') { - assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -prototypeAccessors$1.state.get = function () { - return this._vm._data.$$state -}; - -prototypeAccessors$1.state.set = function (v) { - if (process.env.NODE_ENV !== 'production') { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - process.env.NODE_ENV !== 'production' && - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return new Promise(function (resolve, reject) { - result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - resolve(res); - }, function (e) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.catch; }) - .forEach(function (sub) { return sub.catch(action, this$1.state, e); }); - } catch (_e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in after action catch subscribers: "); - console.error(_e); - } - } - reject(e); - }); - }) -}; - -Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) -}; - -Store.prototype.watch = function watch (getter, cb, options) { - var this$1 = this; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._vm._data.$$state = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); -}; - -Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); -} - -function resetStoreVM (store, state, hot) { - var oldVm = store._vm; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computed = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computed[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return store._vm[key]; }, - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - var silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed: computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(function () { return oldVm.$destroy(); }); - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && process.env.NODE_ENV !== 'production') { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - if (process.env.NODE_ENV !== 'production') { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - Vue.set(parentState, moduleName, module.state); - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, function () { - if (process.env.NODE_ENV !== 'production') { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, sync: true }); -} - -function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - if (process.env.NODE_ENV !== 'production') { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -function install (_Vue) { - if (Vue && _Vue === Vue) { - if (process.env.NODE_ENV !== 'production') { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * 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. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if (process.env.NODE_ENV !== 'production' && !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index = { - Store: Store, - install: install, - version: '3.3.0', - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -module.exports = index; diff --git a/dist/vuex.esm.browser.js b/dist/vuex.esm.browser.js deleted file mode 100644 index 17fece11f..000000000 --- a/dist/vuex.esm.browser.js +++ /dev/null @@ -1,1037 +0,0 @@ -/** - * vuex v3.3.0 - * (c) 2020 Evan You - * @license MIT - */ -function applyMixin (Vue) { - const version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - const _init = Vue.prototype._init; - Vue.prototype._init = function (options = {}) { - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - const options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } -} - -const target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -const devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) return - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', targetState => { - store.replaceState(targetState); - }); - - store.subscribe((mutation, state) => { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction((action, state) => { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(key => fn(obj[key], key)); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) throw new Error(`[vuex] ${msg}`) -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -class Module { - constructor (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - const rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; - } - - get namespaced () { - return !!this._rawModule.namespaced - } - - addChild (key, module) { - this._children[key] = module; - } - - removeChild (key) { - delete this._children[key]; - } - - getChild (key) { - return this._children[key] - } - - hasChild (key) { - return key in this._children - } - - update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } - } - - forEachChild (fn) { - forEachValue(this._children, fn); - } - - forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } - } - - forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } - } - - forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } - } -} - -class ModuleCollection { - constructor (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); - } - - get (path) { - return path.reduce((module, key) => { - return module.getChild(key) - }, this.root) - } - - getNamespace (path) { - let module = this.root; - return path.reduce((namespace, key) => { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') - } - - update (rawRootModule) { - update([], this.root, rawRootModule); - } - - register (path, rawModule, runtime = true) { - { - assertRawModule(path, rawModule); - } - - const newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - const parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, (rawChildModule, key) => { - this.register(path.concat(key), rawChildModule, runtime); - }); - } - } - - unregister (path) { - const parent = this.get(path.slice(0, -1)); - const key = path[path.length - 1]; - if (!parent.getChild(key).runtime) return - - parent.removeChild(key); - } - - isRegistered (path) { - const parent = this.get(path.slice(0, -1)); - const key = path[path.length - 1]; - - return parent.hasChild(key) - } -} - -function update (path, targetModule, newModule) { - { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (const key in newModule.modules) { - if (!targetModule.getChild(key)) { - { - console.warn( - `[vuex] trying to add a new module '${key}' on hot reloading, ` + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -const functionAssert = { - assert: value => typeof value === 'function', - expected: 'function' -}; - -const objectAssert = { - assert: value => typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'), - expected: 'function or object with "handler" function' -}; - -const assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(key => { - if (!rawModule[key]) return - - const assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], (value, type) => { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - let buf = `${key} should be ${expected} but "${key}.${type}"`; - if (path.length > 0) { - buf += ` in module "${path.join('.')}"`; - } - buf += ` is ${JSON.stringify(value)}.`; - return buf -} - -let Vue; // bind on install - -class Store { - constructor (options = {}) { - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - { - assert(Vue, `must call Vue.use(Vuex) before creating a store instance.`); - assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`); - assert(this instanceof Store, `store must be called with the new operator.`); - } - - const { - plugins = [], - strict = false - } = options; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - const store = this; - const { dispatch, commit } = this; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - const state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(plugin => plugin(this)); - - const useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } - } - - get state () { - return this._vm._data.$$state - } - - set state (v) { - { - assert(false, `use store.replaceState() to explicit replace store state.`); - } - } - - commit (_type, _payload, _options) { - // check object-style commit - const { - type, - payload, - options - } = unifyObjectStyle(_type, _payload, _options); - - const mutation = { type, payload }; - const entry = this._mutations[type]; - if (!entry) { - { - console.error(`[vuex] unknown mutation type: ${type}`); - } - return - } - this._withCommit(() => { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(sub => sub(mutation, this.state)); - - if ( - options && options.silent - ) { - console.warn( - `[vuex] mutation type: ${type}. Silent option has been removed. ` + - 'Use the filter functionality in the vue-devtools' - ); - } - } - - dispatch (_type, _payload) { - // check object-style dispatch - const { - type, - payload - } = unifyObjectStyle(_type, _payload); - - const action = { type, payload }; - const entry = this._actions[type]; - if (!entry) { - { - console.error(`[vuex] unknown action type: ${type}`); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(sub => sub.before) - .forEach(sub => sub.before(action, this.state)); - } catch (e) { - { - console.warn(`[vuex] error in before action subscribers: `); - console.error(e); - } - } - - const result = entry.length > 1 - ? Promise.all(entry.map(handler => handler(payload))) - : entry[0](payload); - - return result.then(res => { - try { - this._actionSubscribers - .filter(sub => sub.after) - .forEach(sub => sub.after(action, this.state)); - } catch (e) { - { - console.warn(`[vuex] error in after action subscribers: `); - console.error(e); - } - } - return res - }) - } - - subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) - } - - subscribeAction (fn, options) { - const subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) - } - - watch (getter, cb, options) { - { - assert(typeof getter === 'function', `store.watch only accepts a function.`); - } - return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options) - } - - replaceState (state) { - this._withCommit(() => { - this._vm._data.$$state = state; - }); - } - - registerModule (path, rawModule, options = {}) { - if (typeof path === 'string') path = [path]; - - { - assert(Array.isArray(path), `module path must be a string or an Array.`); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); - } - - unregisterModule (path) { - if (typeof path === 'string') path = [path]; - - { - assert(Array.isArray(path), `module path must be a string or an Array.`); - } - - this._modules.unregister(path); - this._withCommit(() => { - const parentState = getNestedState(this.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); - } - - hasModule (path) { - if (typeof path === 'string') path = [path]; - - { - assert(Array.isArray(path), `module path must be a string or an Array.`); - } - - return this._modules.isRegistered(path) - } - - hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); - } - - _withCommit (fn) { - const committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; - } -} - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return () => { - const i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - const state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); -} - -function resetStoreVM (store, state, hot) { - const oldVm = store._vm; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - const wrappedGetters = store._wrappedGetters; - const computed = {}; - forEachValue(wrappedGetters, (fn, key) => { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computed[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: () => store._vm[key], - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - const silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(() => { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(() => oldVm.$destroy()); - } -} - -function installModule (store, rootState, path, module, hot) { - const isRoot = !path.length; - const namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && "development" !== 'production') { - console.error(`[vuex] duplicate namespace ${namespace} for the namespaced module ${path.join('/')}`); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - const parentState = getNestedState(rootState, path.slice(0, -1)); - const moduleName = path[path.length - 1]; - store._withCommit(() => { - { - if (moduleName in parentState) { - console.warn( - `[vuex] state field "${moduleName}" was overridden by a module with the same name at "${path.join('.')}"` - ); - } - } - Vue.set(parentState, moduleName, module.state); - }); - } - - const local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation((mutation, key) => { - const namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction((action, key) => { - const type = action.root ? key : namespace + key; - const handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter((getter, key) => { - const namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild((child, key) => { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - const noNamespace = namespace === ''; - - const local = { - dispatch: noNamespace ? store.dispatch : (_type, _payload, _options) => { - const args = unifyObjectStyle(_type, _payload, _options); - const { payload, options } = args; - let { type } = args; - - if (!options || !options.root) { - type = namespace + type; - if (!store._actions[type]) { - console.error(`[vuex] unknown local action type: ${args.type}, global type: ${type}`); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : (_type, _payload, _options) => { - const args = unifyObjectStyle(_type, _payload, _options); - const { payload, options } = args; - let { type } = args; - - if (!options || !options.root) { - type = namespace + type; - if (!store._mutations[type]) { - console.error(`[vuex] unknown local mutation type: ${args.type}, global type: ${type}`); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? () => store.getters - : () => makeLocalGetters(store, namespace) - }, - state: { - get: () => getNestedState(store.state, path) - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - const gettersProxy = {}; - const splitPos = namespace.length; - Object.keys(store.getters).forEach(type => { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) return - - // extract local getter type - const localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: () => store.getters[type], - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - const entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - const entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - let res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(err => { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - { - console.error(`[vuex] duplicate getter key: ${type}`); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, () => { - { - assert(store._committing, `do not mutate vuex store state outside mutation handlers.`); - } - }, { deep: true, sync: true }); -} - -function getNestedState (state, path) { - return path.reduce((state, key) => state[key], state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - { - assert(typeof type === 'string', `expects string as the type, but found ${typeof type}.`); - } - - return { type, payload, options } -} - -function install (_Vue) { - if (Vue && _Vue === Vue) { - { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ -const mapState = normalizeNamespace((namespace, states) => { - const res = {}; - if (!isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(({ key, val }) => { - res[key] = function mappedState () { - let state = this.$store.state; - let getters = this.$store.getters; - if (namespace) { - const module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -const mapMutations = normalizeNamespace((namespace, mutations) => { - const res = {}; - if (!isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(({ key, val }) => { - res[key] = function mappedMutation (...args) { - // Get the commit method from store - let commit = this.$store.commit; - if (namespace) { - const module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -const mapGetters = normalizeNamespace((namespace, getters) => { - const res = {}; - if (!isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(({ key, val }) => { - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (!(val in this.$store.getters)) { - console.error(`[vuex] unknown getter: ${val}`); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -const mapActions = normalizeNamespace((namespace, actions) => { - const res = {}; - if (!isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(({ key, val }) => { - res[key] = function mappedAction (...args) { - // get dispatch function from store - let dispatch = this.$store.dispatch; - if (namespace) { - const module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -const createNamespacedHelpers = (namespace) => ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(key => ({ key, val: key })) - : Object.keys(map).map(key => ({ key, val: map[key] })) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * 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. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return (namespace, map) => { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - const module = store._modulesNamespaceMap[namespace]; - if (!module) { - console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`); - } - return module -} - -var index_esm = { - Store, - install, - version: '3.3.0', - mapState, - mapMutations, - mapGetters, - mapActions, - createNamespacedHelpers -}; - -export default index_esm; -export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers }; diff --git a/dist/vuex.esm.browser.min.js b/dist/vuex.esm.browser.min.js deleted file mode 100644 index 3952019a0..000000000 --- a/dist/vuex.esm.browser.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/** - * vuex v3.3.0 - * (c) 2020 Evan You - * @license MIT - */ -const t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,e){Object.keys(t).forEach(s=>e(t[s],s))}function s(t){return null!==t&&"object"==typeof t}class i{constructor(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;const s=t.state;this.state=("function"==typeof s?s():s)||{}}get namespaced(){return!!this._rawModule.namespaced}addChild(t,e){this._children[t]=e}removeChild(t){delete this._children[t]}getChild(t){return this._children[t]}hasChild(t){return t in this._children}update(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)}forEachChild(t){e(this._children,t)}forEachGetter(t){this._rawModule.getters&&e(this._rawModule.getters,t)}forEachAction(t){this._rawModule.actions&&e(this._rawModule.actions,t)}forEachMutation(t){this._rawModule.mutations&&e(this._rawModule.mutations,t)}}class o{constructor(t){this.register([],t,!1)}get(t){return t.reduce((t,e)=>t.getChild(e),this.root)}getNamespace(t){let e=this.root;return t.reduce((t,s)=>t+((e=e.getChild(s)).namespaced?s+"/":""),"")}update(t){!function t(e,s,i){s.update(i);if(i.modules)for(const o in i.modules){if(!s.getChild(o))return;t(e.concat(o),s.getChild(o),i.modules[o])}}([],this.root,t)}register(t,s,o=!0){const n=new i(s,o);if(0===t.length)this.root=n;else{this.get(t.slice(0,-1)).addChild(t[t.length-1],n)}s.modules&&e(s.modules,(e,s)=>{this.register(t.concat(s),e,o)})}unregister(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1];e.getChild(s).runtime&&e.removeChild(s)}isRegistered(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1];return e.hasChild(s)}}let n;class r{constructor(e={}){!n&&"undefined"!=typeof window&&window.Vue&&p(window.Vue);const{plugins:s=[],strict:i=!1}=e;this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new o(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new n,this._makeLocalGettersCache=Object.create(null);const r=this,{dispatch:c,commit:a}=this;this.dispatch=function(t,e){return c.call(r,t,e)},this.commit=function(t,e,s){return a.call(r,t,e,s)},this.strict=i;const l=this._modules.root.state;h(this,l,[],this._modules.root),u(this,l),s.forEach(t=>t(this)),(void 0!==e.devtools?e.devtools:n.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",t=>{e.replaceState(t)}),e.subscribe((e,s)=>{t.emit("vuex:mutation",e,s)},{prepend:!0}),e.subscribeAction((e,s)=>{t.emit("vuex:action",e,s)},{prepend:!0}))}(this)}get state(){return this._vm._data.$$state}set state(t){}commit(t,e,s){const{type:i,payload:o,options:n}=d(t,e,s),r={type:i,payload:o},c=this._mutations[i];c&&(this._withCommit(()=>{c.forEach(function(t){t(o)})}),this._subscribers.slice().forEach(t=>t(r,this.state)))}dispatch(t,e){const{type:s,payload:i}=d(t,e),o={type:s,payload:i},n=this._actions[s];if(n){try{this._actionSubscribers.slice().filter(t=>t.before).forEach(t=>t.before(o,this.state))}catch(t){}return(n.length>1?Promise.all(n.map(t=>t(i))):n[0](i)).then(t=>{try{this._actionSubscribers.filter(t=>t.after).forEach(t=>t.after(o,this.state))}catch(t){}return t})}}subscribe(t,e){return c(t,this._subscribers,e)}subscribeAction(t,e){return c("function"==typeof t?{before:t}:t,this._actionSubscribers,e)}watch(t,e,s){return this._watcherVM.$watch(()=>t(this.state,this.getters),e,s)}replaceState(t){this._withCommit(()=>{this._vm._data.$$state=t})}registerModule(t,e,s={}){"string"==typeof t&&(t=[t]),this._modules.register(t,e),h(this,this.state,t,this._modules.get(t),s.preserveState),u(this,this.state)}unregisterModule(t){"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit(()=>{const e=l(this.state,t.slice(0,-1));n.delete(e,t[t.length-1])}),a(this)}hasModule(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)}hotUpdate(t){this._modules.update(t),a(this,!0)}_withCommit(t){const e=this._committing;this._committing=!0,t(),this._committing=e}}function c(t,e,s){return e.indexOf(t)<0&&(s&&s.prepend?e.unshift(t):e.push(t)),()=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)}}function a(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);const s=t.state;h(t,s,[],t._modules.root,!0),u(t,s,e)}function u(t,s,i){const o=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);const r=t._wrappedGetters,c={};e(r,(e,s)=>{c[s]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,s,{get:()=>t._vm[s],enumerable:!0})});const a=n.config.silent;n.config.silent=!0,t._vm=new n({data:{$$state:s},computed:c}),n.config.silent=a,t.strict&&function(t){t._vm.$watch(function(){return this._data.$$state},()=>{},{deep:!0,sync:!0})}(t),o&&(i&&t._withCommit(()=>{o._data.$$state=null}),n.nextTick(()=>o.$destroy()))}function h(t,e,s,i,o){const r=!s.length,c=t._modules.getNamespace(s);if(i.namespaced&&(t._modulesNamespaceMap[c],t._modulesNamespaceMap[c]=i),!r&&!o){const o=l(e,s.slice(0,-1)),r=s[s.length-1];t._withCommit(()=>{n.set(o,r,i.state)})}const a=i.context=function(t,e,s){const i=""===e,o={dispatch:i?t.dispatch:(s,i,o)=>{const n=d(s,i,o),{payload:r,options:c}=n;let{type:a}=n;return c&&c.root||(a=e+a),t.dispatch(a,r)},commit:i?t.commit:(s,i,o)=>{const n=d(s,i,o),{payload:r,options:c}=n;let{type:a}=n;c&&c.root||(a=e+a),t.commit(a,r,c)}};return Object.defineProperties(o,{getters:{get:i?()=>t.getters:()=>(function(t,e){if(!t._makeLocalGettersCache[e]){const s={},i=e.length;Object.keys(t.getters).forEach(o=>{if(o.slice(0,i)!==e)return;const n=o.slice(i);Object.defineProperty(s,n,{get:()=>t.getters[o],enumerable:!0})}),t._makeLocalGettersCache[e]=s}return t._makeLocalGettersCache[e]})(t,e)},state:{get:()=>l(t.state,s)}}),o}(t,c,s);i.forEachMutation((e,s)=>{!function(t,e,s,i){(t._mutations[e]||(t._mutations[e]=[])).push(function(e){s.call(t,i.state,e)})}(t,c+s,e,a)}),i.forEachAction((e,s)=>{const i=e.root?s:c+s,o=e.handler||e;!function(t,e,s,i){(t._actions[e]||(t._actions[e]=[])).push(function(e){let o=s.call(t,{dispatch:i.dispatch,commit:i.commit,getters:i.getters,state:i.state,rootGetters:t.getters,rootState:t.state},e);var n;return(n=o)&&"function"==typeof n.then||(o=Promise.resolve(o)),t._devtoolHook?o.catch(e=>{throw t._devtoolHook.emit("vuex:error",e),e}):o})}(t,i,o,a)}),i.forEachGetter((e,s)=>{!function(t,e,s,i){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return s(i.state,i.getters,t.state,t.getters)}}(t,c+s,e,a)}),i.forEachChild((i,n)=>{h(t,e,s.concat(n),i,o)})}function l(t,e){return e.reduce((t,e)=>t[e],t)}function d(t,e,i){return s(t)&&t.type&&(i=e,e=t,t=t.type),{type:t,payload:e,options:i}}function p(t){n&&t===n||function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:e});else{const s=t.prototype._init;t.prototype._init=function(t={}){t.init=t.init?[e].concat(t.init):e,s.call(this,t)}}function e(){const t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(n=t)}const m=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{s[e]=function(){let e=this.$store.state,s=this.$store.getters;if(t){const i=v(this.$store,"mapState",t);if(!i)return;e=i.context.state,s=i.context.getters}return"function"==typeof i?i.call(this,e,s):e[i]},s[e].vuex=!0}),s}),f=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{s[e]=function(...e){let s=this.$store.commit;if(t){const e=v(this.$store,"mapMutations",t);if(!e)return;s=e.context.commit}return"function"==typeof i?i.apply(this,[s].concat(e)):s.apply(this.$store,[i].concat(e))}}),s}),_=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{i=t+i,s[e]=function(){if(!t||v(this.$store,"mapGetters",t))return this.$store.getters[i]},s[e].vuex=!0}),s}),g=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{s[e]=function(...e){let s=this.$store.dispatch;if(t){const e=v(this.$store,"mapActions",t);if(!e)return;s=e.context.dispatch}return"function"==typeof i?i.apply(this,[s].concat(e)):s.apply(this.$store,[i].concat(e))}}),s}),y=t=>({mapState:m.bind(null,t),mapGetters:_.bind(null,t),mapMutations:f.bind(null,t),mapActions:g.bind(null,t)});function b(t){return function(t){return Array.isArray(t)||s(t)}(t)?Array.isArray(t)?t.map(t=>({key:t,val:t})):Object.keys(t).map(e=>({key:e,val:t[e]})):[]}function w(t){return(e,s)=>("string"!=typeof e?(s=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,s))}function v(t,e,s){return t._modulesNamespaceMap[s]}export default{Store:r,install:p,version:"3.3.0",mapState:m,mapMutations:f,mapGetters:_,mapActions:g,createNamespacedHelpers:y};export{r as Store,p as install,m as mapState,f as mapMutations,_ as mapGetters,g as mapActions,y as createNamespacedHelpers}; \ No newline at end of file diff --git a/dist/vuex.esm.js b/dist/vuex.esm.js deleted file mode 100644 index 8c0774bac..000000000 --- a/dist/vuex.esm.js +++ /dev/null @@ -1,1078 +0,0 @@ -/** - * vuex v3.3.0 - * (c) 2020 Evan You - * @license MIT - */ -function applyMixin (Vue) { - var version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - var _init = Vue.prototype._init; - Vue.prototype._init = function (options) { - if ( options === void 0 ) options = {}; - - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - var options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } -} - -var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; -var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - -function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); -} - -/** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - -/** - * forEach for object - */ -function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); -} - -function isObject (obj) { - return obj !== null && typeof obj === 'object' -} - -function isPromise (val) { - return val && typeof val.then === 'function' -} - -function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } -} - -function partial (fn, arg) { - return function () { - return fn(arg) - } -} - -// Base data struct for store's module, package with some attribute and method -var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; -}; - -var prototypeAccessors = { namespaced: { configurable: true } }; - -prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced -}; - -Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; -}; - -Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; -}; - -Module.prototype.getChild = function getChild (key) { - return this._children[key] -}; - -Module.prototype.hasChild = function hasChild (key) { - return key in this._children -}; - -Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } -}; - -Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); -}; - -Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } -}; - -Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } -}; - -Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } -}; - -Object.defineProperties( Module.prototype, prototypeAccessors ); - -var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); -}; - -ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) -}; - -ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') -}; - -ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); -}; - -ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } -}; - -ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); -}; - -ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) -}; - -function update (path, targetModule, newModule) { - if (process.env.NODE_ENV !== 'production') { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - if (process.env.NODE_ENV !== 'production') { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } -} - -var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' -}; - -var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' -}; - -var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert -}; - -function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); -} - -function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf -} - -var Vue; // bind on install - -var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - if (process.env.NODE_ENV !== 'production') { - assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } -}; - -var prototypeAccessors$1 = { state: { configurable: true } }; - -prototypeAccessors$1.state.get = function () { - return this._vm._data.$$state -}; - -prototypeAccessors$1.state.set = function (v) { - if (process.env.NODE_ENV !== 'production') { - assert(false, "use store.replaceState() to explicit replace store state."); - } -}; - -Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - process.env.NODE_ENV !== 'production' && - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } -}; - -Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - return res - }) -}; - -Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) -}; - -Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) -}; - -Store.prototype.watch = function watch (getter, cb, options) { - var this$1 = this; - - if (process.env.NODE_ENV !== 'production') { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) -}; - -Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._vm._data.$$state = state; - }); -}; - -Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); -}; - -Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); -}; - -Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - if (process.env.NODE_ENV !== 'production') { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) -}; - -Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); -}; - -Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; -}; - -Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - -function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } -} - -function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); -} - -function resetStoreVM (store, state, hot) { - var oldVm = store._vm; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computed = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computed[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return store._vm[key]; }, - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - var silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed: computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(function () { return oldVm.$destroy(); }); - } -} - -function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && process.env.NODE_ENV !== 'production') { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - if (process.env.NODE_ENV !== 'production') { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - Vue.set(parentState, moduleName, module.state); - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); -} - -/** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ -function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local -} - -function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] -} - -function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); -} - -function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); -} - -function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - if (process.env.NODE_ENV !== 'production') { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; -} - -function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, function () { - if (process.env.NODE_ENV !== 'production') { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, sync: true }); -} - -function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) -} - -function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - if (process.env.NODE_ENV !== 'production') { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } -} - -function install (_Vue) { - if (Vue && _Vue === Vue) { - if (process.env.NODE_ENV !== 'production') { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); -} - -/** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ -var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ -var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res -}); - -/** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ -var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if (process.env.NODE_ENV !== 'production' && !isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res -}); - -/** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ -var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) -}); }; - -/** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ -function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) -} - -/** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ -function isValidMap (map) { - return Array.isArray(map) || isObject(map) -} - -/** - * 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. - * @param {Function} fn - * @return {Function} - */ -function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } -} - -/** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ -function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if (process.env.NODE_ENV !== 'production' && !module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module -} - -var index_esm = { - Store: Store, - install: install, - version: '3.3.0', - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers -}; - -export default index_esm; -export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers }; diff --git a/dist/vuex.js b/dist/vuex.js deleted file mode 100644 index 2f893a40a..000000000 --- a/dist/vuex.js +++ /dev/null @@ -1,1084 +0,0 @@ -/** - * vuex v3.3.0 - * (c) 2020 Evan You - * @license MIT - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = global || self, global.Vuex = factory()); -}(this, function () { 'use strict'; - - function applyMixin (Vue) { - var version = Number(Vue.version.split('.')[0]); - - if (version >= 2) { - Vue.mixin({ beforeCreate: vuexInit }); - } else { - // override init and inject vuex init procedure - // for 1.x backwards compatibility. - var _init = Vue.prototype._init; - Vue.prototype._init = function (options) { - if ( options === void 0 ) options = {}; - - options.init = options.init - ? [vuexInit].concat(options.init) - : vuexInit; - _init.call(this, options); - }; - } - - /** - * Vuex init hook, injected into each instances init hooks list. - */ - - function vuexInit () { - var options = this.$options; - // store injection - if (options.store) { - this.$store = typeof options.store === 'function' - ? options.store() - : options.store; - } else if (options.parent && options.parent.$store) { - this.$store = options.parent.$store; - } - } - } - - var target = typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : {}; - var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; - - function devtoolPlugin (store) { - if (!devtoolHook) { return } - - store._devtoolHook = devtoolHook; - - devtoolHook.emit('vuex:init', store); - - devtoolHook.on('vuex:travel-to-state', function (targetState) { - store.replaceState(targetState); - }); - - store.subscribe(function (mutation, state) { - devtoolHook.emit('vuex:mutation', mutation, state); - }, { prepend: true }); - - store.subscribeAction(function (action, state) { - devtoolHook.emit('vuex:action', action, state); - }, { prepend: true }); - } - - /** - * Get the first item that pass the test - * by second argument function - * - * @param {Array} list - * @param {Function} f - * @return {*} - */ - - /** - * forEach for object - */ - function forEachValue (obj, fn) { - Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); - } - - function isObject (obj) { - return obj !== null && typeof obj === 'object' - } - - function isPromise (val) { - return val && typeof val.then === 'function' - } - - function assert (condition, msg) { - if (!condition) { throw new Error(("[vuex] " + msg)) } - } - - function partial (fn, arg) { - return function () { - return fn(arg) - } - } - - // Base data struct for store's module, package with some attribute and method - var Module = function Module (rawModule, runtime) { - this.runtime = runtime; - // Store some children item - this._children = Object.create(null); - // Store the origin module object which passed by programmer - this._rawModule = rawModule; - var rawState = rawModule.state; - - // Store the origin module's state - this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; - }; - - var prototypeAccessors = { namespaced: { configurable: true } }; - - prototypeAccessors.namespaced.get = function () { - return !!this._rawModule.namespaced - }; - - Module.prototype.addChild = function addChild (key, module) { - this._children[key] = module; - }; - - Module.prototype.removeChild = function removeChild (key) { - delete this._children[key]; - }; - - Module.prototype.getChild = function getChild (key) { - return this._children[key] - }; - - Module.prototype.hasChild = function hasChild (key) { - return key in this._children - }; - - Module.prototype.update = function update (rawModule) { - this._rawModule.namespaced = rawModule.namespaced; - if (rawModule.actions) { - this._rawModule.actions = rawModule.actions; - } - if (rawModule.mutations) { - this._rawModule.mutations = rawModule.mutations; - } - if (rawModule.getters) { - this._rawModule.getters = rawModule.getters; - } - }; - - Module.prototype.forEachChild = function forEachChild (fn) { - forEachValue(this._children, fn); - }; - - Module.prototype.forEachGetter = function forEachGetter (fn) { - if (this._rawModule.getters) { - forEachValue(this._rawModule.getters, fn); - } - }; - - Module.prototype.forEachAction = function forEachAction (fn) { - if (this._rawModule.actions) { - forEachValue(this._rawModule.actions, fn); - } - }; - - Module.prototype.forEachMutation = function forEachMutation (fn) { - if (this._rawModule.mutations) { - forEachValue(this._rawModule.mutations, fn); - } - }; - - Object.defineProperties( Module.prototype, prototypeAccessors ); - - var ModuleCollection = function ModuleCollection (rawRootModule) { - // register root module (Vuex.Store options) - this.register([], rawRootModule, false); - }; - - ModuleCollection.prototype.get = function get (path) { - return path.reduce(function (module, key) { - return module.getChild(key) - }, this.root) - }; - - ModuleCollection.prototype.getNamespace = function getNamespace (path) { - var module = this.root; - return path.reduce(function (namespace, key) { - module = module.getChild(key); - return namespace + (module.namespaced ? key + '/' : '') - }, '') - }; - - ModuleCollection.prototype.update = function update$1 (rawRootModule) { - update([], this.root, rawRootModule); - }; - - ModuleCollection.prototype.register = function register (path, rawModule, runtime) { - var this$1 = this; - if ( runtime === void 0 ) runtime = true; - - { - assertRawModule(path, rawModule); - } - - var newModule = new Module(rawModule, runtime); - if (path.length === 0) { - this.root = newModule; - } else { - var parent = this.get(path.slice(0, -1)); - parent.addChild(path[path.length - 1], newModule); - } - - // register nested modules - if (rawModule.modules) { - forEachValue(rawModule.modules, function (rawChildModule, key) { - this$1.register(path.concat(key), rawChildModule, runtime); - }); - } - }; - - ModuleCollection.prototype.unregister = function unregister (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - if (!parent.getChild(key).runtime) { return } - - parent.removeChild(key); - }; - - ModuleCollection.prototype.isRegistered = function isRegistered (path) { - var parent = this.get(path.slice(0, -1)); - var key = path[path.length - 1]; - - return parent.hasChild(key) - }; - - function update (path, targetModule, newModule) { - { - assertRawModule(path, newModule); - } - - // update target module - targetModule.update(newModule); - - // update nested modules - if (newModule.modules) { - for (var key in newModule.modules) { - if (!targetModule.getChild(key)) { - { - console.warn( - "[vuex] trying to add a new module '" + key + "' on hot reloading, " + - 'manual reload is needed' - ); - } - return - } - update( - path.concat(key), - targetModule.getChild(key), - newModule.modules[key] - ); - } - } - } - - var functionAssert = { - assert: function (value) { return typeof value === 'function'; }, - expected: 'function' - }; - - var objectAssert = { - assert: function (value) { return typeof value === 'function' || - (typeof value === 'object' && typeof value.handler === 'function'); }, - expected: 'function or object with "handler" function' - }; - - var assertTypes = { - getters: functionAssert, - mutations: functionAssert, - actions: objectAssert - }; - - function assertRawModule (path, rawModule) { - Object.keys(assertTypes).forEach(function (key) { - if (!rawModule[key]) { return } - - var assertOptions = assertTypes[key]; - - forEachValue(rawModule[key], function (value, type) { - assert( - assertOptions.assert(value), - makeAssertionMessage(path, key, type, value, assertOptions.expected) - ); - }); - }); - } - - function makeAssertionMessage (path, key, type, value, expected) { - var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; - if (path.length > 0) { - buf += " in module \"" + (path.join('.')) + "\""; - } - buf += " is " + (JSON.stringify(value)) + "."; - return buf - } - - var Vue; // bind on install - - var Store = function Store (options) { - var this$1 = this; - if ( options === void 0 ) options = {}; - - // Auto install if it is not done yet and `window` has `Vue`. - // To allow users to avoid auto-installation in some cases, - // this code should be placed here. See #731 - if (!Vue && typeof window !== 'undefined' && window.Vue) { - install(window.Vue); - } - - { - assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); - assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); - assert(this instanceof Store, "store must be called with the new operator."); - } - - var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; - var strict = options.strict; if ( strict === void 0 ) strict = false; - - // store internal state - this._committing = false; - this._actions = Object.create(null); - this._actionSubscribers = []; - this._mutations = Object.create(null); - this._wrappedGetters = Object.create(null); - this._modules = new ModuleCollection(options); - this._modulesNamespaceMap = Object.create(null); - this._subscribers = []; - this._watcherVM = new Vue(); - this._makeLocalGettersCache = Object.create(null); - - // bind commit and dispatch to self - var store = this; - var ref = this; - var dispatch = ref.dispatch; - var commit = ref.commit; - this.dispatch = function boundDispatch (type, payload) { - return dispatch.call(store, type, payload) - }; - this.commit = function boundCommit (type, payload, options) { - return commit.call(store, type, payload, options) - }; - - // strict mode - this.strict = strict; - - var state = this._modules.root.state; - - // init root module. - // this also recursively registers all sub-modules - // and collects all module getters inside this._wrappedGetters - installModule(this, state, [], this._modules.root); - - // initialize the store vm, which is responsible for the reactivity - // (also registers _wrappedGetters as computed properties) - resetStoreVM(this, state); - - // apply plugins - plugins.forEach(function (plugin) { return plugin(this$1); }); - - var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; - if (useDevtools) { - devtoolPlugin(this); - } - }; - - var prototypeAccessors$1 = { state: { configurable: true } }; - - prototypeAccessors$1.state.get = function () { - return this._vm._data.$$state - }; - - prototypeAccessors$1.state.set = function (v) { - { - assert(false, "use store.replaceState() to explicit replace store state."); - } - }; - - Store.prototype.commit = function commit (_type, _payload, _options) { - var this$1 = this; - - // check object-style commit - var ref = unifyObjectStyle(_type, _payload, _options); - var type = ref.type; - var payload = ref.payload; - var options = ref.options; - - var mutation = { type: type, payload: payload }; - var entry = this._mutations[type]; - if (!entry) { - { - console.error(("[vuex] unknown mutation type: " + type)); - } - return - } - this._withCommit(function () { - entry.forEach(function commitIterator (handler) { - handler(payload); - }); - }); - - this._subscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .forEach(function (sub) { return sub(mutation, this$1.state); }); - - if ( - options && options.silent - ) { - console.warn( - "[vuex] mutation type: " + type + ". Silent option has been removed. " + - 'Use the filter functionality in the vue-devtools' - ); - } - }; - - Store.prototype.dispatch = function dispatch (_type, _payload) { - var this$1 = this; - - // check object-style dispatch - var ref = unifyObjectStyle(_type, _payload); - var type = ref.type; - var payload = ref.payload; - - var action = { type: type, payload: payload }; - var entry = this._actions[type]; - if (!entry) { - { - console.error(("[vuex] unknown action type: " + type)); - } - return - } - - try { - this._actionSubscribers - .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe - .filter(function (sub) { return sub.before; }) - .forEach(function (sub) { return sub.before(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in before action subscribers: "); - console.error(e); - } - } - - var result = entry.length > 1 - ? Promise.all(entry.map(function (handler) { return handler(payload); })) - : entry[0](payload); - - return result.then(function (res) { - try { - this$1._actionSubscribers - .filter(function (sub) { return sub.after; }) - .forEach(function (sub) { return sub.after(action, this$1.state); }); - } catch (e) { - { - console.warn("[vuex] error in after action subscribers: "); - console.error(e); - } - } - return res - }) - }; - - Store.prototype.subscribe = function subscribe (fn, options) { - return genericSubscribe(fn, this._subscribers, options) - }; - - Store.prototype.subscribeAction = function subscribeAction (fn, options) { - var subs = typeof fn === 'function' ? { before: fn } : fn; - return genericSubscribe(subs, this._actionSubscribers, options) - }; - - Store.prototype.watch = function watch (getter, cb, options) { - var this$1 = this; - - { - assert(typeof getter === 'function', "store.watch only accepts a function."); - } - return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) - }; - - Store.prototype.replaceState = function replaceState (state) { - var this$1 = this; - - this._withCommit(function () { - this$1._vm._data.$$state = state; - }); - }; - - Store.prototype.registerModule = function registerModule (path, rawModule, options) { - if ( options === void 0 ) options = {}; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - assert(path.length > 0, 'cannot register the root module by using registerModule.'); - } - - this._modules.register(path, rawModule); - installModule(this, this.state, path, this._modules.get(path), options.preserveState); - // reset store to update getters... - resetStoreVM(this, this.state); - }; - - Store.prototype.unregisterModule = function unregisterModule (path) { - var this$1 = this; - - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - this._modules.unregister(path); - this._withCommit(function () { - var parentState = getNestedState(this$1.state, path.slice(0, -1)); - Vue.delete(parentState, path[path.length - 1]); - }); - resetStore(this); - }; - - Store.prototype.hasModule = function hasModule (path) { - if (typeof path === 'string') { path = [path]; } - - { - assert(Array.isArray(path), "module path must be a string or an Array."); - } - - return this._modules.isRegistered(path) - }; - - Store.prototype.hotUpdate = function hotUpdate (newOptions) { - this._modules.update(newOptions); - resetStore(this, true); - }; - - Store.prototype._withCommit = function _withCommit (fn) { - var committing = this._committing; - this._committing = true; - fn(); - this._committing = committing; - }; - - Object.defineProperties( Store.prototype, prototypeAccessors$1 ); - - function genericSubscribe (fn, subs, options) { - if (subs.indexOf(fn) < 0) { - options && options.prepend - ? subs.unshift(fn) - : subs.push(fn); - } - return function () { - var i = subs.indexOf(fn); - if (i > -1) { - subs.splice(i, 1); - } - } - } - - function resetStore (store, hot) { - store._actions = Object.create(null); - store._mutations = Object.create(null); - store._wrappedGetters = Object.create(null); - store._modulesNamespaceMap = Object.create(null); - var state = store.state; - // init all modules - installModule(store, state, [], store._modules.root, true); - // reset vm - resetStoreVM(store, state, hot); - } - - function resetStoreVM (store, state, hot) { - var oldVm = store._vm; - - // bind store public getters - store.getters = {}; - // reset local getters cache - store._makeLocalGettersCache = Object.create(null); - var wrappedGetters = store._wrappedGetters; - var computed = {}; - forEachValue(wrappedGetters, function (fn, key) { - // use computed to leverage its lazy-caching mechanism - // direct inline function use will lead to closure preserving oldVm. - // using partial to return function with only arguments preserved in closure environment. - computed[key] = partial(fn, store); - Object.defineProperty(store.getters, key, { - get: function () { return store._vm[key]; }, - enumerable: true // for local getters - }); - }); - - // use a Vue instance to store the state tree - // suppress warnings just in case the user has added - // some funky global mixins - var silent = Vue.config.silent; - Vue.config.silent = true; - store._vm = new Vue({ - data: { - $$state: state - }, - computed: computed - }); - Vue.config.silent = silent; - - // enable strict mode for new vm - if (store.strict) { - enableStrictMode(store); - } - - if (oldVm) { - if (hot) { - // dispatch changes in all subscribed watchers - // to force getter re-evaluation for hot reloading. - store._withCommit(function () { - oldVm._data.$$state = null; - }); - } - Vue.nextTick(function () { return oldVm.$destroy(); }); - } - } - - function installModule (store, rootState, path, module, hot) { - var isRoot = !path.length; - var namespace = store._modules.getNamespace(path); - - // register in namespace map - if (module.namespaced) { - if (store._modulesNamespaceMap[namespace] && "development" !== 'production') { - console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); - } - store._modulesNamespaceMap[namespace] = module; - } - - // set state - if (!isRoot && !hot) { - var parentState = getNestedState(rootState, path.slice(0, -1)); - var moduleName = path[path.length - 1]; - store._withCommit(function () { - { - if (moduleName in parentState) { - console.warn( - ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") - ); - } - } - Vue.set(parentState, moduleName, module.state); - }); - } - - var local = module.context = makeLocalContext(store, namespace, path); - - module.forEachMutation(function (mutation, key) { - var namespacedType = namespace + key; - registerMutation(store, namespacedType, mutation, local); - }); - - module.forEachAction(function (action, key) { - var type = action.root ? key : namespace + key; - var handler = action.handler || action; - registerAction(store, type, handler, local); - }); - - module.forEachGetter(function (getter, key) { - var namespacedType = namespace + key; - registerGetter(store, namespacedType, getter, local); - }); - - module.forEachChild(function (child, key) { - installModule(store, rootState, path.concat(key), child, hot); - }); - } - - /** - * make localized dispatch, commit, getters and state - * if there is no namespace, just use root ones - */ - function makeLocalContext (store, namespace, path) { - var noNamespace = namespace === ''; - - var local = { - dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (!store._actions[type]) { - console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); - return - } - } - - return store.dispatch(type, payload) - }, - - commit: noNamespace ? store.commit : function (_type, _payload, _options) { - var args = unifyObjectStyle(_type, _payload, _options); - var payload = args.payload; - var options = args.options; - var type = args.type; - - if (!options || !options.root) { - type = namespace + type; - if (!store._mutations[type]) { - console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); - return - } - } - - store.commit(type, payload, options); - } - }; - - // getters and state object must be gotten lazily - // because they will be changed by vm update - Object.defineProperties(local, { - getters: { - get: noNamespace - ? function () { return store.getters; } - : function () { return makeLocalGetters(store, namespace); } - }, - state: { - get: function () { return getNestedState(store.state, path); } - } - }); - - return local - } - - function makeLocalGetters (store, namespace) { - if (!store._makeLocalGettersCache[namespace]) { - var gettersProxy = {}; - var splitPos = namespace.length; - Object.keys(store.getters).forEach(function (type) { - // skip if the target getter is not match this namespace - if (type.slice(0, splitPos) !== namespace) { return } - - // extract local getter type - var localType = type.slice(splitPos); - - // Add a port to the getters proxy. - // Define as getter property because - // we do not want to evaluate the getters in this time. - Object.defineProperty(gettersProxy, localType, { - get: function () { return store.getters[type]; }, - enumerable: true - }); - }); - store._makeLocalGettersCache[namespace] = gettersProxy; - } - - return store._makeLocalGettersCache[namespace] - } - - function registerMutation (store, type, handler, local) { - var entry = store._mutations[type] || (store._mutations[type] = []); - entry.push(function wrappedMutationHandler (payload) { - handler.call(store, local.state, payload); - }); - } - - function registerAction (store, type, handler, local) { - var entry = store._actions[type] || (store._actions[type] = []); - entry.push(function wrappedActionHandler (payload) { - var res = handler.call(store, { - dispatch: local.dispatch, - commit: local.commit, - getters: local.getters, - state: local.state, - rootGetters: store.getters, - rootState: store.state - }, payload); - if (!isPromise(res)) { - res = Promise.resolve(res); - } - if (store._devtoolHook) { - return res.catch(function (err) { - store._devtoolHook.emit('vuex:error', err); - throw err - }) - } else { - return res - } - }); - } - - function registerGetter (store, type, rawGetter, local) { - if (store._wrappedGetters[type]) { - { - console.error(("[vuex] duplicate getter key: " + type)); - } - return - } - store._wrappedGetters[type] = function wrappedGetter (store) { - return rawGetter( - local.state, // local state - local.getters, // local getters - store.state, // root state - store.getters // root getters - ) - }; - } - - function enableStrictMode (store) { - store._vm.$watch(function () { return this._data.$$state }, function () { - { - assert(store._committing, "do not mutate vuex store state outside mutation handlers."); - } - }, { deep: true, sync: true }); - } - - function getNestedState (state, path) { - return path.reduce(function (state, key) { return state[key]; }, state) - } - - function unifyObjectStyle (type, payload, options) { - if (isObject(type) && type.type) { - options = payload; - payload = type; - type = type.type; - } - - { - assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); - } - - return { type: type, payload: payload, options: options } - } - - function install (_Vue) { - if (Vue && _Vue === Vue) { - { - console.error( - '[vuex] already installed. Vue.use(Vuex) should be called only once.' - ); - } - return - } - Vue = _Vue; - applyMixin(Vue); - } - - /** - * Reduce the code which written in Vue.js for getting the state. - * @param {String} [namespace] - Module's namespace - * @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. - * @param {Object} - */ - var mapState = normalizeNamespace(function (namespace, states) { - var res = {}; - if (!isValidMap(states)) { - console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); - } - normalizeMap(states).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedState () { - var state = this.$store.state; - var getters = this.$store.getters; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapState', namespace); - if (!module) { - return - } - state = module.context.state; - getters = module.context.getters; - } - return typeof val === 'function' - ? val.call(this, state, getters) - : state[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for committing the mutation - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ - var mapMutations = normalizeNamespace(function (namespace, mutations) { - var res = {}; - if (!isValidMap(mutations)) { - console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); - } - normalizeMap(mutations).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedMutation () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // Get the commit method from store - var commit = this.$store.commit; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); - if (!module) { - return - } - commit = module.context.commit; - } - return typeof val === 'function' - ? val.apply(this, [commit].concat(args)) - : commit.apply(this.$store, [val].concat(args)) - }; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for getting the getters - * @param {String} [namespace] - Module's namespace - * @param {Object|Array} getters - * @return {Object} - */ - var mapGetters = normalizeNamespace(function (namespace, getters) { - var res = {}; - if (!isValidMap(getters)) { - console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); - } - normalizeMap(getters).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - // The namespace has been mutated by normalizeNamespace - val = namespace + val; - res[key] = function mappedGetter () { - if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { - return - } - if (!(val in this.$store.getters)) { - console.error(("[vuex] unknown getter: " + val)); - return - } - return this.$store.getters[val] - }; - // mark vuex getter for devtools - res[key].vuex = true; - }); - return res - }); - - /** - * Reduce the code which written in Vue.js for dispatch the action - * @param {String} [namespace] - Module's namespace - * @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. - * @return {Object} - */ - var mapActions = normalizeNamespace(function (namespace, actions) { - var res = {}; - if (!isValidMap(actions)) { - console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); - } - normalizeMap(actions).forEach(function (ref) { - var key = ref.key; - var val = ref.val; - - res[key] = function mappedAction () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - // get dispatch function from store - var dispatch = this.$store.dispatch; - if (namespace) { - var module = getModuleByNamespace(this.$store, 'mapActions', namespace); - if (!module) { - return - } - dispatch = module.context.dispatch; - } - return typeof val === 'function' - ? val.apply(this, [dispatch].concat(args)) - : dispatch.apply(this.$store, [val].concat(args)) - }; - }); - return res - }); - - /** - * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object - * @param {String} namespace - * @return {Object} - */ - var createNamespacedHelpers = function (namespace) { return ({ - mapState: mapState.bind(null, namespace), - mapGetters: mapGetters.bind(null, namespace), - mapMutations: mapMutations.bind(null, namespace), - mapActions: mapActions.bind(null, namespace) - }); }; - - /** - * Normalize the map - * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] - * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] - * @param {Array|Object} map - * @return {Object} - */ - function normalizeMap (map) { - if (!isValidMap(map)) { - return [] - } - return Array.isArray(map) - ? map.map(function (key) { return ({ key: key, val: key }); }) - : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) - } - - /** - * Validate whether given map is valid or not - * @param {*} map - * @return {Boolean} - */ - function isValidMap (map) { - return Array.isArray(map) || isObject(map) - } - - /** - * 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. - * @param {Function} fn - * @return {Function} - */ - function normalizeNamespace (fn) { - return function (namespace, map) { - if (typeof namespace !== 'string') { - map = namespace; - namespace = ''; - } else if (namespace.charAt(namespace.length - 1) !== '/') { - namespace += '/'; - } - return fn(namespace, map) - } - } - - /** - * Search a special module from store by namespace. if module not exist, print error message. - * @param {Object} store - * @param {String} helper - * @param {String} namespace - * @return {Object} - */ - function getModuleByNamespace (store, helper, namespace) { - var module = store._modulesNamespaceMap[namespace]; - if (!module) { - console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); - } - return module - } - - var index = { - Store: Store, - install: install, - version: '3.3.0', - mapState: mapState, - mapMutations: mapMutations, - mapGetters: mapGetters, - mapActions: mapActions, - createNamespacedHelpers: createNamespacedHelpers - }; - - return index; - -})); diff --git a/dist/vuex.min.js b/dist/vuex.min.js deleted file mode 100644 index cd5ce4c56..000000000 --- a/dist/vuex.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/** - * vuex v3.3.0 - * (c) 2020 Evan You - * @license MIT - */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Vuex=e()}(this,function(){"use strict";var t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,e){Object.keys(t).forEach(function(n){return e(t[n],n)})}function n(t){return null!==t&&"object"==typeof t}var o=function(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;var n=t.state;this.state=("function"==typeof n?n():n)||{}},i={namespaced:{configurable:!0}};i.namespaced.get=function(){return!!this._rawModule.namespaced},o.prototype.addChild=function(t,e){this._children[t]=e},o.prototype.removeChild=function(t){delete this._children[t]},o.prototype.getChild=function(t){return this._children[t]},o.prototype.hasChild=function(t){return t in this._children},o.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},o.prototype.forEachChild=function(t){e(this._children,t)},o.prototype.forEachGetter=function(t){this._rawModule.getters&&e(this._rawModule.getters,t)},o.prototype.forEachAction=function(t){this._rawModule.actions&&e(this._rawModule.actions,t)},o.prototype.forEachMutation=function(t){this._rawModule.mutations&&e(this._rawModule.mutations,t)},Object.defineProperties(o.prototype,i);var r,s=function(t){this.register([],t,!1)};s.prototype.get=function(t){return t.reduce(function(t,e){return t.getChild(e)},this.root)},s.prototype.getNamespace=function(t){var e=this.root;return t.reduce(function(t,n){return t+((e=e.getChild(n)).namespaced?n+"/":"")},"")},s.prototype.update=function(t){!function t(e,n,o){n.update(o);if(o.modules)for(var i in o.modules){if(!n.getChild(i))return;t(e.concat(i),n.getChild(i),o.modules[i])}}([],this.root,t)},s.prototype.register=function(t,n,i){var r=this;void 0===i&&(i=!0);var s=new o(n,i);0===t.length?this.root=s:this.get(t.slice(0,-1)).addChild(t[t.length-1],s);n.modules&&e(n.modules,function(e,n){r.register(t.concat(n),e,i)})},s.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];e.getChild(n).runtime&&e.removeChild(n)},s.prototype.isRegistered=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];return e.hasChild(n)};var a=function(e){var n=this;void 0===e&&(e={}),!r&&"undefined"!=typeof window&&window.Vue&&m(window.Vue);var o=e.plugins;void 0===o&&(o=[]);var i=e.strict;void 0===i&&(i=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new s(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new r,this._makeLocalGettersCache=Object.create(null);var a=this,c=this.dispatch,u=this.commit;this.dispatch=function(t,e){return c.call(a,t,e)},this.commit=function(t,e,n){return u.call(a,t,e,n)},this.strict=i;var f=this._modules.root.state;p(this,f,[],this._modules.root),h(this,f),o.forEach(function(t){return t(n)}),(void 0!==e.devtools?e.devtools:r.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",function(t){e.replaceState(t)}),e.subscribe(function(e,n){t.emit("vuex:mutation",e,n)},{prepend:!0}),e.subscribeAction(function(e,n){t.emit("vuex:action",e,n)},{prepend:!0}))}(this)},c={state:{configurable:!0}};function u(t,e,n){return e.indexOf(t)<0&&(n&&n.prepend?e.unshift(t):e.push(t)),function(){var n=e.indexOf(t);n>-1&&e.splice(n,1)}}function f(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);var n=t.state;p(t,n,[],t._modules.root,!0),h(t,n,e)}function h(t,n,o){var i=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);var s=t._wrappedGetters,a={};e(s,function(e,n){a[n]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,n,{get:function(){return t._vm[n]},enumerable:!0})});var c=r.config.silent;r.config.silent=!0,t._vm=new r({data:{$$state:n},computed:a}),r.config.silent=c,t.strict&&function(t){t._vm.$watch(function(){return this._data.$$state},function(){},{deep:!0,sync:!0})}(t),i&&(o&&t._withCommit(function(){i._data.$$state=null}),r.nextTick(function(){return i.$destroy()}))}function p(t,e,n,o,i){var s=!n.length,a=t._modules.getNamespace(n);if(o.namespaced&&(t._modulesNamespaceMap[a],t._modulesNamespaceMap[a]=o),!s&&!i){var c=l(e,n.slice(0,-1)),u=n[n.length-1];t._withCommit(function(){r.set(c,u,o.state)})}var f=o.context=function(t,e,n){var o=""===e,i={dispatch:o?t.dispatch:function(n,o,i){var r=d(n,o,i),s=r.payload,a=r.options,c=r.type;return a&&a.root||(c=e+c),t.dispatch(c,s)},commit:o?t.commit:function(n,o,i){var r=d(n,o,i),s=r.payload,a=r.options,c=r.type;a&&a.root||(c=e+c),t.commit(c,s,a)}};return Object.defineProperties(i,{getters:{get:o?function(){return t.getters}:function(){return function(t,e){if(!t._makeLocalGettersCache[e]){var n={},o=e.length;Object.keys(t.getters).forEach(function(i){if(i.slice(0,o)===e){var r=i.slice(o);Object.defineProperty(n,r,{get:function(){return t.getters[i]},enumerable:!0})}}),t._makeLocalGettersCache[e]=n}return t._makeLocalGettersCache[e]}(t,e)}},state:{get:function(){return l(t.state,n)}}}),i}(t,a,n);o.forEachMutation(function(e,n){!function(t,e,n,o){(t._mutations[e]||(t._mutations[e]=[])).push(function(e){n.call(t,o.state,e)})}(t,a+n,e,f)}),o.forEachAction(function(e,n){var o=e.root?n:a+n,i=e.handler||e;!function(t,e,n,o){(t._actions[e]||(t._actions[e]=[])).push(function(e){var i,r=n.call(t,{dispatch:o.dispatch,commit:o.commit,getters:o.getters,state:o.state,rootGetters:t.getters,rootState:t.state},e);return(i=r)&&"function"==typeof i.then||(r=Promise.resolve(r)),t._devtoolHook?r.catch(function(e){throw t._devtoolHook.emit("vuex:error",e),e}):r})}(t,o,i,f)}),o.forEachGetter(function(e,n){!function(t,e,n,o){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return n(o.state,o.getters,t.state,t.getters)}}(t,a+n,e,f)}),o.forEachChild(function(o,r){p(t,e,n.concat(r),o,i)})}function l(t,e){return e.reduce(function(t,e){return t[e]},t)}function d(t,e,o){return n(t)&&t.type&&(o=e,e=t,t=t.type),{type:t,payload:e,options:o}}function m(t){r&&t===r||function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:n});else{var e=t.prototype._init;t.prototype._init=function(t){void 0===t&&(t={}),t.init=t.init?[n].concat(t.init):n,e.call(this,t)}}function n(){var t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(r=t)}c.state.get=function(){return this._vm._data.$$state},c.state.set=function(t){},a.prototype.commit=function(t,e,n){var o=this,i=d(t,e,n),r=i.type,s=i.payload,a={type:r,payload:s},c=this._mutations[r];c&&(this._withCommit(function(){c.forEach(function(t){t(s)})}),this._subscribers.slice().forEach(function(t){return t(a,o.state)}))},a.prototype.dispatch=function(t,e){var n=this,o=d(t,e),i=o.type,r=o.payload,s={type:i,payload:r},a=this._actions[i];if(a){try{this._actionSubscribers.slice().filter(function(t){return t.before}).forEach(function(t){return t.before(s,n.state)})}catch(t){}return(a.length>1?Promise.all(a.map(function(t){return t(r)})):a[0](r)).then(function(t){try{n._actionSubscribers.filter(function(t){return t.after}).forEach(function(t){return t.after(s,n.state)})}catch(t){}return t})}},a.prototype.subscribe=function(t,e){return u(t,this._subscribers,e)},a.prototype.subscribeAction=function(t,e){return u("function"==typeof t?{before:t}:t,this._actionSubscribers,e)},a.prototype.watch=function(t,e,n){var o=this;return this._watcherVM.$watch(function(){return t(o.state,o.getters)},e,n)},a.prototype.replaceState=function(t){var e=this;this._withCommit(function(){e._vm._data.$$state=t})},a.prototype.registerModule=function(t,e,n){void 0===n&&(n={}),"string"==typeof t&&(t=[t]),this._modules.register(t,e),p(this,this.state,t,this._modules.get(t),n.preserveState),h(this,this.state)},a.prototype.unregisterModule=function(t){var e=this;"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit(function(){var n=l(e.state,t.slice(0,-1));r.delete(n,t[t.length-1])}),f(this)},a.prototype.hasModule=function(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)},a.prototype.hotUpdate=function(t){this._modules.update(t),f(this,!0)},a.prototype._withCommit=function(t){var e=this._committing;this._committing=!0,t(),this._committing=e},Object.defineProperties(a.prototype,c);var v=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;n[o]=function(){var e=this.$store.state,n=this.$store.getters;if(t){var o=$(this.$store,"mapState",t);if(!o)return;e=o.context.state,n=o.context.getters}return"function"==typeof i?i.call(this,e,n):e[i]},n[o].vuex=!0}),n}),_=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.commit;if(t){var r=$(this.$store,"mapMutations",t);if(!r)return;o=r.context.commit}return"function"==typeof i?i.apply(this,[o].concat(e)):o.apply(this.$store,[i].concat(e))}}),n}),y=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;i=t+i,n[o]=function(){if(!t||$(this.$store,"mapGetters",t))return this.$store.getters[i]},n[o].vuex=!0}),n}),g=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.dispatch;if(t){var r=$(this.$store,"mapActions",t);if(!r)return;o=r.context.dispatch}return"function"==typeof i?i.apply(this,[o].concat(e)):o.apply(this.$store,[i].concat(e))}}),n});function b(t){return function(t){return Array.isArray(t)||n(t)}(t)?Array.isArray(t)?t.map(function(t){return{key:t,val:t}}):Object.keys(t).map(function(e){return{key:e,val:t[e]}}):[]}function w(t){return function(e,n){return"string"!=typeof e?(n=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,n)}}function $(t,e,n){return t._modulesNamespaceMap[n]}return{Store:a,install:m,version:"3.3.0",mapState:v,mapMutations:_,mapGetters:y,mapActions:g,createNamespacedHelpers:function(t){return{mapState:v.bind(null,t),mapGetters:y.bind(null,t),mapMutations:_.bind(null,t),mapActions:g.bind(null,t)}}}}); \ No newline at end of file From 151e4e231d57eb9a661aa2f788c930f220fea955 Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Mon, 4 May 2020 20:21:48 -0400 Subject: [PATCH 7/8] Recommit dev dist. --- dist/logger.d.ts | 17 + dist/logger.js | 150 +++++ dist/vuex.common.js | 1079 +++++++++++++++++++++++++++++++++ dist/vuex.esm.browser.js | 1037 ++++++++++++++++++++++++++++++++ dist/vuex.esm.browser.min.js | 6 + dist/vuex.esm.js | 1078 +++++++++++++++++++++++++++++++++ dist/vuex.js | 1084 ++++++++++++++++++++++++++++++++++ dist/vuex.min.js | 6 + 8 files changed, 4457 insertions(+) create mode 100644 dist/logger.d.ts create mode 100644 dist/logger.js create mode 100644 dist/vuex.common.js create mode 100644 dist/vuex.esm.browser.js create mode 100644 dist/vuex.esm.browser.min.js create mode 100644 dist/vuex.esm.js create mode 100644 dist/vuex.js create mode 100644 dist/vuex.min.js diff --git a/dist/logger.d.ts b/dist/logger.d.ts new file mode 100644 index 000000000..8ee43089c --- /dev/null +++ b/dist/logger.d.ts @@ -0,0 +1,17 @@ +// Types for the logger plugin. This file must be put alongside the bundled +// JavaScript file of the logger. + +import { Payload, Plugin } from "../types/index"; + +export interface LoggerOption { + collapsed?: boolean; + filter?:

(mutation: P, stateBefore: S, stateAfter: S) => boolean; + transformer?: (state: S) => any; + mutationTransformer?:

(mutation: P) => any; + actionFilter?:

(action: P, state: S) => boolean; + actionTransformer?:

(action: P) => any; + logMutations?: boolean; + logActions?: boolean; +} + +export default function createLogger(option?: LoggerOption): Plugin; diff --git a/dist/logger.js b/dist/logger.js new file mode 100644 index 000000000..cdcde6763 --- /dev/null +++ b/dist/logger.js @@ -0,0 +1,150 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.createVuexLogger = factory()); +}(this, function () { 'use strict'; + + /** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + function find (list, f) { + return list.filter(f)[0] + } + + /** + * Deep copy the given object considering circular structure. + * This function caches all nested objects and its copies. + * If it detects circular structure, use cached copy to avoid infinite loop. + * + * @param {*} obj + * @param {Array} cache + * @return {*} + */ + function deepCopy (obj, cache) { + if ( cache === void 0 ) cache = []; + + // just return if obj is immutable value + if (obj === null || typeof obj !== 'object') { + return obj + } + + // if obj is hit, it is in circular structure + var hit = find(cache, function (c) { return c.original === obj; }); + if (hit) { + return hit.copy + } + + var copy = Array.isArray(obj) ? [] : {}; + // put the copy into cache at first + // because we want to refer it in recursive deepCopy + cache.push({ + original: obj, + copy: copy + }); + + Object.keys(obj).forEach(function (key) { + copy[key] = deepCopy(obj[key], cache); + }); + + return copy + } + + // Credits: borrowed code from fcomb/redux-logger + + function createLogger (ref) { + if ( ref === void 0 ) ref = {}; + var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true; + var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; }; + var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; }; + var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; }; + var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; }; + var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; }; + var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true; + var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true; + var logger = ref.logger; if ( logger === void 0 ) logger = console; + + return function (store) { + var prevState = deepCopy(store.state); + + if (typeof logger === 'undefined') { + return + } + + if (logMutations) { + store.subscribe(function (mutation, state) { + var nextState = deepCopy(state); + + if (filter(mutation, prevState, nextState)) { + var formattedTime = getFormattedTime(); + var formattedMutation = mutationTransformer(mutation); + var message = "mutation " + (mutation.type) + formattedTime; + + startMessage(logger, message, collapsed); + logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState)); + logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation); + logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState)); + endMessage(logger); + } + + prevState = nextState; + }); + } + + if (logActions) { + store.subscribeAction(function (action, state) { + if (actionFilter(action, state)) { + var formattedTime = getFormattedTime(); + var formattedAction = actionTransformer(action); + var message = "action " + (action.type) + formattedTime; + + startMessage(logger, message, collapsed); + logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction); + endMessage(logger); + } + }); + } + } + } + + function startMessage (logger, message, collapsed) { + var startMessage = collapsed + ? logger.groupCollapsed + : logger.group; + + // render + try { + startMessage.call(logger, message); + } catch (e) { + logger.log(message); + } + } + + function endMessage (logger) { + try { + logger.groupEnd(); + } catch (e) { + logger.log('—— log end ——'); + } + } + + function getFormattedTime () { + var time = new Date(); + return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3))) + } + + function repeat (str, times) { + return (new Array(times + 1)).join(str) + } + + function pad (num, maxLength) { + return repeat('0', maxLength - num.toString().length) + num + } + + return createLogger; + +})); diff --git a/dist/vuex.common.js b/dist/vuex.common.js new file mode 100644 index 000000000..66df3178c --- /dev/null +++ b/dist/vuex.common.js @@ -0,0 +1,1079 @@ +/** + * vuex v3.3.0 + * (c) 2020 Evan You + * @license MIT + */ +'use strict'; + +function applyMixin (Vue) { + var version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + var _init = Vue.prototype._init; + Vue.prototype._init = function (options) { + if ( options === void 0 ) options = {}; + + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + var options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } +} + +var target = typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}; +var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; + +function devtoolPlugin (store) { + if (!devtoolHook) { return } + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', function (targetState) { + store.replaceState(targetState); + }); + + store.subscribe(function (mutation, state) { + devtoolHook.emit('vuex:mutation', mutation, state); + }, { prepend: true }); + + store.subscribeAction(function (action, state) { + devtoolHook.emit('vuex:action', action, state); + }, { prepend: true }); +} + +/** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + +/** + * forEach for object + */ +function forEachValue (obj, fn) { + Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); +} + +function isObject (obj) { + return obj !== null && typeof obj === 'object' +} + +function isPromise (val) { + return val && typeof val.then === 'function' +} + +function assert (condition, msg) { + if (!condition) { throw new Error(("[vuex] " + msg)) } +} + +function partial (fn, arg) { + return function () { + return fn(arg) + } +} + +// Base data struct for store's module, package with some attribute and method +var Module = function Module (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + var rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; +}; + +var prototypeAccessors = { namespaced: { configurable: true } }; + +prototypeAccessors.namespaced.get = function () { + return !!this._rawModule.namespaced +}; + +Module.prototype.addChild = function addChild (key, module) { + this._children[key] = module; +}; + +Module.prototype.removeChild = function removeChild (key) { + delete this._children[key]; +}; + +Module.prototype.getChild = function getChild (key) { + return this._children[key] +}; + +Module.prototype.hasChild = function hasChild (key) { + return key in this._children +}; + +Module.prototype.update = function update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } +}; + +Module.prototype.forEachChild = function forEachChild (fn) { + forEachValue(this._children, fn); +}; + +Module.prototype.forEachGetter = function forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } +}; + +Module.prototype.forEachAction = function forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } +}; + +Module.prototype.forEachMutation = function forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } +}; + +Object.defineProperties( Module.prototype, prototypeAccessors ); + +var ModuleCollection = function ModuleCollection (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); +}; + +ModuleCollection.prototype.get = function get (path) { + return path.reduce(function (module, key) { + return module.getChild(key) + }, this.root) +}; + +ModuleCollection.prototype.getNamespace = function getNamespace (path) { + var module = this.root; + return path.reduce(function (namespace, key) { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') +}; + +ModuleCollection.prototype.update = function update$1 (rawRootModule) { + update([], this.root, rawRootModule); +}; + +ModuleCollection.prototype.register = function register (path, rawModule, runtime) { + var this$1 = this; + if ( runtime === void 0 ) runtime = true; + + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, rawModule); + } + + var newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + var parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, function (rawChildModule, key) { + this$1.register(path.concat(key), rawChildModule, runtime); + }); + } +}; + +ModuleCollection.prototype.unregister = function unregister (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + if (!parent.getChild(key).runtime) { return } + + parent.removeChild(key); +}; + +ModuleCollection.prototype.isRegistered = function isRegistered (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + + return parent.hasChild(key) +}; + +function update (path, targetModule, newModule) { + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (var key in newModule.modules) { + if (!targetModule.getChild(key)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + "[vuex] trying to add a new module '" + key + "' on hot reloading, " + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } +} + +var functionAssert = { + assert: function (value) { return typeof value === 'function'; }, + expected: 'function' +}; + +var objectAssert = { + assert: function (value) { return typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'); }, + expected: 'function or object with "handler" function' +}; + +var assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert +}; + +function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(function (key) { + if (!rawModule[key]) { return } + + var assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], function (value, type) { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); +} + +function makeAssertionMessage (path, key, type, value, expected) { + var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; + if (path.length > 0) { + buf += " in module \"" + (path.join('.')) + "\""; + } + buf += " is " + (JSON.stringify(value)) + "."; + return buf +} + +var Vue; // bind on install + +var Store = function Store (options) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + if (process.env.NODE_ENV !== 'production') { + assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); + assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); + assert(this instanceof Store, "store must be called with the new operator."); + } + + var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; + var strict = options.strict; if ( strict === void 0 ) strict = false; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + this._makeLocalGettersCache = Object.create(null); + + // bind commit and dispatch to self + var store = this; + var ref = this; + var dispatch = ref.dispatch; + var commit = ref.commit; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + var state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(function (plugin) { return plugin(this$1); }); + + var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } +}; + +var prototypeAccessors$1 = { state: { configurable: true } }; + +prototypeAccessors$1.state.get = function () { + return this._vm._data.$$state +}; + +prototypeAccessors$1.state.set = function (v) { + if (process.env.NODE_ENV !== 'production') { + assert(false, "use store.replaceState() to explicit replace store state."); + } +}; + +Store.prototype.commit = function commit (_type, _payload, _options) { + var this$1 = this; + + // check object-style commit + var ref = unifyObjectStyle(_type, _payload, _options); + var type = ref.type; + var payload = ref.payload; + var options = ref.options; + + var mutation = { type: type, payload: payload }; + var entry = this._mutations[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown mutation type: " + type)); + } + return + } + this._withCommit(function () { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + + this._subscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .forEach(function (sub) { return sub(mutation, this$1.state); }); + + if ( + process.env.NODE_ENV !== 'production' && + options && options.silent + ) { + console.warn( + "[vuex] mutation type: " + type + ". Silent option has been removed. " + + 'Use the filter functionality in the vue-devtools' + ); + } +}; + +Store.prototype.dispatch = function dispatch (_type, _payload) { + var this$1 = this; + + // check object-style dispatch + var ref = unifyObjectStyle(_type, _payload); + var type = ref.type; + var payload = ref.payload; + + var action = { type: type, payload: payload }; + var entry = this._actions[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown action type: " + type)); + } + return + } + + try { + this._actionSubscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .filter(function (sub) { return sub.before; }) + .forEach(function (sub) { return sub.before(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in before action subscribers: "); + console.error(e); + } + } + + var result = entry.length > 1 + ? Promise.all(entry.map(function (handler) { return handler(payload); })) + : entry[0](payload); + + return result.then(function (res) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.after; }) + .forEach(function (sub) { return sub.after(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in after action subscribers: "); + console.error(e); + } + } + return res + }) +}; + +Store.prototype.subscribe = function subscribe (fn, options) { + return genericSubscribe(fn, this._subscribers, options) +}; + +Store.prototype.subscribeAction = function subscribeAction (fn, options) { + var subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers, options) +}; + +Store.prototype.watch = function watch (getter, cb, options) { + var this$1 = this; + + if (process.env.NODE_ENV !== 'production') { + assert(typeof getter === 'function', "store.watch only accepts a function."); + } + return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) +}; + +Store.prototype.replaceState = function replaceState (state) { + var this$1 = this; + + this._withCommit(function () { + this$1._vm._data.$$state = state; + }); +}; + +Store.prototype.registerModule = function registerModule (path, rawModule, options) { + if ( options === void 0 ) options = {}; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); +}; + +Store.prototype.unregisterModule = function unregisterModule (path) { + var this$1 = this; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + this._modules.unregister(path); + this._withCommit(function () { + var parentState = getNestedState(this$1.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); +}; + +Store.prototype.hasModule = function hasModule (path) { + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + return this._modules.isRegistered(path) +}; + +Store.prototype.hotUpdate = function hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); +}; + +Store.prototype._withCommit = function _withCommit (fn) { + var committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; +}; + +Object.defineProperties( Store.prototype, prototypeAccessors$1 ); + +function genericSubscribe (fn, subs, options) { + if (subs.indexOf(fn) < 0) { + options && options.prepend + ? subs.unshift(fn) + : subs.push(fn); + } + return function () { + var i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } +} + +function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + var state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); +} + +function resetStoreVM (store, state, hot) { + var oldVm = store._vm; + + // bind store public getters + store.getters = {}; + // reset local getters cache + store._makeLocalGettersCache = Object.create(null); + var wrappedGetters = store._wrappedGetters; + var computed = {}; + forEachValue(wrappedGetters, function (fn, key) { + // use computed to leverage its lazy-caching mechanism + // direct inline function use will lead to closure preserving oldVm. + // using partial to return function with only arguments preserved in closure environment. + computed[key] = partial(fn, store); + Object.defineProperty(store.getters, key, { + get: function () { return store._vm[key]; }, + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + var silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed: computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(function () { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(function () { return oldVm.$destroy(); }); + } +} + +function installModule (store, rootState, path, module, hot) { + var isRoot = !path.length; + var namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + if (store._modulesNamespaceMap[namespace] && process.env.NODE_ENV !== 'production') { + console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); + } + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + var parentState = getNestedState(rootState, path.slice(0, -1)); + var moduleName = path[path.length - 1]; + store._withCommit(function () { + if (process.env.NODE_ENV !== 'production') { + if (moduleName in parentState) { + console.warn( + ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") + ); + } + } + Vue.set(parentState, moduleName, module.state); + }); + } + + var local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation(function (mutation, key) { + var namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction(function (action, key) { + var type = action.root ? key : namespace + key; + var handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter(function (getter, key) { + var namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild(function (child, key) { + installModule(store, rootState, path.concat(key), child, hot); + }); +} + +/** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ +function makeLocalContext (store, namespace, path) { + var noNamespace = namespace === ''; + + var local = { + dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { + console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { + console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? function () { return store.getters; } + : function () { return makeLocalGetters(store, namespace); } + }, + state: { + get: function () { return getNestedState(store.state, path); } + } + }); + + return local +} + +function makeLocalGetters (store, namespace) { + if (!store._makeLocalGettersCache[namespace]) { + var gettersProxy = {}; + var splitPos = namespace.length; + Object.keys(store.getters).forEach(function (type) { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) { return } + + // extract local getter type + var localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: function () { return store.getters[type]; }, + enumerable: true + }); + }); + store._makeLocalGettersCache[namespace] = gettersProxy; + } + + return store._makeLocalGettersCache[namespace] +} + +function registerMutation (store, type, handler, local) { + var entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); +} + +function registerAction (store, type, handler, local) { + var entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload) { + var res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(function (err) { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); +} + +function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] duplicate getter key: " + type)); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; +} + +function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, function () { + if (process.env.NODE_ENV !== 'production') { + assert(store._committing, "do not mutate vuex store state outside mutation handlers."); + } + }, { deep: true, sync: true }); +} + +function getNestedState (state, path) { + return path.reduce(function (state, key) { return state[key]; }, state) +} + +function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + if (process.env.NODE_ENV !== 'production') { + assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); + } + + return { type: type, payload: payload, options: options } +} + +function install (_Vue) { + if (Vue && _Vue === Vue) { + if (process.env.NODE_ENV !== 'production') { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); +} + +/** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ +var mapState = normalizeNamespace(function (namespace, states) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(states)) { + console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); + } + normalizeMap(states).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedState () { + var state = this.$store.state; + var getters = this.$store.getters; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapMutations = normalizeNamespace(function (namespace, mutations) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(mutations)) { + console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); + } + normalizeMap(mutations).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedMutation () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // Get the commit method from store + var commit = this.$store.commit; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ +var mapGetters = normalizeNamespace(function (namespace, getters) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(getters)) { + console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); + } + normalizeMap(getters).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { + console.error(("[vuex] unknown getter: " + val)); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapActions = normalizeNamespace(function (namespace, actions) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(actions)) { + console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); + } + normalizeMap(actions).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // get dispatch function from store + var dispatch = this.$store.dispatch; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ +var createNamespacedHelpers = function (namespace) { return ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) +}); }; + +/** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ +function normalizeMap (map) { + if (!isValidMap(map)) { + return [] + } + return Array.isArray(map) + ? map.map(function (key) { return ({ key: key, val: key }); }) + : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) +} + +/** + * Validate whether given map is valid or not + * @param {*} map + * @return {Boolean} + */ +function isValidMap (map) { + return Array.isArray(map) || isObject(map) +} + +/** + * 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. + * @param {Function} fn + * @return {Function} + */ +function normalizeNamespace (fn) { + return function (namespace, map) { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } +} + +/** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ +function getModuleByNamespace (store, helper, namespace) { + var module = store._modulesNamespaceMap[namespace]; + if (process.env.NODE_ENV !== 'production' && !module) { + console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); + } + return module +} + +var index = { + Store: Store, + install: install, + version: '3.3.0', + mapState: mapState, + mapMutations: mapMutations, + mapGetters: mapGetters, + mapActions: mapActions, + createNamespacedHelpers: createNamespacedHelpers +}; + +module.exports = index; diff --git a/dist/vuex.esm.browser.js b/dist/vuex.esm.browser.js new file mode 100644 index 000000000..17fece11f --- /dev/null +++ b/dist/vuex.esm.browser.js @@ -0,0 +1,1037 @@ +/** + * vuex v3.3.0 + * (c) 2020 Evan You + * @license MIT + */ +function applyMixin (Vue) { + const version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + const _init = Vue.prototype._init; + Vue.prototype._init = function (options = {}) { + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + const options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } +} + +const target = typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}; +const devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; + +function devtoolPlugin (store) { + if (!devtoolHook) return + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', targetState => { + store.replaceState(targetState); + }); + + store.subscribe((mutation, state) => { + devtoolHook.emit('vuex:mutation', mutation, state); + }, { prepend: true }); + + store.subscribeAction((action, state) => { + devtoolHook.emit('vuex:action', action, state); + }, { prepend: true }); +} + +/** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + +/** + * forEach for object + */ +function forEachValue (obj, fn) { + Object.keys(obj).forEach(key => fn(obj[key], key)); +} + +function isObject (obj) { + return obj !== null && typeof obj === 'object' +} + +function isPromise (val) { + return val && typeof val.then === 'function' +} + +function assert (condition, msg) { + if (!condition) throw new Error(`[vuex] ${msg}`) +} + +function partial (fn, arg) { + return function () { + return fn(arg) + } +} + +// Base data struct for store's module, package with some attribute and method +class Module { + constructor (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + const rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; + } + + get namespaced () { + return !!this._rawModule.namespaced + } + + addChild (key, module) { + this._children[key] = module; + } + + removeChild (key) { + delete this._children[key]; + } + + getChild (key) { + return this._children[key] + } + + hasChild (key) { + return key in this._children + } + + update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } + } + + forEachChild (fn) { + forEachValue(this._children, fn); + } + + forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } + } + + forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } + } + + forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } + } +} + +class ModuleCollection { + constructor (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); + } + + get (path) { + return path.reduce((module, key) => { + return module.getChild(key) + }, this.root) + } + + getNamespace (path) { + let module = this.root; + return path.reduce((namespace, key) => { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') + } + + update (rawRootModule) { + update([], this.root, rawRootModule); + } + + register (path, rawModule, runtime = true) { + { + assertRawModule(path, rawModule); + } + + const newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + const parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, (rawChildModule, key) => { + this.register(path.concat(key), rawChildModule, runtime); + }); + } + } + + unregister (path) { + const parent = this.get(path.slice(0, -1)); + const key = path[path.length - 1]; + if (!parent.getChild(key).runtime) return + + parent.removeChild(key); + } + + isRegistered (path) { + const parent = this.get(path.slice(0, -1)); + const key = path[path.length - 1]; + + return parent.hasChild(key) + } +} + +function update (path, targetModule, newModule) { + { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (const key in newModule.modules) { + if (!targetModule.getChild(key)) { + { + console.warn( + `[vuex] trying to add a new module '${key}' on hot reloading, ` + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } +} + +const functionAssert = { + assert: value => typeof value === 'function', + expected: 'function' +}; + +const objectAssert = { + assert: value => typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'), + expected: 'function or object with "handler" function' +}; + +const assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert +}; + +function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(key => { + if (!rawModule[key]) return + + const assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], (value, type) => { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); +} + +function makeAssertionMessage (path, key, type, value, expected) { + let buf = `${key} should be ${expected} but "${key}.${type}"`; + if (path.length > 0) { + buf += ` in module "${path.join('.')}"`; + } + buf += ` is ${JSON.stringify(value)}.`; + return buf +} + +let Vue; // bind on install + +class Store { + constructor (options = {}) { + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + { + assert(Vue, `must call Vue.use(Vuex) before creating a store instance.`); + assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`); + assert(this instanceof Store, `store must be called with the new operator.`); + } + + const { + plugins = [], + strict = false + } = options; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + this._makeLocalGettersCache = Object.create(null); + + // bind commit and dispatch to self + const store = this; + const { dispatch, commit } = this; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + const state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(plugin => plugin(this)); + + const useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } + } + + get state () { + return this._vm._data.$$state + } + + set state (v) { + { + assert(false, `use store.replaceState() to explicit replace store state.`); + } + } + + commit (_type, _payload, _options) { + // check object-style commit + const { + type, + payload, + options + } = unifyObjectStyle(_type, _payload, _options); + + const mutation = { type, payload }; + const entry = this._mutations[type]; + if (!entry) { + { + console.error(`[vuex] unknown mutation type: ${type}`); + } + return + } + this._withCommit(() => { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + + this._subscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .forEach(sub => sub(mutation, this.state)); + + if ( + options && options.silent + ) { + console.warn( + `[vuex] mutation type: ${type}. Silent option has been removed. ` + + 'Use the filter functionality in the vue-devtools' + ); + } + } + + dispatch (_type, _payload) { + // check object-style dispatch + const { + type, + payload + } = unifyObjectStyle(_type, _payload); + + const action = { type, payload }; + const entry = this._actions[type]; + if (!entry) { + { + console.error(`[vuex] unknown action type: ${type}`); + } + return + } + + try { + this._actionSubscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .filter(sub => sub.before) + .forEach(sub => sub.before(action, this.state)); + } catch (e) { + { + console.warn(`[vuex] error in before action subscribers: `); + console.error(e); + } + } + + const result = entry.length > 1 + ? Promise.all(entry.map(handler => handler(payload))) + : entry[0](payload); + + return result.then(res => { + try { + this._actionSubscribers + .filter(sub => sub.after) + .forEach(sub => sub.after(action, this.state)); + } catch (e) { + { + console.warn(`[vuex] error in after action subscribers: `); + console.error(e); + } + } + return res + }) + } + + subscribe (fn, options) { + return genericSubscribe(fn, this._subscribers, options) + } + + subscribeAction (fn, options) { + const subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers, options) + } + + watch (getter, cb, options) { + { + assert(typeof getter === 'function', `store.watch only accepts a function.`); + } + return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options) + } + + replaceState (state) { + this._withCommit(() => { + this._vm._data.$$state = state; + }); + } + + registerModule (path, rawModule, options = {}) { + if (typeof path === 'string') path = [path]; + + { + assert(Array.isArray(path), `module path must be a string or an Array.`); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); + } + + unregisterModule (path) { + if (typeof path === 'string') path = [path]; + + { + assert(Array.isArray(path), `module path must be a string or an Array.`); + } + + this._modules.unregister(path); + this._withCommit(() => { + const parentState = getNestedState(this.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); + } + + hasModule (path) { + if (typeof path === 'string') path = [path]; + + { + assert(Array.isArray(path), `module path must be a string or an Array.`); + } + + return this._modules.isRegistered(path) + } + + hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); + } + + _withCommit (fn) { + const committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; + } +} + +function genericSubscribe (fn, subs, options) { + if (subs.indexOf(fn) < 0) { + options && options.prepend + ? subs.unshift(fn) + : subs.push(fn); + } + return () => { + const i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } +} + +function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + const state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); +} + +function resetStoreVM (store, state, hot) { + const oldVm = store._vm; + + // bind store public getters + store.getters = {}; + // reset local getters cache + store._makeLocalGettersCache = Object.create(null); + const wrappedGetters = store._wrappedGetters; + const computed = {}; + forEachValue(wrappedGetters, (fn, key) => { + // use computed to leverage its lazy-caching mechanism + // direct inline function use will lead to closure preserving oldVm. + // using partial to return function with only arguments preserved in closure environment. + computed[key] = partial(fn, store); + Object.defineProperty(store.getters, key, { + get: () => store._vm[key], + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + const silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(() => { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(() => oldVm.$destroy()); + } +} + +function installModule (store, rootState, path, module, hot) { + const isRoot = !path.length; + const namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + if (store._modulesNamespaceMap[namespace] && "development" !== 'production') { + console.error(`[vuex] duplicate namespace ${namespace} for the namespaced module ${path.join('/')}`); + } + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + const parentState = getNestedState(rootState, path.slice(0, -1)); + const moduleName = path[path.length - 1]; + store._withCommit(() => { + { + if (moduleName in parentState) { + console.warn( + `[vuex] state field "${moduleName}" was overridden by a module with the same name at "${path.join('.')}"` + ); + } + } + Vue.set(parentState, moduleName, module.state); + }); + } + + const local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation((mutation, key) => { + const namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction((action, key) => { + const type = action.root ? key : namespace + key; + const handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter((getter, key) => { + const namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild((child, key) => { + installModule(store, rootState, path.concat(key), child, hot); + }); +} + +/** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ +function makeLocalContext (store, namespace, path) { + const noNamespace = namespace === ''; + + const local = { + dispatch: noNamespace ? store.dispatch : (_type, _payload, _options) => { + const args = unifyObjectStyle(_type, _payload, _options); + const { payload, options } = args; + let { type } = args; + + if (!options || !options.root) { + type = namespace + type; + if (!store._actions[type]) { + console.error(`[vuex] unknown local action type: ${args.type}, global type: ${type}`); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : (_type, _payload, _options) => { + const args = unifyObjectStyle(_type, _payload, _options); + const { payload, options } = args; + let { type } = args; + + if (!options || !options.root) { + type = namespace + type; + if (!store._mutations[type]) { + console.error(`[vuex] unknown local mutation type: ${args.type}, global type: ${type}`); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? () => store.getters + : () => makeLocalGetters(store, namespace) + }, + state: { + get: () => getNestedState(store.state, path) + } + }); + + return local +} + +function makeLocalGetters (store, namespace) { + if (!store._makeLocalGettersCache[namespace]) { + const gettersProxy = {}; + const splitPos = namespace.length; + Object.keys(store.getters).forEach(type => { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) return + + // extract local getter type + const localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: () => store.getters[type], + enumerable: true + }); + }); + store._makeLocalGettersCache[namespace] = gettersProxy; + } + + return store._makeLocalGettersCache[namespace] +} + +function registerMutation (store, type, handler, local) { + const entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); +} + +function registerAction (store, type, handler, local) { + const entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload) { + let res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(err => { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); +} + +function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + { + console.error(`[vuex] duplicate getter key: ${type}`); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; +} + +function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, () => { + { + assert(store._committing, `do not mutate vuex store state outside mutation handlers.`); + } + }, { deep: true, sync: true }); +} + +function getNestedState (state, path) { + return path.reduce((state, key) => state[key], state) +} + +function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + { + assert(typeof type === 'string', `expects string as the type, but found ${typeof type}.`); + } + + return { type, payload, options } +} + +function install (_Vue) { + if (Vue && _Vue === Vue) { + { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); +} + +/** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ +const mapState = normalizeNamespace((namespace, states) => { + const res = {}; + if (!isValidMap(states)) { + console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); + } + normalizeMap(states).forEach(({ key, val }) => { + res[key] = function mappedState () { + let state = this.$store.state; + let getters = this.$store.getters; + if (namespace) { + const module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +const mapMutations = normalizeNamespace((namespace, mutations) => { + const res = {}; + if (!isValidMap(mutations)) { + console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); + } + normalizeMap(mutations).forEach(({ key, val }) => { + res[key] = function mappedMutation (...args) { + // Get the commit method from store + let commit = this.$store.commit; + if (namespace) { + const module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ +const mapGetters = normalizeNamespace((namespace, getters) => { + const res = {}; + if (!isValidMap(getters)) { + console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); + } + normalizeMap(getters).forEach(({ key, val }) => { + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (!(val in this.$store.getters)) { + console.error(`[vuex] unknown getter: ${val}`); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +const mapActions = normalizeNamespace((namespace, actions) => { + const res = {}; + if (!isValidMap(actions)) { + console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); + } + normalizeMap(actions).forEach(({ key, val }) => { + res[key] = function mappedAction (...args) { + // get dispatch function from store + let dispatch = this.$store.dispatch; + if (namespace) { + const module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ +const createNamespacedHelpers = (namespace) => ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) +}); + +/** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ +function normalizeMap (map) { + if (!isValidMap(map)) { + return [] + } + return Array.isArray(map) + ? map.map(key => ({ key, val: key })) + : Object.keys(map).map(key => ({ key, val: map[key] })) +} + +/** + * Validate whether given map is valid or not + * @param {*} map + * @return {Boolean} + */ +function isValidMap (map) { + return Array.isArray(map) || isObject(map) +} + +/** + * 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. + * @param {Function} fn + * @return {Function} + */ +function normalizeNamespace (fn) { + return (namespace, map) => { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } +} + +/** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ +function getModuleByNamespace (store, helper, namespace) { + const module = store._modulesNamespaceMap[namespace]; + if (!module) { + console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`); + } + return module +} + +var index_esm = { + Store, + install, + version: '3.3.0', + mapState, + mapMutations, + mapGetters, + mapActions, + createNamespacedHelpers +}; + +export default index_esm; +export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers }; diff --git a/dist/vuex.esm.browser.min.js b/dist/vuex.esm.browser.min.js new file mode 100644 index 000000000..3952019a0 --- /dev/null +++ b/dist/vuex.esm.browser.min.js @@ -0,0 +1,6 @@ +/** + * vuex v3.3.0 + * (c) 2020 Evan You + * @license MIT + */ +const t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,e){Object.keys(t).forEach(s=>e(t[s],s))}function s(t){return null!==t&&"object"==typeof t}class i{constructor(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;const s=t.state;this.state=("function"==typeof s?s():s)||{}}get namespaced(){return!!this._rawModule.namespaced}addChild(t,e){this._children[t]=e}removeChild(t){delete this._children[t]}getChild(t){return this._children[t]}hasChild(t){return t in this._children}update(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)}forEachChild(t){e(this._children,t)}forEachGetter(t){this._rawModule.getters&&e(this._rawModule.getters,t)}forEachAction(t){this._rawModule.actions&&e(this._rawModule.actions,t)}forEachMutation(t){this._rawModule.mutations&&e(this._rawModule.mutations,t)}}class o{constructor(t){this.register([],t,!1)}get(t){return t.reduce((t,e)=>t.getChild(e),this.root)}getNamespace(t){let e=this.root;return t.reduce((t,s)=>t+((e=e.getChild(s)).namespaced?s+"/":""),"")}update(t){!function t(e,s,i){s.update(i);if(i.modules)for(const o in i.modules){if(!s.getChild(o))return;t(e.concat(o),s.getChild(o),i.modules[o])}}([],this.root,t)}register(t,s,o=!0){const n=new i(s,o);if(0===t.length)this.root=n;else{this.get(t.slice(0,-1)).addChild(t[t.length-1],n)}s.modules&&e(s.modules,(e,s)=>{this.register(t.concat(s),e,o)})}unregister(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1];e.getChild(s).runtime&&e.removeChild(s)}isRegistered(t){const e=this.get(t.slice(0,-1)),s=t[t.length-1];return e.hasChild(s)}}let n;class r{constructor(e={}){!n&&"undefined"!=typeof window&&window.Vue&&p(window.Vue);const{plugins:s=[],strict:i=!1}=e;this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new o(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new n,this._makeLocalGettersCache=Object.create(null);const r=this,{dispatch:c,commit:a}=this;this.dispatch=function(t,e){return c.call(r,t,e)},this.commit=function(t,e,s){return a.call(r,t,e,s)},this.strict=i;const l=this._modules.root.state;h(this,l,[],this._modules.root),u(this,l),s.forEach(t=>t(this)),(void 0!==e.devtools?e.devtools:n.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",t=>{e.replaceState(t)}),e.subscribe((e,s)=>{t.emit("vuex:mutation",e,s)},{prepend:!0}),e.subscribeAction((e,s)=>{t.emit("vuex:action",e,s)},{prepend:!0}))}(this)}get state(){return this._vm._data.$$state}set state(t){}commit(t,e,s){const{type:i,payload:o,options:n}=d(t,e,s),r={type:i,payload:o},c=this._mutations[i];c&&(this._withCommit(()=>{c.forEach(function(t){t(o)})}),this._subscribers.slice().forEach(t=>t(r,this.state)))}dispatch(t,e){const{type:s,payload:i}=d(t,e),o={type:s,payload:i},n=this._actions[s];if(n){try{this._actionSubscribers.slice().filter(t=>t.before).forEach(t=>t.before(o,this.state))}catch(t){}return(n.length>1?Promise.all(n.map(t=>t(i))):n[0](i)).then(t=>{try{this._actionSubscribers.filter(t=>t.after).forEach(t=>t.after(o,this.state))}catch(t){}return t})}}subscribe(t,e){return c(t,this._subscribers,e)}subscribeAction(t,e){return c("function"==typeof t?{before:t}:t,this._actionSubscribers,e)}watch(t,e,s){return this._watcherVM.$watch(()=>t(this.state,this.getters),e,s)}replaceState(t){this._withCommit(()=>{this._vm._data.$$state=t})}registerModule(t,e,s={}){"string"==typeof t&&(t=[t]),this._modules.register(t,e),h(this,this.state,t,this._modules.get(t),s.preserveState),u(this,this.state)}unregisterModule(t){"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit(()=>{const e=l(this.state,t.slice(0,-1));n.delete(e,t[t.length-1])}),a(this)}hasModule(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)}hotUpdate(t){this._modules.update(t),a(this,!0)}_withCommit(t){const e=this._committing;this._committing=!0,t(),this._committing=e}}function c(t,e,s){return e.indexOf(t)<0&&(s&&s.prepend?e.unshift(t):e.push(t)),()=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)}}function a(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);const s=t.state;h(t,s,[],t._modules.root,!0),u(t,s,e)}function u(t,s,i){const o=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);const r=t._wrappedGetters,c={};e(r,(e,s)=>{c[s]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,s,{get:()=>t._vm[s],enumerable:!0})});const a=n.config.silent;n.config.silent=!0,t._vm=new n({data:{$$state:s},computed:c}),n.config.silent=a,t.strict&&function(t){t._vm.$watch(function(){return this._data.$$state},()=>{},{deep:!0,sync:!0})}(t),o&&(i&&t._withCommit(()=>{o._data.$$state=null}),n.nextTick(()=>o.$destroy()))}function h(t,e,s,i,o){const r=!s.length,c=t._modules.getNamespace(s);if(i.namespaced&&(t._modulesNamespaceMap[c],t._modulesNamespaceMap[c]=i),!r&&!o){const o=l(e,s.slice(0,-1)),r=s[s.length-1];t._withCommit(()=>{n.set(o,r,i.state)})}const a=i.context=function(t,e,s){const i=""===e,o={dispatch:i?t.dispatch:(s,i,o)=>{const n=d(s,i,o),{payload:r,options:c}=n;let{type:a}=n;return c&&c.root||(a=e+a),t.dispatch(a,r)},commit:i?t.commit:(s,i,o)=>{const n=d(s,i,o),{payload:r,options:c}=n;let{type:a}=n;c&&c.root||(a=e+a),t.commit(a,r,c)}};return Object.defineProperties(o,{getters:{get:i?()=>t.getters:()=>(function(t,e){if(!t._makeLocalGettersCache[e]){const s={},i=e.length;Object.keys(t.getters).forEach(o=>{if(o.slice(0,i)!==e)return;const n=o.slice(i);Object.defineProperty(s,n,{get:()=>t.getters[o],enumerable:!0})}),t._makeLocalGettersCache[e]=s}return t._makeLocalGettersCache[e]})(t,e)},state:{get:()=>l(t.state,s)}}),o}(t,c,s);i.forEachMutation((e,s)=>{!function(t,e,s,i){(t._mutations[e]||(t._mutations[e]=[])).push(function(e){s.call(t,i.state,e)})}(t,c+s,e,a)}),i.forEachAction((e,s)=>{const i=e.root?s:c+s,o=e.handler||e;!function(t,e,s,i){(t._actions[e]||(t._actions[e]=[])).push(function(e){let o=s.call(t,{dispatch:i.dispatch,commit:i.commit,getters:i.getters,state:i.state,rootGetters:t.getters,rootState:t.state},e);var n;return(n=o)&&"function"==typeof n.then||(o=Promise.resolve(o)),t._devtoolHook?o.catch(e=>{throw t._devtoolHook.emit("vuex:error",e),e}):o})}(t,i,o,a)}),i.forEachGetter((e,s)=>{!function(t,e,s,i){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return s(i.state,i.getters,t.state,t.getters)}}(t,c+s,e,a)}),i.forEachChild((i,n)=>{h(t,e,s.concat(n),i,o)})}function l(t,e){return e.reduce((t,e)=>t[e],t)}function d(t,e,i){return s(t)&&t.type&&(i=e,e=t,t=t.type),{type:t,payload:e,options:i}}function p(t){n&&t===n||function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:e});else{const s=t.prototype._init;t.prototype._init=function(t={}){t.init=t.init?[e].concat(t.init):e,s.call(this,t)}}function e(){const t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(n=t)}const m=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{s[e]=function(){let e=this.$store.state,s=this.$store.getters;if(t){const i=v(this.$store,"mapState",t);if(!i)return;e=i.context.state,s=i.context.getters}return"function"==typeof i?i.call(this,e,s):e[i]},s[e].vuex=!0}),s}),f=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{s[e]=function(...e){let s=this.$store.commit;if(t){const e=v(this.$store,"mapMutations",t);if(!e)return;s=e.context.commit}return"function"==typeof i?i.apply(this,[s].concat(e)):s.apply(this.$store,[i].concat(e))}}),s}),_=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{i=t+i,s[e]=function(){if(!t||v(this.$store,"mapGetters",t))return this.$store.getters[i]},s[e].vuex=!0}),s}),g=w((t,e)=>{const s={};return b(e).forEach(({key:e,val:i})=>{s[e]=function(...e){let s=this.$store.dispatch;if(t){const e=v(this.$store,"mapActions",t);if(!e)return;s=e.context.dispatch}return"function"==typeof i?i.apply(this,[s].concat(e)):s.apply(this.$store,[i].concat(e))}}),s}),y=t=>({mapState:m.bind(null,t),mapGetters:_.bind(null,t),mapMutations:f.bind(null,t),mapActions:g.bind(null,t)});function b(t){return function(t){return Array.isArray(t)||s(t)}(t)?Array.isArray(t)?t.map(t=>({key:t,val:t})):Object.keys(t).map(e=>({key:e,val:t[e]})):[]}function w(t){return(e,s)=>("string"!=typeof e?(s=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,s))}function v(t,e,s){return t._modulesNamespaceMap[s]}export default{Store:r,install:p,version:"3.3.0",mapState:m,mapMutations:f,mapGetters:_,mapActions:g,createNamespacedHelpers:y};export{r as Store,p as install,m as mapState,f as mapMutations,_ as mapGetters,g as mapActions,y as createNamespacedHelpers}; \ No newline at end of file diff --git a/dist/vuex.esm.js b/dist/vuex.esm.js new file mode 100644 index 000000000..8c0774bac --- /dev/null +++ b/dist/vuex.esm.js @@ -0,0 +1,1078 @@ +/** + * vuex v3.3.0 + * (c) 2020 Evan You + * @license MIT + */ +function applyMixin (Vue) { + var version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + var _init = Vue.prototype._init; + Vue.prototype._init = function (options) { + if ( options === void 0 ) options = {}; + + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + var options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } +} + +var target = typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}; +var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; + +function devtoolPlugin (store) { + if (!devtoolHook) { return } + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', function (targetState) { + store.replaceState(targetState); + }); + + store.subscribe(function (mutation, state) { + devtoolHook.emit('vuex:mutation', mutation, state); + }, { prepend: true }); + + store.subscribeAction(function (action, state) { + devtoolHook.emit('vuex:action', action, state); + }, { prepend: true }); +} + +/** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + +/** + * forEach for object + */ +function forEachValue (obj, fn) { + Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); +} + +function isObject (obj) { + return obj !== null && typeof obj === 'object' +} + +function isPromise (val) { + return val && typeof val.then === 'function' +} + +function assert (condition, msg) { + if (!condition) { throw new Error(("[vuex] " + msg)) } +} + +function partial (fn, arg) { + return function () { + return fn(arg) + } +} + +// Base data struct for store's module, package with some attribute and method +var Module = function Module (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + var rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; +}; + +var prototypeAccessors = { namespaced: { configurable: true } }; + +prototypeAccessors.namespaced.get = function () { + return !!this._rawModule.namespaced +}; + +Module.prototype.addChild = function addChild (key, module) { + this._children[key] = module; +}; + +Module.prototype.removeChild = function removeChild (key) { + delete this._children[key]; +}; + +Module.prototype.getChild = function getChild (key) { + return this._children[key] +}; + +Module.prototype.hasChild = function hasChild (key) { + return key in this._children +}; + +Module.prototype.update = function update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } +}; + +Module.prototype.forEachChild = function forEachChild (fn) { + forEachValue(this._children, fn); +}; + +Module.prototype.forEachGetter = function forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } +}; + +Module.prototype.forEachAction = function forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } +}; + +Module.prototype.forEachMutation = function forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } +}; + +Object.defineProperties( Module.prototype, prototypeAccessors ); + +var ModuleCollection = function ModuleCollection (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); +}; + +ModuleCollection.prototype.get = function get (path) { + return path.reduce(function (module, key) { + return module.getChild(key) + }, this.root) +}; + +ModuleCollection.prototype.getNamespace = function getNamespace (path) { + var module = this.root; + return path.reduce(function (namespace, key) { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') +}; + +ModuleCollection.prototype.update = function update$1 (rawRootModule) { + update([], this.root, rawRootModule); +}; + +ModuleCollection.prototype.register = function register (path, rawModule, runtime) { + var this$1 = this; + if ( runtime === void 0 ) runtime = true; + + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, rawModule); + } + + var newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + var parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, function (rawChildModule, key) { + this$1.register(path.concat(key), rawChildModule, runtime); + }); + } +}; + +ModuleCollection.prototype.unregister = function unregister (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + if (!parent.getChild(key).runtime) { return } + + parent.removeChild(key); +}; + +ModuleCollection.prototype.isRegistered = function isRegistered (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + + return parent.hasChild(key) +}; + +function update (path, targetModule, newModule) { + if (process.env.NODE_ENV !== 'production') { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (var key in newModule.modules) { + if (!targetModule.getChild(key)) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + "[vuex] trying to add a new module '" + key + "' on hot reloading, " + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } +} + +var functionAssert = { + assert: function (value) { return typeof value === 'function'; }, + expected: 'function' +}; + +var objectAssert = { + assert: function (value) { return typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'); }, + expected: 'function or object with "handler" function' +}; + +var assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert +}; + +function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(function (key) { + if (!rawModule[key]) { return } + + var assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], function (value, type) { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); +} + +function makeAssertionMessage (path, key, type, value, expected) { + var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; + if (path.length > 0) { + buf += " in module \"" + (path.join('.')) + "\""; + } + buf += " is " + (JSON.stringify(value)) + "."; + return buf +} + +var Vue; // bind on install + +var Store = function Store (options) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + if (process.env.NODE_ENV !== 'production') { + assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); + assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); + assert(this instanceof Store, "store must be called with the new operator."); + } + + var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; + var strict = options.strict; if ( strict === void 0 ) strict = false; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + this._makeLocalGettersCache = Object.create(null); + + // bind commit and dispatch to self + var store = this; + var ref = this; + var dispatch = ref.dispatch; + var commit = ref.commit; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + var state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(function (plugin) { return plugin(this$1); }); + + var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } +}; + +var prototypeAccessors$1 = { state: { configurable: true } }; + +prototypeAccessors$1.state.get = function () { + return this._vm._data.$$state +}; + +prototypeAccessors$1.state.set = function (v) { + if (process.env.NODE_ENV !== 'production') { + assert(false, "use store.replaceState() to explicit replace store state."); + } +}; + +Store.prototype.commit = function commit (_type, _payload, _options) { + var this$1 = this; + + // check object-style commit + var ref = unifyObjectStyle(_type, _payload, _options); + var type = ref.type; + var payload = ref.payload; + var options = ref.options; + + var mutation = { type: type, payload: payload }; + var entry = this._mutations[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown mutation type: " + type)); + } + return + } + this._withCommit(function () { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + + this._subscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .forEach(function (sub) { return sub(mutation, this$1.state); }); + + if ( + process.env.NODE_ENV !== 'production' && + options && options.silent + ) { + console.warn( + "[vuex] mutation type: " + type + ". Silent option has been removed. " + + 'Use the filter functionality in the vue-devtools' + ); + } +}; + +Store.prototype.dispatch = function dispatch (_type, _payload) { + var this$1 = this; + + // check object-style dispatch + var ref = unifyObjectStyle(_type, _payload); + var type = ref.type; + var payload = ref.payload; + + var action = { type: type, payload: payload }; + var entry = this._actions[type]; + if (!entry) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] unknown action type: " + type)); + } + return + } + + try { + this._actionSubscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .filter(function (sub) { return sub.before; }) + .forEach(function (sub) { return sub.before(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in before action subscribers: "); + console.error(e); + } + } + + var result = entry.length > 1 + ? Promise.all(entry.map(function (handler) { return handler(payload); })) + : entry[0](payload); + + return result.then(function (res) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.after; }) + .forEach(function (sub) { return sub.after(action, this$1.state); }); + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn("[vuex] error in after action subscribers: "); + console.error(e); + } + } + return res + }) +}; + +Store.prototype.subscribe = function subscribe (fn, options) { + return genericSubscribe(fn, this._subscribers, options) +}; + +Store.prototype.subscribeAction = function subscribeAction (fn, options) { + var subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers, options) +}; + +Store.prototype.watch = function watch (getter, cb, options) { + var this$1 = this; + + if (process.env.NODE_ENV !== 'production') { + assert(typeof getter === 'function', "store.watch only accepts a function."); + } + return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) +}; + +Store.prototype.replaceState = function replaceState (state) { + var this$1 = this; + + this._withCommit(function () { + this$1._vm._data.$$state = state; + }); +}; + +Store.prototype.registerModule = function registerModule (path, rawModule, options) { + if ( options === void 0 ) options = {}; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); +}; + +Store.prototype.unregisterModule = function unregisterModule (path) { + var this$1 = this; + + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + this._modules.unregister(path); + this._withCommit(function () { + var parentState = getNestedState(this$1.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); +}; + +Store.prototype.hasModule = function hasModule (path) { + if (typeof path === 'string') { path = [path]; } + + if (process.env.NODE_ENV !== 'production') { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + return this._modules.isRegistered(path) +}; + +Store.prototype.hotUpdate = function hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); +}; + +Store.prototype._withCommit = function _withCommit (fn) { + var committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; +}; + +Object.defineProperties( Store.prototype, prototypeAccessors$1 ); + +function genericSubscribe (fn, subs, options) { + if (subs.indexOf(fn) < 0) { + options && options.prepend + ? subs.unshift(fn) + : subs.push(fn); + } + return function () { + var i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } +} + +function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + var state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); +} + +function resetStoreVM (store, state, hot) { + var oldVm = store._vm; + + // bind store public getters + store.getters = {}; + // reset local getters cache + store._makeLocalGettersCache = Object.create(null); + var wrappedGetters = store._wrappedGetters; + var computed = {}; + forEachValue(wrappedGetters, function (fn, key) { + // use computed to leverage its lazy-caching mechanism + // direct inline function use will lead to closure preserving oldVm. + // using partial to return function with only arguments preserved in closure environment. + computed[key] = partial(fn, store); + Object.defineProperty(store.getters, key, { + get: function () { return store._vm[key]; }, + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + var silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed: computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(function () { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(function () { return oldVm.$destroy(); }); + } +} + +function installModule (store, rootState, path, module, hot) { + var isRoot = !path.length; + var namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + if (store._modulesNamespaceMap[namespace] && process.env.NODE_ENV !== 'production') { + console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); + } + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + var parentState = getNestedState(rootState, path.slice(0, -1)); + var moduleName = path[path.length - 1]; + store._withCommit(function () { + if (process.env.NODE_ENV !== 'production') { + if (moduleName in parentState) { + console.warn( + ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") + ); + } + } + Vue.set(parentState, moduleName, module.state); + }); + } + + var local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation(function (mutation, key) { + var namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction(function (action, key) { + var type = action.root ? key : namespace + key; + var handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter(function (getter, key) { + var namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild(function (child, key) { + installModule(store, rootState, path.concat(key), child, hot); + }); +} + +/** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ +function makeLocalContext (store, namespace, path) { + var noNamespace = namespace === ''; + + var local = { + dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._actions[type]) { + console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) { + console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? function () { return store.getters; } + : function () { return makeLocalGetters(store, namespace); } + }, + state: { + get: function () { return getNestedState(store.state, path); } + } + }); + + return local +} + +function makeLocalGetters (store, namespace) { + if (!store._makeLocalGettersCache[namespace]) { + var gettersProxy = {}; + var splitPos = namespace.length; + Object.keys(store.getters).forEach(function (type) { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) { return } + + // extract local getter type + var localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: function () { return store.getters[type]; }, + enumerable: true + }); + }); + store._makeLocalGettersCache[namespace] = gettersProxy; + } + + return store._makeLocalGettersCache[namespace] +} + +function registerMutation (store, type, handler, local) { + var entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); +} + +function registerAction (store, type, handler, local) { + var entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload) { + var res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(function (err) { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); +} + +function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + if (process.env.NODE_ENV !== 'production') { + console.error(("[vuex] duplicate getter key: " + type)); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; +} + +function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, function () { + if (process.env.NODE_ENV !== 'production') { + assert(store._committing, "do not mutate vuex store state outside mutation handlers."); + } + }, { deep: true, sync: true }); +} + +function getNestedState (state, path) { + return path.reduce(function (state, key) { return state[key]; }, state) +} + +function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + if (process.env.NODE_ENV !== 'production') { + assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); + } + + return { type: type, payload: payload, options: options } +} + +function install (_Vue) { + if (Vue && _Vue === Vue) { + if (process.env.NODE_ENV !== 'production') { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); +} + +/** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ +var mapState = normalizeNamespace(function (namespace, states) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(states)) { + console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); + } + normalizeMap(states).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedState () { + var state = this.$store.state; + var getters = this.$store.getters; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapMutations = normalizeNamespace(function (namespace, mutations) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(mutations)) { + console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); + } + normalizeMap(mutations).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedMutation () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // Get the commit method from store + var commit = this.$store.commit; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ +var mapGetters = normalizeNamespace(function (namespace, getters) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(getters)) { + console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); + } + normalizeMap(getters).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (process.env.NODE_ENV !== 'production' && !(val in this.$store.getters)) { + console.error(("[vuex] unknown getter: " + val)); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res +}); + +/** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ +var mapActions = normalizeNamespace(function (namespace, actions) { + var res = {}; + if (process.env.NODE_ENV !== 'production' && !isValidMap(actions)) { + console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); + } + normalizeMap(actions).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // get dispatch function from store + var dispatch = this.$store.dispatch; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res +}); + +/** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ +var createNamespacedHelpers = function (namespace) { return ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) +}); }; + +/** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ +function normalizeMap (map) { + if (!isValidMap(map)) { + return [] + } + return Array.isArray(map) + ? map.map(function (key) { return ({ key: key, val: key }); }) + : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) +} + +/** + * Validate whether given map is valid or not + * @param {*} map + * @return {Boolean} + */ +function isValidMap (map) { + return Array.isArray(map) || isObject(map) +} + +/** + * 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. + * @param {Function} fn + * @return {Function} + */ +function normalizeNamespace (fn) { + return function (namespace, map) { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } +} + +/** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ +function getModuleByNamespace (store, helper, namespace) { + var module = store._modulesNamespaceMap[namespace]; + if (process.env.NODE_ENV !== 'production' && !module) { + console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); + } + return module +} + +var index_esm = { + Store: Store, + install: install, + version: '3.3.0', + mapState: mapState, + mapMutations: mapMutations, + mapGetters: mapGetters, + mapActions: mapActions, + createNamespacedHelpers: createNamespacedHelpers +}; + +export default index_esm; +export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers }; diff --git a/dist/vuex.js b/dist/vuex.js new file mode 100644 index 000000000..2f893a40a --- /dev/null +++ b/dist/vuex.js @@ -0,0 +1,1084 @@ +/** + * vuex v3.3.0 + * (c) 2020 Evan You + * @license MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.Vuex = factory()); +}(this, function () { 'use strict'; + + function applyMixin (Vue) { + var version = Number(Vue.version.split('.')[0]); + + if (version >= 2) { + Vue.mixin({ beforeCreate: vuexInit }); + } else { + // override init and inject vuex init procedure + // for 1.x backwards compatibility. + var _init = Vue.prototype._init; + Vue.prototype._init = function (options) { + if ( options === void 0 ) options = {}; + + options.init = options.init + ? [vuexInit].concat(options.init) + : vuexInit; + _init.call(this, options); + }; + } + + /** + * Vuex init hook, injected into each instances init hooks list. + */ + + function vuexInit () { + var options = this.$options; + // store injection + if (options.store) { + this.$store = typeof options.store === 'function' + ? options.store() + : options.store; + } else if (options.parent && options.parent.$store) { + this.$store = options.parent.$store; + } + } + } + + var target = typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}; + var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__; + + function devtoolPlugin (store) { + if (!devtoolHook) { return } + + store._devtoolHook = devtoolHook; + + devtoolHook.emit('vuex:init', store); + + devtoolHook.on('vuex:travel-to-state', function (targetState) { + store.replaceState(targetState); + }); + + store.subscribe(function (mutation, state) { + devtoolHook.emit('vuex:mutation', mutation, state); + }, { prepend: true }); + + store.subscribeAction(function (action, state) { + devtoolHook.emit('vuex:action', action, state); + }, { prepend: true }); + } + + /** + * Get the first item that pass the test + * by second argument function + * + * @param {Array} list + * @param {Function} f + * @return {*} + */ + + /** + * forEach for object + */ + function forEachValue (obj, fn) { + Object.keys(obj).forEach(function (key) { return fn(obj[key], key); }); + } + + function isObject (obj) { + return obj !== null && typeof obj === 'object' + } + + function isPromise (val) { + return val && typeof val.then === 'function' + } + + function assert (condition, msg) { + if (!condition) { throw new Error(("[vuex] " + msg)) } + } + + function partial (fn, arg) { + return function () { + return fn(arg) + } + } + + // Base data struct for store's module, package with some attribute and method + var Module = function Module (rawModule, runtime) { + this.runtime = runtime; + // Store some children item + this._children = Object.create(null); + // Store the origin module object which passed by programmer + this._rawModule = rawModule; + var rawState = rawModule.state; + + // Store the origin module's state + this.state = (typeof rawState === 'function' ? rawState() : rawState) || {}; + }; + + var prototypeAccessors = { namespaced: { configurable: true } }; + + prototypeAccessors.namespaced.get = function () { + return !!this._rawModule.namespaced + }; + + Module.prototype.addChild = function addChild (key, module) { + this._children[key] = module; + }; + + Module.prototype.removeChild = function removeChild (key) { + delete this._children[key]; + }; + + Module.prototype.getChild = function getChild (key) { + return this._children[key] + }; + + Module.prototype.hasChild = function hasChild (key) { + return key in this._children + }; + + Module.prototype.update = function update (rawModule) { + this._rawModule.namespaced = rawModule.namespaced; + if (rawModule.actions) { + this._rawModule.actions = rawModule.actions; + } + if (rawModule.mutations) { + this._rawModule.mutations = rawModule.mutations; + } + if (rawModule.getters) { + this._rawModule.getters = rawModule.getters; + } + }; + + Module.prototype.forEachChild = function forEachChild (fn) { + forEachValue(this._children, fn); + }; + + Module.prototype.forEachGetter = function forEachGetter (fn) { + if (this._rawModule.getters) { + forEachValue(this._rawModule.getters, fn); + } + }; + + Module.prototype.forEachAction = function forEachAction (fn) { + if (this._rawModule.actions) { + forEachValue(this._rawModule.actions, fn); + } + }; + + Module.prototype.forEachMutation = function forEachMutation (fn) { + if (this._rawModule.mutations) { + forEachValue(this._rawModule.mutations, fn); + } + }; + + Object.defineProperties( Module.prototype, prototypeAccessors ); + + var ModuleCollection = function ModuleCollection (rawRootModule) { + // register root module (Vuex.Store options) + this.register([], rawRootModule, false); + }; + + ModuleCollection.prototype.get = function get (path) { + return path.reduce(function (module, key) { + return module.getChild(key) + }, this.root) + }; + + ModuleCollection.prototype.getNamespace = function getNamespace (path) { + var module = this.root; + return path.reduce(function (namespace, key) { + module = module.getChild(key); + return namespace + (module.namespaced ? key + '/' : '') + }, '') + }; + + ModuleCollection.prototype.update = function update$1 (rawRootModule) { + update([], this.root, rawRootModule); + }; + + ModuleCollection.prototype.register = function register (path, rawModule, runtime) { + var this$1 = this; + if ( runtime === void 0 ) runtime = true; + + { + assertRawModule(path, rawModule); + } + + var newModule = new Module(rawModule, runtime); + if (path.length === 0) { + this.root = newModule; + } else { + var parent = this.get(path.slice(0, -1)); + parent.addChild(path[path.length - 1], newModule); + } + + // register nested modules + if (rawModule.modules) { + forEachValue(rawModule.modules, function (rawChildModule, key) { + this$1.register(path.concat(key), rawChildModule, runtime); + }); + } + }; + + ModuleCollection.prototype.unregister = function unregister (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + if (!parent.getChild(key).runtime) { return } + + parent.removeChild(key); + }; + + ModuleCollection.prototype.isRegistered = function isRegistered (path) { + var parent = this.get(path.slice(0, -1)); + var key = path[path.length - 1]; + + return parent.hasChild(key) + }; + + function update (path, targetModule, newModule) { + { + assertRawModule(path, newModule); + } + + // update target module + targetModule.update(newModule); + + // update nested modules + if (newModule.modules) { + for (var key in newModule.modules) { + if (!targetModule.getChild(key)) { + { + console.warn( + "[vuex] trying to add a new module '" + key + "' on hot reloading, " + + 'manual reload is needed' + ); + } + return + } + update( + path.concat(key), + targetModule.getChild(key), + newModule.modules[key] + ); + } + } + } + + var functionAssert = { + assert: function (value) { return typeof value === 'function'; }, + expected: 'function' + }; + + var objectAssert = { + assert: function (value) { return typeof value === 'function' || + (typeof value === 'object' && typeof value.handler === 'function'); }, + expected: 'function or object with "handler" function' + }; + + var assertTypes = { + getters: functionAssert, + mutations: functionAssert, + actions: objectAssert + }; + + function assertRawModule (path, rawModule) { + Object.keys(assertTypes).forEach(function (key) { + if (!rawModule[key]) { return } + + var assertOptions = assertTypes[key]; + + forEachValue(rawModule[key], function (value, type) { + assert( + assertOptions.assert(value), + makeAssertionMessage(path, key, type, value, assertOptions.expected) + ); + }); + }); + } + + function makeAssertionMessage (path, key, type, value, expected) { + var buf = key + " should be " + expected + " but \"" + key + "." + type + "\""; + if (path.length > 0) { + buf += " in module \"" + (path.join('.')) + "\""; + } + buf += " is " + (JSON.stringify(value)) + "."; + return buf + } + + var Vue; // bind on install + + var Store = function Store (options) { + var this$1 = this; + if ( options === void 0 ) options = {}; + + // Auto install if it is not done yet and `window` has `Vue`. + // To allow users to avoid auto-installation in some cases, + // this code should be placed here. See #731 + if (!Vue && typeof window !== 'undefined' && window.Vue) { + install(window.Vue); + } + + { + assert(Vue, "must call Vue.use(Vuex) before creating a store instance."); + assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser."); + assert(this instanceof Store, "store must be called with the new operator."); + } + + var plugins = options.plugins; if ( plugins === void 0 ) plugins = []; + var strict = options.strict; if ( strict === void 0 ) strict = false; + + // store internal state + this._committing = false; + this._actions = Object.create(null); + this._actionSubscribers = []; + this._mutations = Object.create(null); + this._wrappedGetters = Object.create(null); + this._modules = new ModuleCollection(options); + this._modulesNamespaceMap = Object.create(null); + this._subscribers = []; + this._watcherVM = new Vue(); + this._makeLocalGettersCache = Object.create(null); + + // bind commit and dispatch to self + var store = this; + var ref = this; + var dispatch = ref.dispatch; + var commit = ref.commit; + this.dispatch = function boundDispatch (type, payload) { + return dispatch.call(store, type, payload) + }; + this.commit = function boundCommit (type, payload, options) { + return commit.call(store, type, payload, options) + }; + + // strict mode + this.strict = strict; + + var state = this._modules.root.state; + + // init root module. + // this also recursively registers all sub-modules + // and collects all module getters inside this._wrappedGetters + installModule(this, state, [], this._modules.root); + + // initialize the store vm, which is responsible for the reactivity + // (also registers _wrappedGetters as computed properties) + resetStoreVM(this, state); + + // apply plugins + plugins.forEach(function (plugin) { return plugin(this$1); }); + + var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools; + if (useDevtools) { + devtoolPlugin(this); + } + }; + + var prototypeAccessors$1 = { state: { configurable: true } }; + + prototypeAccessors$1.state.get = function () { + return this._vm._data.$$state + }; + + prototypeAccessors$1.state.set = function (v) { + { + assert(false, "use store.replaceState() to explicit replace store state."); + } + }; + + Store.prototype.commit = function commit (_type, _payload, _options) { + var this$1 = this; + + // check object-style commit + var ref = unifyObjectStyle(_type, _payload, _options); + var type = ref.type; + var payload = ref.payload; + var options = ref.options; + + var mutation = { type: type, payload: payload }; + var entry = this._mutations[type]; + if (!entry) { + { + console.error(("[vuex] unknown mutation type: " + type)); + } + return + } + this._withCommit(function () { + entry.forEach(function commitIterator (handler) { + handler(payload); + }); + }); + + this._subscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .forEach(function (sub) { return sub(mutation, this$1.state); }); + + if ( + options && options.silent + ) { + console.warn( + "[vuex] mutation type: " + type + ". Silent option has been removed. " + + 'Use the filter functionality in the vue-devtools' + ); + } + }; + + Store.prototype.dispatch = function dispatch (_type, _payload) { + var this$1 = this; + + // check object-style dispatch + var ref = unifyObjectStyle(_type, _payload); + var type = ref.type; + var payload = ref.payload; + + var action = { type: type, payload: payload }; + var entry = this._actions[type]; + if (!entry) { + { + console.error(("[vuex] unknown action type: " + type)); + } + return + } + + try { + this._actionSubscribers + .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe + .filter(function (sub) { return sub.before; }) + .forEach(function (sub) { return sub.before(action, this$1.state); }); + } catch (e) { + { + console.warn("[vuex] error in before action subscribers: "); + console.error(e); + } + } + + var result = entry.length > 1 + ? Promise.all(entry.map(function (handler) { return handler(payload); })) + : entry[0](payload); + + return result.then(function (res) { + try { + this$1._actionSubscribers + .filter(function (sub) { return sub.after; }) + .forEach(function (sub) { return sub.after(action, this$1.state); }); + } catch (e) { + { + console.warn("[vuex] error in after action subscribers: "); + console.error(e); + } + } + return res + }) + }; + + Store.prototype.subscribe = function subscribe (fn, options) { + return genericSubscribe(fn, this._subscribers, options) + }; + + Store.prototype.subscribeAction = function subscribeAction (fn, options) { + var subs = typeof fn === 'function' ? { before: fn } : fn; + return genericSubscribe(subs, this._actionSubscribers, options) + }; + + Store.prototype.watch = function watch (getter, cb, options) { + var this$1 = this; + + { + assert(typeof getter === 'function', "store.watch only accepts a function."); + } + return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options) + }; + + Store.prototype.replaceState = function replaceState (state) { + var this$1 = this; + + this._withCommit(function () { + this$1._vm._data.$$state = state; + }); + }; + + Store.prototype.registerModule = function registerModule (path, rawModule, options) { + if ( options === void 0 ) options = {}; + + if (typeof path === 'string') { path = [path]; } + + { + assert(Array.isArray(path), "module path must be a string or an Array."); + assert(path.length > 0, 'cannot register the root module by using registerModule.'); + } + + this._modules.register(path, rawModule); + installModule(this, this.state, path, this._modules.get(path), options.preserveState); + // reset store to update getters... + resetStoreVM(this, this.state); + }; + + Store.prototype.unregisterModule = function unregisterModule (path) { + var this$1 = this; + + if (typeof path === 'string') { path = [path]; } + + { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + this._modules.unregister(path); + this._withCommit(function () { + var parentState = getNestedState(this$1.state, path.slice(0, -1)); + Vue.delete(parentState, path[path.length - 1]); + }); + resetStore(this); + }; + + Store.prototype.hasModule = function hasModule (path) { + if (typeof path === 'string') { path = [path]; } + + { + assert(Array.isArray(path), "module path must be a string or an Array."); + } + + return this._modules.isRegistered(path) + }; + + Store.prototype.hotUpdate = function hotUpdate (newOptions) { + this._modules.update(newOptions); + resetStore(this, true); + }; + + Store.prototype._withCommit = function _withCommit (fn) { + var committing = this._committing; + this._committing = true; + fn(); + this._committing = committing; + }; + + Object.defineProperties( Store.prototype, prototypeAccessors$1 ); + + function genericSubscribe (fn, subs, options) { + if (subs.indexOf(fn) < 0) { + options && options.prepend + ? subs.unshift(fn) + : subs.push(fn); + } + return function () { + var i = subs.indexOf(fn); + if (i > -1) { + subs.splice(i, 1); + } + } + } + + function resetStore (store, hot) { + store._actions = Object.create(null); + store._mutations = Object.create(null); + store._wrappedGetters = Object.create(null); + store._modulesNamespaceMap = Object.create(null); + var state = store.state; + // init all modules + installModule(store, state, [], store._modules.root, true); + // reset vm + resetStoreVM(store, state, hot); + } + + function resetStoreVM (store, state, hot) { + var oldVm = store._vm; + + // bind store public getters + store.getters = {}; + // reset local getters cache + store._makeLocalGettersCache = Object.create(null); + var wrappedGetters = store._wrappedGetters; + var computed = {}; + forEachValue(wrappedGetters, function (fn, key) { + // use computed to leverage its lazy-caching mechanism + // direct inline function use will lead to closure preserving oldVm. + // using partial to return function with only arguments preserved in closure environment. + computed[key] = partial(fn, store); + Object.defineProperty(store.getters, key, { + get: function () { return store._vm[key]; }, + enumerable: true // for local getters + }); + }); + + // use a Vue instance to store the state tree + // suppress warnings just in case the user has added + // some funky global mixins + var silent = Vue.config.silent; + Vue.config.silent = true; + store._vm = new Vue({ + data: { + $$state: state + }, + computed: computed + }); + Vue.config.silent = silent; + + // enable strict mode for new vm + if (store.strict) { + enableStrictMode(store); + } + + if (oldVm) { + if (hot) { + // dispatch changes in all subscribed watchers + // to force getter re-evaluation for hot reloading. + store._withCommit(function () { + oldVm._data.$$state = null; + }); + } + Vue.nextTick(function () { return oldVm.$destroy(); }); + } + } + + function installModule (store, rootState, path, module, hot) { + var isRoot = !path.length; + var namespace = store._modules.getNamespace(path); + + // register in namespace map + if (module.namespaced) { + if (store._modulesNamespaceMap[namespace] && "development" !== 'production') { + console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/')))); + } + store._modulesNamespaceMap[namespace] = module; + } + + // set state + if (!isRoot && !hot) { + var parentState = getNestedState(rootState, path.slice(0, -1)); + var moduleName = path[path.length - 1]; + store._withCommit(function () { + { + if (moduleName in parentState) { + console.warn( + ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"") + ); + } + } + Vue.set(parentState, moduleName, module.state); + }); + } + + var local = module.context = makeLocalContext(store, namespace, path); + + module.forEachMutation(function (mutation, key) { + var namespacedType = namespace + key; + registerMutation(store, namespacedType, mutation, local); + }); + + module.forEachAction(function (action, key) { + var type = action.root ? key : namespace + key; + var handler = action.handler || action; + registerAction(store, type, handler, local); + }); + + module.forEachGetter(function (getter, key) { + var namespacedType = namespace + key; + registerGetter(store, namespacedType, getter, local); + }); + + module.forEachChild(function (child, key) { + installModule(store, rootState, path.concat(key), child, hot); + }); + } + + /** + * make localized dispatch, commit, getters and state + * if there is no namespace, just use root ones + */ + function makeLocalContext (store, namespace, path) { + var noNamespace = namespace === ''; + + var local = { + dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (!store._actions[type]) { + console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type)); + return + } + } + + return store.dispatch(type, payload) + }, + + commit: noNamespace ? store.commit : function (_type, _payload, _options) { + var args = unifyObjectStyle(_type, _payload, _options); + var payload = args.payload; + var options = args.options; + var type = args.type; + + if (!options || !options.root) { + type = namespace + type; + if (!store._mutations[type]) { + console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type)); + return + } + } + + store.commit(type, payload, options); + } + }; + + // getters and state object must be gotten lazily + // because they will be changed by vm update + Object.defineProperties(local, { + getters: { + get: noNamespace + ? function () { return store.getters; } + : function () { return makeLocalGetters(store, namespace); } + }, + state: { + get: function () { return getNestedState(store.state, path); } + } + }); + + return local + } + + function makeLocalGetters (store, namespace) { + if (!store._makeLocalGettersCache[namespace]) { + var gettersProxy = {}; + var splitPos = namespace.length; + Object.keys(store.getters).forEach(function (type) { + // skip if the target getter is not match this namespace + if (type.slice(0, splitPos) !== namespace) { return } + + // extract local getter type + var localType = type.slice(splitPos); + + // Add a port to the getters proxy. + // Define as getter property because + // we do not want to evaluate the getters in this time. + Object.defineProperty(gettersProxy, localType, { + get: function () { return store.getters[type]; }, + enumerable: true + }); + }); + store._makeLocalGettersCache[namespace] = gettersProxy; + } + + return store._makeLocalGettersCache[namespace] + } + + function registerMutation (store, type, handler, local) { + var entry = store._mutations[type] || (store._mutations[type] = []); + entry.push(function wrappedMutationHandler (payload) { + handler.call(store, local.state, payload); + }); + } + + function registerAction (store, type, handler, local) { + var entry = store._actions[type] || (store._actions[type] = []); + entry.push(function wrappedActionHandler (payload) { + var res = handler.call(store, { + dispatch: local.dispatch, + commit: local.commit, + getters: local.getters, + state: local.state, + rootGetters: store.getters, + rootState: store.state + }, payload); + if (!isPromise(res)) { + res = Promise.resolve(res); + } + if (store._devtoolHook) { + return res.catch(function (err) { + store._devtoolHook.emit('vuex:error', err); + throw err + }) + } else { + return res + } + }); + } + + function registerGetter (store, type, rawGetter, local) { + if (store._wrappedGetters[type]) { + { + console.error(("[vuex] duplicate getter key: " + type)); + } + return + } + store._wrappedGetters[type] = function wrappedGetter (store) { + return rawGetter( + local.state, // local state + local.getters, // local getters + store.state, // root state + store.getters // root getters + ) + }; + } + + function enableStrictMode (store) { + store._vm.$watch(function () { return this._data.$$state }, function () { + { + assert(store._committing, "do not mutate vuex store state outside mutation handlers."); + } + }, { deep: true, sync: true }); + } + + function getNestedState (state, path) { + return path.reduce(function (state, key) { return state[key]; }, state) + } + + function unifyObjectStyle (type, payload, options) { + if (isObject(type) && type.type) { + options = payload; + payload = type; + type = type.type; + } + + { + assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + ".")); + } + + return { type: type, payload: payload, options: options } + } + + function install (_Vue) { + if (Vue && _Vue === Vue) { + { + console.error( + '[vuex] already installed. Vue.use(Vuex) should be called only once.' + ); + } + return + } + Vue = _Vue; + applyMixin(Vue); + } + + /** + * Reduce the code which written in Vue.js for getting the state. + * @param {String} [namespace] - Module's namespace + * @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. + * @param {Object} + */ + var mapState = normalizeNamespace(function (namespace, states) { + var res = {}; + if (!isValidMap(states)) { + console.error('[vuex] mapState: mapper parameter must be either an Array or an Object'); + } + normalizeMap(states).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedState () { + var state = this.$store.state; + var getters = this.$store.getters; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapState', namespace); + if (!module) { + return + } + state = module.context.state; + getters = module.context.getters; + } + return typeof val === 'function' + ? val.call(this, state, getters) + : state[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res + }); + + /** + * Reduce the code which written in Vue.js for committing the mutation + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ + var mapMutations = normalizeNamespace(function (namespace, mutations) { + var res = {}; + if (!isValidMap(mutations)) { + console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object'); + } + normalizeMap(mutations).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedMutation () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // Get the commit method from store + var commit = this.$store.commit; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapMutations', namespace); + if (!module) { + return + } + commit = module.context.commit; + } + return typeof val === 'function' + ? val.apply(this, [commit].concat(args)) + : commit.apply(this.$store, [val].concat(args)) + }; + }); + return res + }); + + /** + * Reduce the code which written in Vue.js for getting the getters + * @param {String} [namespace] - Module's namespace + * @param {Object|Array} getters + * @return {Object} + */ + var mapGetters = normalizeNamespace(function (namespace, getters) { + var res = {}; + if (!isValidMap(getters)) { + console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object'); + } + normalizeMap(getters).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + // The namespace has been mutated by normalizeNamespace + val = namespace + val; + res[key] = function mappedGetter () { + if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) { + return + } + if (!(val in this.$store.getters)) { + console.error(("[vuex] unknown getter: " + val)); + return + } + return this.$store.getters[val] + }; + // mark vuex getter for devtools + res[key].vuex = true; + }); + return res + }); + + /** + * Reduce the code which written in Vue.js for dispatch the action + * @param {String} [namespace] - Module's namespace + * @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. + * @return {Object} + */ + var mapActions = normalizeNamespace(function (namespace, actions) { + var res = {}; + if (!isValidMap(actions)) { + console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object'); + } + normalizeMap(actions).forEach(function (ref) { + var key = ref.key; + var val = ref.val; + + res[key] = function mappedAction () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // get dispatch function from store + var dispatch = this.$store.dispatch; + if (namespace) { + var module = getModuleByNamespace(this.$store, 'mapActions', namespace); + if (!module) { + return + } + dispatch = module.context.dispatch; + } + return typeof val === 'function' + ? val.apply(this, [dispatch].concat(args)) + : dispatch.apply(this.$store, [val].concat(args)) + }; + }); + return res + }); + + /** + * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object + * @param {String} namespace + * @return {Object} + */ + var createNamespacedHelpers = function (namespace) { return ({ + mapState: mapState.bind(null, namespace), + mapGetters: mapGetters.bind(null, namespace), + mapMutations: mapMutations.bind(null, namespace), + mapActions: mapActions.bind(null, namespace) + }); }; + + /** + * Normalize the map + * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ] + * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ] + * @param {Array|Object} map + * @return {Object} + */ + function normalizeMap (map) { + if (!isValidMap(map)) { + return [] + } + return Array.isArray(map) + ? map.map(function (key) { return ({ key: key, val: key }); }) + : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); }) + } + + /** + * Validate whether given map is valid or not + * @param {*} map + * @return {Boolean} + */ + function isValidMap (map) { + return Array.isArray(map) || isObject(map) + } + + /** + * 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. + * @param {Function} fn + * @return {Function} + */ + function normalizeNamespace (fn) { + return function (namespace, map) { + if (typeof namespace !== 'string') { + map = namespace; + namespace = ''; + } else if (namespace.charAt(namespace.length - 1) !== '/') { + namespace += '/'; + } + return fn(namespace, map) + } + } + + /** + * Search a special module from store by namespace. if module not exist, print error message. + * @param {Object} store + * @param {String} helper + * @param {String} namespace + * @return {Object} + */ + function getModuleByNamespace (store, helper, namespace) { + var module = store._modulesNamespaceMap[namespace]; + if (!module) { + console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace)); + } + return module + } + + var index = { + Store: Store, + install: install, + version: '3.3.0', + mapState: mapState, + mapMutations: mapMutations, + mapGetters: mapGetters, + mapActions: mapActions, + createNamespacedHelpers: createNamespacedHelpers + }; + + return index; + +})); diff --git a/dist/vuex.min.js b/dist/vuex.min.js new file mode 100644 index 000000000..cd5ce4c56 --- /dev/null +++ b/dist/vuex.min.js @@ -0,0 +1,6 @@ +/** + * vuex v3.3.0 + * (c) 2020 Evan You + * @license MIT + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Vuex=e()}(this,function(){"use strict";var t=("undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).__VUE_DEVTOOLS_GLOBAL_HOOK__;function e(t,e){Object.keys(t).forEach(function(n){return e(t[n],n)})}function n(t){return null!==t&&"object"==typeof t}var o=function(t,e){this.runtime=e,this._children=Object.create(null),this._rawModule=t;var n=t.state;this.state=("function"==typeof n?n():n)||{}},i={namespaced:{configurable:!0}};i.namespaced.get=function(){return!!this._rawModule.namespaced},o.prototype.addChild=function(t,e){this._children[t]=e},o.prototype.removeChild=function(t){delete this._children[t]},o.prototype.getChild=function(t){return this._children[t]},o.prototype.hasChild=function(t){return t in this._children},o.prototype.update=function(t){this._rawModule.namespaced=t.namespaced,t.actions&&(this._rawModule.actions=t.actions),t.mutations&&(this._rawModule.mutations=t.mutations),t.getters&&(this._rawModule.getters=t.getters)},o.prototype.forEachChild=function(t){e(this._children,t)},o.prototype.forEachGetter=function(t){this._rawModule.getters&&e(this._rawModule.getters,t)},o.prototype.forEachAction=function(t){this._rawModule.actions&&e(this._rawModule.actions,t)},o.prototype.forEachMutation=function(t){this._rawModule.mutations&&e(this._rawModule.mutations,t)},Object.defineProperties(o.prototype,i);var r,s=function(t){this.register([],t,!1)};s.prototype.get=function(t){return t.reduce(function(t,e){return t.getChild(e)},this.root)},s.prototype.getNamespace=function(t){var e=this.root;return t.reduce(function(t,n){return t+((e=e.getChild(n)).namespaced?n+"/":"")},"")},s.prototype.update=function(t){!function t(e,n,o){n.update(o);if(o.modules)for(var i in o.modules){if(!n.getChild(i))return;t(e.concat(i),n.getChild(i),o.modules[i])}}([],this.root,t)},s.prototype.register=function(t,n,i){var r=this;void 0===i&&(i=!0);var s=new o(n,i);0===t.length?this.root=s:this.get(t.slice(0,-1)).addChild(t[t.length-1],s);n.modules&&e(n.modules,function(e,n){r.register(t.concat(n),e,i)})},s.prototype.unregister=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];e.getChild(n).runtime&&e.removeChild(n)},s.prototype.isRegistered=function(t){var e=this.get(t.slice(0,-1)),n=t[t.length-1];return e.hasChild(n)};var a=function(e){var n=this;void 0===e&&(e={}),!r&&"undefined"!=typeof window&&window.Vue&&m(window.Vue);var o=e.plugins;void 0===o&&(o=[]);var i=e.strict;void 0===i&&(i=!1),this._committing=!1,this._actions=Object.create(null),this._actionSubscribers=[],this._mutations=Object.create(null),this._wrappedGetters=Object.create(null),this._modules=new s(e),this._modulesNamespaceMap=Object.create(null),this._subscribers=[],this._watcherVM=new r,this._makeLocalGettersCache=Object.create(null);var a=this,c=this.dispatch,u=this.commit;this.dispatch=function(t,e){return c.call(a,t,e)},this.commit=function(t,e,n){return u.call(a,t,e,n)},this.strict=i;var f=this._modules.root.state;p(this,f,[],this._modules.root),h(this,f),o.forEach(function(t){return t(n)}),(void 0!==e.devtools?e.devtools:r.config.devtools)&&function(e){t&&(e._devtoolHook=t,t.emit("vuex:init",e),t.on("vuex:travel-to-state",function(t){e.replaceState(t)}),e.subscribe(function(e,n){t.emit("vuex:mutation",e,n)},{prepend:!0}),e.subscribeAction(function(e,n){t.emit("vuex:action",e,n)},{prepend:!0}))}(this)},c={state:{configurable:!0}};function u(t,e,n){return e.indexOf(t)<0&&(n&&n.prepend?e.unshift(t):e.push(t)),function(){var n=e.indexOf(t);n>-1&&e.splice(n,1)}}function f(t,e){t._actions=Object.create(null),t._mutations=Object.create(null),t._wrappedGetters=Object.create(null),t._modulesNamespaceMap=Object.create(null);var n=t.state;p(t,n,[],t._modules.root,!0),h(t,n,e)}function h(t,n,o){var i=t._vm;t.getters={},t._makeLocalGettersCache=Object.create(null);var s=t._wrappedGetters,a={};e(s,function(e,n){a[n]=function(t,e){return function(){return t(e)}}(e,t),Object.defineProperty(t.getters,n,{get:function(){return t._vm[n]},enumerable:!0})});var c=r.config.silent;r.config.silent=!0,t._vm=new r({data:{$$state:n},computed:a}),r.config.silent=c,t.strict&&function(t){t._vm.$watch(function(){return this._data.$$state},function(){},{deep:!0,sync:!0})}(t),i&&(o&&t._withCommit(function(){i._data.$$state=null}),r.nextTick(function(){return i.$destroy()}))}function p(t,e,n,o,i){var s=!n.length,a=t._modules.getNamespace(n);if(o.namespaced&&(t._modulesNamespaceMap[a],t._modulesNamespaceMap[a]=o),!s&&!i){var c=l(e,n.slice(0,-1)),u=n[n.length-1];t._withCommit(function(){r.set(c,u,o.state)})}var f=o.context=function(t,e,n){var o=""===e,i={dispatch:o?t.dispatch:function(n,o,i){var r=d(n,o,i),s=r.payload,a=r.options,c=r.type;return a&&a.root||(c=e+c),t.dispatch(c,s)},commit:o?t.commit:function(n,o,i){var r=d(n,o,i),s=r.payload,a=r.options,c=r.type;a&&a.root||(c=e+c),t.commit(c,s,a)}};return Object.defineProperties(i,{getters:{get:o?function(){return t.getters}:function(){return function(t,e){if(!t._makeLocalGettersCache[e]){var n={},o=e.length;Object.keys(t.getters).forEach(function(i){if(i.slice(0,o)===e){var r=i.slice(o);Object.defineProperty(n,r,{get:function(){return t.getters[i]},enumerable:!0})}}),t._makeLocalGettersCache[e]=n}return t._makeLocalGettersCache[e]}(t,e)}},state:{get:function(){return l(t.state,n)}}}),i}(t,a,n);o.forEachMutation(function(e,n){!function(t,e,n,o){(t._mutations[e]||(t._mutations[e]=[])).push(function(e){n.call(t,o.state,e)})}(t,a+n,e,f)}),o.forEachAction(function(e,n){var o=e.root?n:a+n,i=e.handler||e;!function(t,e,n,o){(t._actions[e]||(t._actions[e]=[])).push(function(e){var i,r=n.call(t,{dispatch:o.dispatch,commit:o.commit,getters:o.getters,state:o.state,rootGetters:t.getters,rootState:t.state},e);return(i=r)&&"function"==typeof i.then||(r=Promise.resolve(r)),t._devtoolHook?r.catch(function(e){throw t._devtoolHook.emit("vuex:error",e),e}):r})}(t,o,i,f)}),o.forEachGetter(function(e,n){!function(t,e,n,o){if(t._wrappedGetters[e])return;t._wrappedGetters[e]=function(t){return n(o.state,o.getters,t.state,t.getters)}}(t,a+n,e,f)}),o.forEachChild(function(o,r){p(t,e,n.concat(r),o,i)})}function l(t,e){return e.reduce(function(t,e){return t[e]},t)}function d(t,e,o){return n(t)&&t.type&&(o=e,e=t,t=t.type),{type:t,payload:e,options:o}}function m(t){r&&t===r||function(t){if(Number(t.version.split(".")[0])>=2)t.mixin({beforeCreate:n});else{var e=t.prototype._init;t.prototype._init=function(t){void 0===t&&(t={}),t.init=t.init?[n].concat(t.init):n,e.call(this,t)}}function n(){var t=this.$options;t.store?this.$store="function"==typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}(r=t)}c.state.get=function(){return this._vm._data.$$state},c.state.set=function(t){},a.prototype.commit=function(t,e,n){var o=this,i=d(t,e,n),r=i.type,s=i.payload,a={type:r,payload:s},c=this._mutations[r];c&&(this._withCommit(function(){c.forEach(function(t){t(s)})}),this._subscribers.slice().forEach(function(t){return t(a,o.state)}))},a.prototype.dispatch=function(t,e){var n=this,o=d(t,e),i=o.type,r=o.payload,s={type:i,payload:r},a=this._actions[i];if(a){try{this._actionSubscribers.slice().filter(function(t){return t.before}).forEach(function(t){return t.before(s,n.state)})}catch(t){}return(a.length>1?Promise.all(a.map(function(t){return t(r)})):a[0](r)).then(function(t){try{n._actionSubscribers.filter(function(t){return t.after}).forEach(function(t){return t.after(s,n.state)})}catch(t){}return t})}},a.prototype.subscribe=function(t,e){return u(t,this._subscribers,e)},a.prototype.subscribeAction=function(t,e){return u("function"==typeof t?{before:t}:t,this._actionSubscribers,e)},a.prototype.watch=function(t,e,n){var o=this;return this._watcherVM.$watch(function(){return t(o.state,o.getters)},e,n)},a.prototype.replaceState=function(t){var e=this;this._withCommit(function(){e._vm._data.$$state=t})},a.prototype.registerModule=function(t,e,n){void 0===n&&(n={}),"string"==typeof t&&(t=[t]),this._modules.register(t,e),p(this,this.state,t,this._modules.get(t),n.preserveState),h(this,this.state)},a.prototype.unregisterModule=function(t){var e=this;"string"==typeof t&&(t=[t]),this._modules.unregister(t),this._withCommit(function(){var n=l(e.state,t.slice(0,-1));r.delete(n,t[t.length-1])}),f(this)},a.prototype.hasModule=function(t){return"string"==typeof t&&(t=[t]),this._modules.isRegistered(t)},a.prototype.hotUpdate=function(t){this._modules.update(t),f(this,!0)},a.prototype._withCommit=function(t){var e=this._committing;this._committing=!0,t(),this._committing=e},Object.defineProperties(a.prototype,c);var v=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;n[o]=function(){var e=this.$store.state,n=this.$store.getters;if(t){var o=$(this.$store,"mapState",t);if(!o)return;e=o.context.state,n=o.context.getters}return"function"==typeof i?i.call(this,e,n):e[i]},n[o].vuex=!0}),n}),_=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.commit;if(t){var r=$(this.$store,"mapMutations",t);if(!r)return;o=r.context.commit}return"function"==typeof i?i.apply(this,[o].concat(e)):o.apply(this.$store,[i].concat(e))}}),n}),y=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;i=t+i,n[o]=function(){if(!t||$(this.$store,"mapGetters",t))return this.$store.getters[i]},n[o].vuex=!0}),n}),g=w(function(t,e){var n={};return b(e).forEach(function(e){var o=e.key,i=e.val;n[o]=function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var o=this.$store.dispatch;if(t){var r=$(this.$store,"mapActions",t);if(!r)return;o=r.context.dispatch}return"function"==typeof i?i.apply(this,[o].concat(e)):o.apply(this.$store,[i].concat(e))}}),n});function b(t){return function(t){return Array.isArray(t)||n(t)}(t)?Array.isArray(t)?t.map(function(t){return{key:t,val:t}}):Object.keys(t).map(function(e){return{key:e,val:t[e]}}):[]}function w(t){return function(e,n){return"string"!=typeof e?(n=e,e=""):"/"!==e.charAt(e.length-1)&&(e+="/"),t(e,n)}}function $(t,e,n){return t._modulesNamespaceMap[n]}return{Store:a,install:m,version:"3.3.0",mapState:v,mapMutations:_,mapGetters:y,mapActions:g,createNamespacedHelpers:function(t){return{mapState:v.bind(null,t),mapGetters:y.bind(null,t),mapMutations:_.bind(null,t),mapActions:g.bind(null,t)}}}}); \ No newline at end of file From d6807634f0bb894d54d714c017414bad9044a5ba Mon Sep 17 00:00:00 2001 From: Joe Plahitko Date: Wed, 6 May 2020 07:36:26 -0400 Subject: [PATCH 8/8] Updated error message in error action subscriber. --- src/store.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/store.js b/src/store.js index 6966700fb..03169d958 100644 --- a/src/store.js +++ b/src/store.js @@ -169,7 +169,7 @@ export class Store { .forEach(sub => sub.error(action, this.state, e)) } catch (_e) { if (__DEV__) { - console.warn(`[vuex] error in after action catch subscribers: `) + console.warn(`[vuex] error in error action subscribers: `) console.error(_e) } }