This commit is contained in:
darenhsu
2022-07-17 13:16:16 +08:00
parent 84759556ff
commit befd344ab0
28070 changed files with 4008428 additions and 1 deletions
+103
View File
@@ -0,0 +1,103 @@
# CHANGELOG
If `(beta)` or `(alpha)` is marked in front of any release, it can be
installed as `npm install vuex-module-decorators@beta` (or alpha similar).
## 1.0.0
### 0.14.0
- support for `preserveState: true` in module options to use `vuex-persist` (OPTIONAL)
### 0.13.0
- tslib update, latest versions of all typescript compilers and runtimes
### 0.11.0
- fix support for SSR (with NUXT)
### 0.10.0
- Updated to TypeScript 3.5
#### 0.9.9
- added github actions
#### 0.9.5
- more typesafe `@MutationAction`
- you cannot `mutate` keys not in the module
- the returned object must be a partial of the module
#### 0.9.4
- initializing properties with `null` and then running `@MutationAction` is possible now
#### 0.9.3
- we will distribute in ES5 as a lot of people still use ES5 target for their websites
#### 0.9.1
- fix context getting lost in actions
- via [pr 55](https://github.com/championswimmer/vuex-module-decorators/pull/55)
- add ability to access getters inside actions simply as `this.getterName`
### 0.9.0
- distribute as ES2015 (users need to transpile)
### 0.8.0
##### 0.8.0-4 (beta)
- inside getters we can access `rootState` and `rootGetters`
- Use `this.context.rootState` and `this.context.rootGetters`
##### 0.8.0-3 (beta)
- in `@Action` and `@MutationAction` functions -
- Now introduces `rawError` decorator option
- By default they are set to false to keep the old behavior
- Old behaviour - it is wrapped in a helper message
- If set to true, errors inside actions will be thrown as it is
- in`@Action` functions -
- `commit` decorator option can now be optional
##### 0.8.0-2 (beta)
- in `@Action` functions -
- `this.stateField` works pointing to fields in the module's state
- `this.context.commit('mutationName', payload)` is way to trigger mutation
- `this.context.getters['getterName'])` is the way to use getters
- **iff your module is dynamic** you get more typesafety
- calling `this.mutationName(payload)` will work as well
- accessing `this.getterName` will work as well
##### 0.8.0-0 (beta)
- allow `getModule()` even for non-dynamic modules
> **NOTE:** From now on you have to use`getModule(ModuleClass)`
> instead of the earlier `getModule(ModuleClass.prototype)`
- update to prettier code formatting
#### 0.7.1
- fix `unable to construct without new` error for transpiled ES5
### 0.7.0
- add `module` field to package.json for ES6 module loaders
- tree-shaking supported
### 0.6.0
- distribute cjs, esm and minified cdn package separately
### 0.1.0
#### 0.0.1
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Arnav Gupta
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+396
View File
@@ -0,0 +1,396 @@
# vuex-module-decorators
[![Usage Guide](https://img.shields.io/badge/usage-guide-1e90ff.svg?style=for-the-badge&longCache=true)](https://championswimmer.in/vuex-module-decorators/)
Detailed Guide: https://championswimmer.in/vuex-module-decorators/
Typescript/ES7 Decorators to make Vuex modules a breeze
[![Build Status](https://travis-ci.org/championswimmer/vuex-module-decorators.svg?branch=master)](https://travis-ci.org/championswimmer/vuex-module-decorators)
[![npm:size:gzip](https://img.shields.io/bundlephobia/minzip/vuex-module-decorators.svg?label=npm:size:gzip)](https://bundlephobia.com/result?p=vuex-module-decorators)
[![cdn:min:gzip](https://img.badgesize.io/https://cdn.jsdelivr.net/npm/vuex-module-decorators.svg?label=cdn:min:gzip&compression=gzip)](https://cdn.jsdelivr.net/npm/vuex-module-decorators/dist/cjs/index.min.js)
[![codecov](https://codecov.io/gh/championswimmer/vuex-module-decorators/branch/master/graph/badge.svg)](https://codecov.io/gh/championswimmer/vuex-module-decorators)
[![npm](https://img.shields.io/npm/v/vuex-module-decorators.svg)](https://www.npmjs.com/package/vuex-module-decorators)
[![npm](https://img.shields.io/npm/dw/vuex-module-decorators.svg?colorB=ff0033)](https://www.npmjs.com/package/vuex-module-decorators)
![npm type definitions](https://img.shields.io/npm/types/vuex-module-decorators.svg)
[![Maintainability](https://api.codeclimate.com/v1/badges/5b1dfa8d3d4bdf409b60/maintainability)](https://codeclimate.com/github/championswimmer/vuex-module-decorators/maintainability)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/b7944c579d5c4c1d949f71a91a538d77)](https://www.codacy.com/app/championswimmer/vuex-module-decorators?utm_source=github.com&utm_medium=referral&utm_content=championswimmer/vuex-module-decorators&utm_campaign=Badge_Grade)
[![codebeat badge](https://codebeat.co/badges/0272746c-8a7d-428b-a20d-387d22bfbcfb)](https://codebeat.co/projects/github-com-championswimmer-vuex-module-decorators-master)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/championswimmer/vuex-module-decorators.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/championswimmer/vuex-module-decorators/alerts/)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/championswimmer/vuex-module-decorators.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/championswimmer/vuex-module-decorators/context:javascript)
## CHANGELOG
- There are major type-checking changes (could be breaking) in v0.9.7
- There are major usage improvements (non backwards compatible) in 0.8.0
Please check [CHANGELOG](CHANGELOG.md)
## Examples
Read the rest of the README to figure out how to use, or if you readily want to jump into a production codebase and see how this is used, you can check out -
- <https://github.com/Armour/vue-typescript-admin-template>
- <https://github.com/xieguangcai/vue-order-admin>
- <https://github.com/coding-blocks-archives/realworld-vue-typescript>
## Installation
```shell
npm install -D vuex-module-decorators
```
### Babel 6/7
> **NOTE** This is **not** necessary for `vue-cli@3` projects, since `@vue/babel-preset-app` already includes this plugin
1. You need to install `babel-plugin-transform-decorators`
### TypeScript
1. set `experimentalDecorators` to true
2. For reduced code with decorators, set `importHelpers: true` in `tsconfig.json`
3. _(only for TypeScript 2)_ set `emitHelpers: true` in `tsconfig.json`
## Configuration
### Using with `target: es5`
> **NOTE** Since version `0.9.3` we distribute as ES5, so this section is applicable only to v0.9.2 and below
This package generates code in `es2015` format. If your Vue project targets ES6 or ES2015 then
you need not do anything. But in case your project uses `es5` target (to support old browsers), then
you need to tell Vue CLI / Babel to transpile this package.
```js
// in your vue.config.js
module.exports = {
/* ... other settings */
transpileDependencies: ['vuex-module-decorators']
}
```
## Usage
#### The <strike>conventional</strike> old & boring way
Remember how vuex modules used to be made ?
```js
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
```
#### Hello Decorators !
Well not anymore. Now you get better syntax. Inspired by `vue-class-component`
```typescript
import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'
@Module
export default class Counter2 extends VuexModule {
count = 0
@Mutation
increment(delta: number) {
this.count += delta
}
@Mutation
decrement(delta: number) {
this.count -= delta
}
// action 'incr' commits mutation 'increment' when done with return value as payload
@Action({ commit: 'increment' })
incr() {
return 5
}
// action 'decr' commits mutation 'decrement' when done with return value as payload
@Action({ commit: 'decrement' })
decr() {
return 5
}
}
```
#### async MutationAction === magic
Want to see something even better ?
```typescript
import { Module, VuexModule, MutationAction } from 'vuex-module-decorators'
import { ConferencesEntity, EventsEntity } from '@/models/definitions'
@Module
export default class HGAPIModule extends VuexModule {
conferences: Array<ConferencesEntity> = []
events: Array<EventsEntity> = []
// 'events' and 'conferences' are replaced by returned object
// whose shape must be `{events: [...], conferences: [...] }`
@MutationAction({ mutate: ['events', 'conferences'] })
async fetchAll() {
const response: Response = await getJSON('https://hasgeek.github.io/events/api/events.json')
return response
}
}
```
#### Automatic getter detection
```typescript
@Module
class MyModule extends VuexModule {
wheels = 2
@Mutation
incrWheels(extra) {
this.wheels += extra
}
get axles() {
return this.wheels / 2
}
}
```
this is turned into the equivalent
```javascript
const module = {
state: { wheels: 2 },
mutations: {
incrWheels(state, extra) {
state.wheels += extra
}
},
getters: {
axles: (state) => state.wheels / 2
}
}
```
### Putting into the store
Use the modules just like you would earlier
```typescript
import Vue from 'nativescript-vue'
import Vuex, { Module } from 'vuex'
import counter from './modules/Counter2'
import hgapi from './modules/HGAPIModule'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {},
modules: {
counter,
hgapi
}
})
```
### Module re-use, use with NuxtJS
If you need to support [module reuse](https://vuex.vuejs.org/guide/modules.html#module-reuse)
or to use modules with NuxtJS, you can have a state factory function generated instead
of a static state object instance by using `stateFactory` option to `@Module`, like so:
```typescript
@Module({ stateFactory: true })
class MyModule extends VuexModule {
wheels = 2
@Mutation
incrWheels(extra) {
this.wheels += extra
}
get axles() {
return this.wheels / 2
}
}
```
this is turned into the equivalent
```javascript
const module = {
state() {
return { wheels: 2 }
},
mutations: {
incrWheels(state, extra) {
state.wheels += extra
}
},
getters: {
axles: (state) => state.wheels / 2
}
}
```
### Dynamic Modules
Vuex allows us to register modules into store at runtime after store is
constructed. We can do the following to create dynamic modules
```typescript
interface StoreType {
mm: MyModule
}
// Declare empty store first
const store = new Vuex.Store<StoreType>({})
// Create module later in your code (it will register itself automatically)
// In the decorator we pass the store object into which module is injected
// NOTE: When you set dynamic true, make sure you give module a name
@Module({ dynamic: true, store: store, name: 'mm' })
class MyModule extends VuexModule {
count = 0
@Mutation
incrCount(delta) {
this.count += delta
}
}
```
If you would like to preserve the state e.g when loading in the state from [vuex-persist](https://www.npmjs.com/package/vuex-persist)
```diff
...
-- @Module({ dynamic: true, store: store, name: 'mm' })
++ @Module({ dynamic: true, store: store, name: 'mm', preserveState: true })
class MyModule extends VuexModule {
...
```
Or when it doesn't have a initial state and you load the state from the localStorage
```diff
...
-- @Module({ dynamic: true, store: store, name: 'mm' })
++ @Module({ dynamic: true, store: store, name: 'mm', preserveState: localStorage.getItem('vuex') !== null })
class MyModule extends VuexModule {
...
```
### Accessing modules with NuxtJS
There are many possible ways to construct your modules. Here is one way for drop-in use with NuxtJS (you simply need to add your modules to `~/utils/store-accessor.ts` and then just import the modules from `~/store`):
`~/store/index.ts`:
```typescript
import { Store } from 'vuex'
import { initialiseStores } from '~/utils/store-accessor'
const initializer = (store: Store<any>) => initialiseStores(store)
export const plugins = [initializer]
export * from '~/utils/store-accessor'
```
`~/utils/store-accessor.ts`:
```typescript
import { Store } from 'vuex'
import { getModule } from 'vuex-module-decorators'
import example from '~/store/example'
let exampleStore: example
function initialiseStores(store: Store<any>): void {
exampleStore = getModule(example, store)
}
export { initialiseStores, exampleStore }
```
Now you can access stores in a type-safe way by doing the following from a component or page - no extra initialization required.
```typescript
import { exampleStore } from '~/store'
...
someMethod() {
return exampleStore.exampleGetter
}
```
### Using the decorators with ServerSideRender
When SSR is involved the store is recreated on each request. Every time the module is accessed
using `getModule` function the current store instance must be provided and the module must
be manually registered to the root store modules
#### Example
```typescript
// store/modules/MyStoreModule.ts
import { Module, VuexModule, Mutation } from 'vuex-module-decorators'
@Module({
name: 'MyStoreModule',
namespaced: true,
stateFactory: true,
})
export default class MyStoreModule extends VuexModule {
public test: string = 'initial'
@Mutation
public setTest(val: string) {
this.test = val
}
}
// store/index.ts
import Vuex from 'vuex'
import MyStoreModule from '~/store/modules/MyStoreModule'
export function createStore() {
return new Vuex.Store({
modules: {
MyStoreModule,
},
}
}
// components/Random.tsx
import { Component, Vue } from 'vue-property-decorator';
import { getModule } from 'vuex-module-decorators';
import MyStoreModule from '~/store/modules/MyStoreModule'
@Component
export default class extends Vue {
public created() {
const MyModuleInstance = getModule(MyStoreModule, this.$store);
// Do stuff with module
MyModuleInstance.setTest('random')
}
}
```
+530
View File
@@ -0,0 +1,530 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Takes the properties on object from parameter source and adds them to the object
* parameter target
* @param {object} target Object to have properties copied onto from y
* @param {object} source Object with properties to be copied to x
*/
function addPropertiesToObject(target, source) {
var _loop_1 = function (k) {
Object.defineProperty(target, k, {
get: function () { return source[k]; }
});
};
for (var _i = 0, _a = Object.keys(source || {}); _i < _a.length; _i++) {
var k = _a[_i];
_loop_1(k);
}
}
/**
* Returns a namespaced name of the module to be used as a store getter
* @param module
*/
function getModuleName(module) {
if (!module._vmdModuleName) {
throw new Error("ERR_GET_MODULE_NAME : Could not get module accessor.\n Make sure your module has name, we can't make accessors for unnamed modules\n i.e. @Module({ name: 'something' })");
}
return "vuexModuleDecorators/" + module._vmdModuleName;
}
var VuexModule = /** @class */ (function () {
function VuexModule(module) {
this.actions = module.actions;
this.mutations = module.mutations;
this.state = module.state;
this.getters = module.getters;
this.namespaced = module.namespaced;
this.modules = module.modules;
}
return VuexModule;
}());
function getModule(moduleClass, store) {
var moduleName = getModuleName(moduleClass);
if (store && store.getters[moduleName]) {
return store.getters[moduleName];
}
else if (moduleClass._statics) {
return moduleClass._statics;
}
var genStatic = moduleClass._genStatic;
if (!genStatic) {
throw new Error("ERR_GET_MODULE_NO_STATICS : Could not get module accessor.\n Make sure your module has name, we can't make accessors for unnamed modules\n i.e. @Module({ name: 'something' })");
}
var storeModule = genStatic(store);
if (store) {
store.getters[moduleName] = storeModule;
}
else {
moduleClass._statics = storeModule;
}
return storeModule;
}
var reservedKeys = ['actions', 'getters', 'mutations', 'modules', 'state', 'namespaced', 'commit'];
function stateFactory(module) {
var state = new module.prototype.constructor({});
var s = {};
Object.keys(state).forEach(function (key) {
if (reservedKeys.indexOf(key) !== -1) {
if (typeof state[key] !== 'undefined') {
throw new Error("ERR_RESERVED_STATE_KEY_USED: You cannot use the following\n ['actions', 'getters', 'mutations', 'modules', 'state', 'namespaced', 'commit']\n as fields in your module. These are reserved as they have special purpose in Vuex");
}
return;
}
if (state.hasOwnProperty(key)) {
if (typeof state[key] !== 'function') {
s[key] = state[key];
}
}
});
return s;
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function staticStateGenerator(module, modOpt, statics) {
var state = modOpt.stateFactory ? module.state() : module.state;
Object.keys(state).forEach(function (key) {
if (state.hasOwnProperty(key)) {
// If not undefined or function means it is a state value
if (['undefined', 'function'].indexOf(typeof state[key]) === -1) {
Object.defineProperty(statics, key, {
get: function () {
return statics.store.state[modOpt.name][key];
}
});
}
}
});
}
function staticGetterGenerator(module, modOpt, statics) {
Object.keys(module.getters).forEach(function (key) {
if (module.namespaced) {
Object.defineProperty(statics, key, {
get: function () {
return statics.store.getters[modOpt.name + "/" + key];
}
});
}
else {
Object.defineProperty(statics, key, {
get: function () {
return statics.store.getters[key];
}
});
}
});
}
function staticMutationGenerator(module, modOpt, statics) {
Object.keys(module.mutations).forEach(function (key) {
if (module.namespaced) {
statics[key] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
(_a = statics.store).commit.apply(_a, __spreadArrays([modOpt.name + "/" + key], args));
};
}
else {
statics[key] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
(_a = statics.store).commit.apply(_a, __spreadArrays([key], args));
};
}
});
}
function staticActionGenerators(module, modOpt, statics) {
Object.keys(module.actions).forEach(function (key) {
if (module.namespaced) {
statics[key] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
return [2 /*return*/, (_a = statics.store).dispatch.apply(_a, __spreadArrays([modOpt.name + "/" + key], args))];
});
});
};
}
else {
statics[key] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
return [2 /*return*/, (_a = statics.store).dispatch.apply(_a, __spreadArrays([key], args))];
});
});
};
}
});
}
function registerDynamicModule(module, modOpt) {
if (!modOpt.name) {
throw new Error('Name of module not provided in decorator options');
}
if (!modOpt.store) {
throw new Error('Store not provided in decorator options when using dynamic option');
}
modOpt.store.registerModule(modOpt.name, // TODO: Handle nested modules too in future
module, { preserveState: modOpt.preserveState || false });
}
function moduleDecoratorFactory(moduleOptions) {
return function (constructor) {
var module = constructor;
var stateFactory$1 = function () { return stateFactory(module); };
if (!module.state) {
module.state = moduleOptions && moduleOptions.stateFactory ? stateFactory$1 : stateFactory$1();
}
if (!module.getters) {
module.getters = {};
}
if (!module.namespaced) {
module.namespaced = moduleOptions && moduleOptions.namespaced;
}
Object.getOwnPropertyNames(module.prototype).forEach(function (funcName) {
var descriptor = Object.getOwnPropertyDescriptor(module.prototype, funcName);
if (descriptor.get && module.getters) {
module.getters[funcName] = function (state, getters, rootState, rootGetters) {
var thisObj = { context: { state: state, getters: getters, rootState: rootState, rootGetters: rootGetters } };
addPropertiesToObject(thisObj, state);
addPropertiesToObject(thisObj, getters);
var got = descriptor.get.call(thisObj);
return got;
};
}
});
var modOpt = moduleOptions;
if (modOpt.name) {
Object.defineProperty(constructor, '_genStatic', {
value: function (store) {
var statics = { store: store || modOpt.store };
if (!statics.store) {
throw new Error("ERR_STORE_NOT_PROVIDED: To use getModule(), either the module\n should be decorated with store in decorator, i.e. @Module({store: store}) or\n store should be passed when calling getModule(), i.e. getModule(MyModule, this.$store)");
}
// =========== For statics ==============
// ------ state -------
staticStateGenerator(module, modOpt, statics);
// ------- getters -------
if (module.getters) {
staticGetterGenerator(module, modOpt, statics);
}
// -------- mutations --------
if (module.mutations) {
staticMutationGenerator(module, modOpt, statics);
}
// -------- actions ---------
if (module.actions) {
staticActionGenerators(module, modOpt, statics);
}
return statics;
}
});
Object.defineProperty(constructor, '_vmdModuleName', {
value: modOpt.name
});
}
if (modOpt.dynamic) {
registerDynamicModule(module, modOpt);
}
return constructor;
};
}
function Module(modOrOpt) {
if (typeof modOrOpt === 'function') {
/*
* @Module decorator called without options (directly on the class definition)
*/
moduleDecoratorFactory({})(modOrOpt);
}
else {
/*
* @Module({...}) decorator called with options
*/
return moduleDecoratorFactory(modOrOpt);
}
}
function actionDecoratorFactory(params) {
var _a = params || {}, _b = _a.commit, commit = _b === void 0 ? undefined : _b, _c = _a.rawError, rawError = _c === void 0 ? false : _c, _d = _a.root, root = _d === void 0 ? false : _d;
return function (target, key, descriptor) {
var module = target.constructor;
if (!module.hasOwnProperty('actions')) {
module.actions = Object.assign({}, module.actions);
}
var actionFunction = descriptor.value;
var action = function (context, payload) {
return __awaiter(this, void 0, void 0, function () {
var actionPayload, moduleName, moduleAccessor, thisObj, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
actionPayload = null;
if (!module._genStatic) return [3 /*break*/, 2];
moduleName = getModuleName(module);
moduleAccessor = context.rootGetters[moduleName]
? context.rootGetters[moduleName]
: getModule(module);
moduleAccessor.context = context;
return [4 /*yield*/, actionFunction.call(moduleAccessor, payload)];
case 1:
actionPayload = _a.sent();
return [3 /*break*/, 4];
case 2:
thisObj = { context: context };
addPropertiesToObject(thisObj, context.state);
addPropertiesToObject(thisObj, context.getters);
return [4 /*yield*/, actionFunction.call(thisObj, payload)];
case 3:
actionPayload = _a.sent();
_a.label = 4;
case 4:
if (commit) {
context.commit(commit, actionPayload);
}
return [2 /*return*/, actionPayload];
case 5:
e_1 = _a.sent();
throw rawError
? e_1
: new Error('ERR_ACTION_ACCESS_UNDEFINED: Are you trying to access ' +
'this.someMutation() or this.someGetter inside an @Action? \n' +
'That works only in dynamic modules. \n' +
'If not dynamic use this.context.commit("mutationName", payload) ' +
'and this.context.getters["getterName"]' +
'\n' +
new Error("Could not perform action " + key.toString()).stack +
'\n' +
e_1.stack);
case 6: return [2 /*return*/];
}
});
});
};
module.actions[key] = root ? { root: root, handler: action } : action;
};
}
/**
* The @Action decorator turns an async function into an Vuex action
*
* @param targetOrParams the module class
* @param key name of the action
* @param descriptor the action function descriptor
* @constructor
*/
function Action(targetOrParams, key, descriptor) {
if (!key && !descriptor) {
/*
* This is the case when `targetOrParams` is params.
* i.e. when used as -
* <pre>
@Action({commit: 'incrCount'})
async getCountDelta() {
return 5
}
* </pre>
*/
return actionDecoratorFactory(targetOrParams);
}
else {
/*
* This is the case when @Action is called on action function
* without any params
* <pre>
* @Action
* async doSomething() {
* ...
* }
* </pre>
*/
actionDecoratorFactory()(targetOrParams, key, descriptor);
}
}
function Mutation(target, key, descriptor) {
var module = target.constructor;
if (!module.hasOwnProperty('mutations')) {
module.mutations = Object.assign({}, module.mutations);
}
var mutationFunction = descriptor.value;
var mutation = function (state, payload) {
mutationFunction.call(state, payload);
};
module.mutations[key] = mutation;
}
function mutationActionDecoratorFactory(params) {
return function (target, key, descriptor) {
var module = target.constructor;
if (!module.hasOwnProperty('mutations')) {
module.mutations = Object.assign({}, module.mutations);
}
if (!module.hasOwnProperty('actions')) {
module.actions = Object.assign({}, module.actions);
}
var mutactFunction = descriptor.value;
var action = function (context, payload) {
return __awaiter(this, void 0, void 0, function () {
var actionPayload, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, mutactFunction.call(context, payload)];
case 1:
actionPayload = _a.sent();
context.commit(key, actionPayload);
return [3 /*break*/, 3];
case 2:
e_1 = _a.sent();
if (params.rawError) {
throw e_1;
}
else {
console.error('Could not perform action ' + key.toString());
console.error(e_1);
return [2 /*return*/, Promise.reject(e_1)];
}
case 3: return [2 /*return*/];
}
});
});
};
var mutation = function (state, payload) {
if (!params.mutate) {
params.mutate = Object.keys(payload);
}
for (var _i = 0, _a = params.mutate; _i < _a.length; _i++) {
var stateItem = _a[_i];
if (state.hasOwnProperty(stateItem) && payload.hasOwnProperty(stateItem)) {
state[stateItem] = payload[stateItem];
}
else {
throw new Error("ERR_MUTATE_PARAMS_NOT_IN_PAYLOAD\n In @MutationAction, mutate: ['a', 'b', ...] array keys must\n match with return type = {a: {}, b: {}, ...} and must\n also be in state.");
}
}
};
module.actions[key] = params.root ? { root: true, handler: action } : action;
module.mutations[key] = mutation;
};
}
/**
* The @MutationAction decorator turns this into an action that further calls a mutation
* Both the action and the mutation are generated for you
*
* @param paramsOrTarget the params or the target class
* @param key the name of the function
* @param descriptor the function body
* @constructor
*/
function MutationAction(paramsOrTarget, key, descriptor) {
if (!key && !descriptor) {
/*
* This is the case when `paramsOrTarget` is params.
* i.e. when used as -
* <pre>
@MutationAction({mutate: ['incrCount']})
async getCountDelta() {
return {incrCount: 5}
}
* </pre>
*/
return mutationActionDecoratorFactory(paramsOrTarget);
}
else {
/*
* This is the case when `paramsOrTarget` is target.
* i.e. when used as -
* <pre>
@MutationAction
async getCountDelta() {
return {incrCount: 5}
}
* </pre>
*/
mutationActionDecoratorFactory({})(paramsOrTarget, key, descriptor);
}
}
exports.Action = Action;
exports.Module = Module;
exports.Mutation = Mutation;
exports.MutationAction = MutationAction;
exports.VuexModule = VuexModule;
exports.getModule = getModule;
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+521
View File
@@ -0,0 +1,521 @@
/**
* Takes the properties on object from parameter source and adds them to the object
* parameter target
* @param {object} target Object to have properties copied onto from y
* @param {object} source Object with properties to be copied to x
*/
function addPropertiesToObject(target, source) {
var _loop_1 = function (k) {
Object.defineProperty(target, k, {
get: function () { return source[k]; }
});
};
for (var _i = 0, _a = Object.keys(source || {}); _i < _a.length; _i++) {
var k = _a[_i];
_loop_1(k);
}
}
/**
* Returns a namespaced name of the module to be used as a store getter
* @param module
*/
function getModuleName(module) {
if (!module._vmdModuleName) {
throw new Error("ERR_GET_MODULE_NAME : Could not get module accessor.\n Make sure your module has name, we can't make accessors for unnamed modules\n i.e. @Module({ name: 'something' })");
}
return "vuexModuleDecorators/" + module._vmdModuleName;
}
var VuexModule = /** @class */ (function () {
function VuexModule(module) {
this.actions = module.actions;
this.mutations = module.mutations;
this.state = module.state;
this.getters = module.getters;
this.namespaced = module.namespaced;
this.modules = module.modules;
}
return VuexModule;
}());
function getModule(moduleClass, store) {
var moduleName = getModuleName(moduleClass);
if (store && store.getters[moduleName]) {
return store.getters[moduleName];
}
else if (moduleClass._statics) {
return moduleClass._statics;
}
var genStatic = moduleClass._genStatic;
if (!genStatic) {
throw new Error("ERR_GET_MODULE_NO_STATICS : Could not get module accessor.\n Make sure your module has name, we can't make accessors for unnamed modules\n i.e. @Module({ name: 'something' })");
}
var storeModule = genStatic(store);
if (store) {
store.getters[moduleName] = storeModule;
}
else {
moduleClass._statics = storeModule;
}
return storeModule;
}
var reservedKeys = ['actions', 'getters', 'mutations', 'modules', 'state', 'namespaced', 'commit'];
function stateFactory(module) {
var state = new module.prototype.constructor({});
var s = {};
Object.keys(state).forEach(function (key) {
if (reservedKeys.indexOf(key) !== -1) {
if (typeof state[key] !== 'undefined') {
throw new Error("ERR_RESERVED_STATE_KEY_USED: You cannot use the following\n ['actions', 'getters', 'mutations', 'modules', 'state', 'namespaced', 'commit']\n as fields in your module. These are reserved as they have special purpose in Vuex");
}
return;
}
if (state.hasOwnProperty(key)) {
if (typeof state[key] !== 'function') {
s[key] = state[key];
}
}
});
return s;
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function staticStateGenerator(module, modOpt, statics) {
var state = modOpt.stateFactory ? module.state() : module.state;
Object.keys(state).forEach(function (key) {
if (state.hasOwnProperty(key)) {
// If not undefined or function means it is a state value
if (['undefined', 'function'].indexOf(typeof state[key]) === -1) {
Object.defineProperty(statics, key, {
get: function () {
return statics.store.state[modOpt.name][key];
}
});
}
}
});
}
function staticGetterGenerator(module, modOpt, statics) {
Object.keys(module.getters).forEach(function (key) {
if (module.namespaced) {
Object.defineProperty(statics, key, {
get: function () {
return statics.store.getters[modOpt.name + "/" + key];
}
});
}
else {
Object.defineProperty(statics, key, {
get: function () {
return statics.store.getters[key];
}
});
}
});
}
function staticMutationGenerator(module, modOpt, statics) {
Object.keys(module.mutations).forEach(function (key) {
if (module.namespaced) {
statics[key] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
(_a = statics.store).commit.apply(_a, __spreadArrays([modOpt.name + "/" + key], args));
};
}
else {
statics[key] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
(_a = statics.store).commit.apply(_a, __spreadArrays([key], args));
};
}
});
}
function staticActionGenerators(module, modOpt, statics) {
Object.keys(module.actions).forEach(function (key) {
if (module.namespaced) {
statics[key] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
return [2 /*return*/, (_a = statics.store).dispatch.apply(_a, __spreadArrays([modOpt.name + "/" + key], args))];
});
});
};
}
else {
statics[key] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
return [2 /*return*/, (_a = statics.store).dispatch.apply(_a, __spreadArrays([key], args))];
});
});
};
}
});
}
function registerDynamicModule(module, modOpt) {
if (!modOpt.name) {
throw new Error('Name of module not provided in decorator options');
}
if (!modOpt.store) {
throw new Error('Store not provided in decorator options when using dynamic option');
}
modOpt.store.registerModule(modOpt.name, // TODO: Handle nested modules too in future
module, { preserveState: modOpt.preserveState || false });
}
function moduleDecoratorFactory(moduleOptions) {
return function (constructor) {
var module = constructor;
var stateFactory$1 = function () { return stateFactory(module); };
if (!module.state) {
module.state = moduleOptions && moduleOptions.stateFactory ? stateFactory$1 : stateFactory$1();
}
if (!module.getters) {
module.getters = {};
}
if (!module.namespaced) {
module.namespaced = moduleOptions && moduleOptions.namespaced;
}
Object.getOwnPropertyNames(module.prototype).forEach(function (funcName) {
var descriptor = Object.getOwnPropertyDescriptor(module.prototype, funcName);
if (descriptor.get && module.getters) {
module.getters[funcName] = function (state, getters, rootState, rootGetters) {
var thisObj = { context: { state: state, getters: getters, rootState: rootState, rootGetters: rootGetters } };
addPropertiesToObject(thisObj, state);
addPropertiesToObject(thisObj, getters);
var got = descriptor.get.call(thisObj);
return got;
};
}
});
var modOpt = moduleOptions;
if (modOpt.name) {
Object.defineProperty(constructor, '_genStatic', {
value: function (store) {
var statics = { store: store || modOpt.store };
if (!statics.store) {
throw new Error("ERR_STORE_NOT_PROVIDED: To use getModule(), either the module\n should be decorated with store in decorator, i.e. @Module({store: store}) or\n store should be passed when calling getModule(), i.e. getModule(MyModule, this.$store)");
}
// =========== For statics ==============
// ------ state -------
staticStateGenerator(module, modOpt, statics);
// ------- getters -------
if (module.getters) {
staticGetterGenerator(module, modOpt, statics);
}
// -------- mutations --------
if (module.mutations) {
staticMutationGenerator(module, modOpt, statics);
}
// -------- actions ---------
if (module.actions) {
staticActionGenerators(module, modOpt, statics);
}
return statics;
}
});
Object.defineProperty(constructor, '_vmdModuleName', {
value: modOpt.name
});
}
if (modOpt.dynamic) {
registerDynamicModule(module, modOpt);
}
return constructor;
};
}
function Module(modOrOpt) {
if (typeof modOrOpt === 'function') {
/*
* @Module decorator called without options (directly on the class definition)
*/
moduleDecoratorFactory({})(modOrOpt);
}
else {
/*
* @Module({...}) decorator called with options
*/
return moduleDecoratorFactory(modOrOpt);
}
}
function actionDecoratorFactory(params) {
var _a = params || {}, _b = _a.commit, commit = _b === void 0 ? undefined : _b, _c = _a.rawError, rawError = _c === void 0 ? false : _c, _d = _a.root, root = _d === void 0 ? false : _d;
return function (target, key, descriptor) {
var module = target.constructor;
if (!module.hasOwnProperty('actions')) {
module.actions = Object.assign({}, module.actions);
}
var actionFunction = descriptor.value;
var action = function (context, payload) {
return __awaiter(this, void 0, void 0, function () {
var actionPayload, moduleName, moduleAccessor, thisObj, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
actionPayload = null;
if (!module._genStatic) return [3 /*break*/, 2];
moduleName = getModuleName(module);
moduleAccessor = context.rootGetters[moduleName]
? context.rootGetters[moduleName]
: getModule(module);
moduleAccessor.context = context;
return [4 /*yield*/, actionFunction.call(moduleAccessor, payload)];
case 1:
actionPayload = _a.sent();
return [3 /*break*/, 4];
case 2:
thisObj = { context: context };
addPropertiesToObject(thisObj, context.state);
addPropertiesToObject(thisObj, context.getters);
return [4 /*yield*/, actionFunction.call(thisObj, payload)];
case 3:
actionPayload = _a.sent();
_a.label = 4;
case 4:
if (commit) {
context.commit(commit, actionPayload);
}
return [2 /*return*/, actionPayload];
case 5:
e_1 = _a.sent();
throw rawError
? e_1
: new Error('ERR_ACTION_ACCESS_UNDEFINED: Are you trying to access ' +
'this.someMutation() or this.someGetter inside an @Action? \n' +
'That works only in dynamic modules. \n' +
'If not dynamic use this.context.commit("mutationName", payload) ' +
'and this.context.getters["getterName"]' +
'\n' +
new Error("Could not perform action " + key.toString()).stack +
'\n' +
e_1.stack);
case 6: return [2 /*return*/];
}
});
});
};
module.actions[key] = root ? { root: root, handler: action } : action;
};
}
/**
* The @Action decorator turns an async function into an Vuex action
*
* @param targetOrParams the module class
* @param key name of the action
* @param descriptor the action function descriptor
* @constructor
*/
function Action(targetOrParams, key, descriptor) {
if (!key && !descriptor) {
/*
* This is the case when `targetOrParams` is params.
* i.e. when used as -
* <pre>
@Action({commit: 'incrCount'})
async getCountDelta() {
return 5
}
* </pre>
*/
return actionDecoratorFactory(targetOrParams);
}
else {
/*
* This is the case when @Action is called on action function
* without any params
* <pre>
* @Action
* async doSomething() {
* ...
* }
* </pre>
*/
actionDecoratorFactory()(targetOrParams, key, descriptor);
}
}
function Mutation(target, key, descriptor) {
var module = target.constructor;
if (!module.hasOwnProperty('mutations')) {
module.mutations = Object.assign({}, module.mutations);
}
var mutationFunction = descriptor.value;
var mutation = function (state, payload) {
mutationFunction.call(state, payload);
};
module.mutations[key] = mutation;
}
function mutationActionDecoratorFactory(params) {
return function (target, key, descriptor) {
var module = target.constructor;
if (!module.hasOwnProperty('mutations')) {
module.mutations = Object.assign({}, module.mutations);
}
if (!module.hasOwnProperty('actions')) {
module.actions = Object.assign({}, module.actions);
}
var mutactFunction = descriptor.value;
var action = function (context, payload) {
return __awaiter(this, void 0, void 0, function () {
var actionPayload, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, mutactFunction.call(context, payload)];
case 1:
actionPayload = _a.sent();
context.commit(key, actionPayload);
return [3 /*break*/, 3];
case 2:
e_1 = _a.sent();
if (params.rawError) {
throw e_1;
}
else {
console.error('Could not perform action ' + key.toString());
console.error(e_1);
return [2 /*return*/, Promise.reject(e_1)];
}
case 3: return [2 /*return*/];
}
});
});
};
var mutation = function (state, payload) {
if (!params.mutate) {
params.mutate = Object.keys(payload);
}
for (var _i = 0, _a = params.mutate; _i < _a.length; _i++) {
var stateItem = _a[_i];
if (state.hasOwnProperty(stateItem) && payload.hasOwnProperty(stateItem)) {
state[stateItem] = payload[stateItem];
}
else {
throw new Error("ERR_MUTATE_PARAMS_NOT_IN_PAYLOAD\n In @MutationAction, mutate: ['a', 'b', ...] array keys must\n match with return type = {a: {}, b: {}, ...} and must\n also be in state.");
}
}
};
module.actions[key] = params.root ? { root: true, handler: action } : action;
module.mutations[key] = mutation;
};
}
/**
* The @MutationAction decorator turns this into an action that further calls a mutation
* Both the action and the mutation are generated for you
*
* @param paramsOrTarget the params or the target class
* @param key the name of the function
* @param descriptor the function body
* @constructor
*/
function MutationAction(paramsOrTarget, key, descriptor) {
if (!key && !descriptor) {
/*
* This is the case when `paramsOrTarget` is params.
* i.e. when used as -
* <pre>
@MutationAction({mutate: ['incrCount']})
async getCountDelta() {
return {incrCount: 5}
}
* </pre>
*/
return mutationActionDecoratorFactory(paramsOrTarget);
}
else {
/*
* This is the case when `paramsOrTarget` is target.
* i.e. when used as -
* <pre>
@MutationAction
async getCountDelta() {
return {incrCount: 5}
}
* </pre>
*/
mutationActionDecoratorFactory({})(paramsOrTarget, key, descriptor);
}
}
export { Action, Module, Mutation, MutationAction, VuexModule, getModule };
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
/**
* Parameters that can be passed to the @Action decorator
*/
export interface ActionDecoratorParams {
commit?: string;
rawError?: boolean;
root?: boolean;
}
export declare function Action<T, R>(target: T, key: string | symbol, descriptor: TypedPropertyDescriptor<(...args: any[]) => R>): void;
export declare function Action<T>(params: ActionDecoratorParams): MethodDecorator;
+12
View File
@@ -0,0 +1,12 @@
/**
* Takes the properties on object from parameter source and adds them to the object
* parameter target
* @param {object} target Object to have properties copied onto from y
* @param {object} source Object with properties to be copied to x
*/
export declare function addPropertiesToObject(target: any, source: any): void;
/**
* Returns a namespaced name of the module to be used as a store getter
* @param module
*/
export declare function getModuleName(module: any): string;
+5
View File
@@ -0,0 +1,5 @@
export { VuexModule, getModule } from './vuexmodule';
export { Module } from './module';
export { Action } from './action';
export { Mutation } from './mutation';
export { MutationAction } from './mutationaction';
+4
View File
@@ -0,0 +1,4 @@
import { Module as Mod } from 'vuex';
import { ModuleOptions } from '../moduleoptions';
export declare function Module<S>(module: Function & Mod<S, any>): void;
export declare function Module<S>(options: ModuleOptions): ClassDecorator;
@@ -0,0 +1,2 @@
import { Module as Mod } from 'vuex';
export declare function stateFactory<S>(module: Function & Mod<S, any>): S;
@@ -0,0 +1,6 @@
import { Module as Mod } from 'vuex';
import { DynamicModuleOptions } from '../moduleoptions';
export declare function staticStateGenerator<S extends Object>(module: Function & Mod<S, any>, modOpt: DynamicModuleOptions, statics: any): void;
export declare function staticGetterGenerator<S>(module: Function & Mod<S, any>, modOpt: DynamicModuleOptions, statics: any): void;
export declare function staticMutationGenerator<S>(module: Function & Mod<S, any>, modOpt: DynamicModuleOptions, statics: any): void;
export declare function staticActionGenerators<S>(module: Function & Mod<S, any>, modOpt: DynamicModuleOptions, statics: any): void;
+45
View File
@@ -0,0 +1,45 @@
import { Store } from 'vuex';
/**
* Options to pass to the @Module decorator
*/
export interface StaticModuleOptions {
/**
* name of module, if being namespaced
*/
name?: string;
/**
* whether or not the module is namespaced
*/
namespaced?: boolean;
/**
* Whether to generate a plain state object, or a state factory for the module
*/
stateFactory?: boolean;
}
export interface DynamicModuleOptions {
/**
* If this is a dynamic module (added to store after store is created)
*/
dynamic: true;
/**
* The store into which this module will be injected
*/
store: Store<any>;
/**
* name of module, compulsory for dynamic modules
*/
name: string;
/**
* If this is enabled it will preserve the state when loading the module
*/
preserveState?: boolean;
/**
* whether or not the module is namespaced
*/
namespaced?: boolean;
/**
* Whether to generate a plain state object, or a state factory for the module
*/
stateFactory?: boolean;
}
export declare type ModuleOptions = StaticModuleOptions | DynamicModuleOptions;
+1
View File
@@ -0,0 +1 @@
export declare function Mutation<T extends Object, R>(target: T, key: string | symbol, descriptor: TypedPropertyDescriptor<(...args: any[]) => R>): void;
+9
View File
@@ -0,0 +1,9 @@
export interface MutationActionParams<M> {
mutate?: (keyof Partial<M>)[];
rawError?: boolean;
root?: boolean;
}
export declare function MutationAction<K, T extends K>(target: {
[k in keyof T]: T[k] | null;
}, key: string | symbol, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<K>>): void;
export declare function MutationAction<T>(params: MutationActionParams<T>): (target: T, key: string | symbol, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<T>>) => void;
+22
View File
@@ -0,0 +1,22 @@
import { ActionTree, GetterTree, Module as Mod, ModuleTree, MutationTree, Store, ActionContext } from 'vuex';
export declare class VuexModule<S = ThisType<any>, R = any> implements Mod<S, R> {
static namespaced?: boolean;
static state?: any | (() => any);
static getters?: GetterTree<any, any>;
static actions?: ActionTree<any, any>;
static mutations?: MutationTree<any>;
static modules?: ModuleTree<any>;
modules?: ModuleTree<any>;
namespaced?: boolean;
getters?: GetterTree<S, R>;
state?: S | (() => S);
mutations?: MutationTree<S>;
actions?: ActionTree<S, R>;
context: ActionContext<S, R>;
constructor(module: Mod<S, any>);
}
declare type ConstructorOf<C> = {
new (...args: any[]): C;
};
export declare function getModule<M extends VuexModule>(moduleClass: ConstructorOf<M>, store?: Store<any>): M;
export {};
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
{
"_args": [
[
"vuex-module-decorators@0.16.1",
"/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series"
]
],
"_from": "vuex-module-decorators@0.16.1",
"_id": "vuex-module-decorators@0.16.1",
"_inBundle": false,
"_integrity": "sha512-Zz8HF2rMoDYf78uOBbWCq8wGFFo7YyNWc10Yj2eScKxVoRMla9HnFpiqvI3Dm0cLyOnBBklCn1AFUys62BZGAw==",
"_location": "/vuex-module-decorators",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "vuex-module-decorators@0.16.1",
"name": "vuex-module-decorators",
"escapedName": "vuex-module-decorators",
"rawSpec": "0.16.1",
"saveSpec": null,
"fetchSpec": "0.16.1"
},
"_requiredBy": [
"/nuxt-property-decorator"
],
"_resolved": "https://registry.npmjs.org/vuex-module-decorators/-/vuex-module-decorators-0.16.1.tgz",
"_spec": "0.16.1",
"_where": "/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series",
"author": {
"name": "Arnav Gupta",
"email": "arnav@codingblocks.com"
},
"bugs": {
"url": "https://github.com/championswimmer/vuex-module-decorators/issues"
},
"dependencies": {},
"description": "Decorators to make class-like Vuex modules",
"devDependencies": {
"@types/chai": "^4.1.7",
"@types/mocha": "^5.2.5",
"chai": "^4.2.0",
"mocha": "^5.2.0",
"mock-local-storage": "^1.1.8",
"nyc": "^13.2.0",
"prettier": "^1.16.4",
"rimraf": "^2.6.3",
"rollup": "^1.19.4",
"rollup-plugin-typescript2": "^0.25.3",
"rollup-plugin-uglify": "^6.0.2",
"ts-node": "^8.6.2",
"tslib": "^1.10.0",
"tslint": "^6.0.0",
"tslint-config-prettier": "^1.18.0",
"tslint-config-standard": "^9.0.0",
"tslint-plugin-prettier": "^2.0.1",
"typescript": "^3.5.3",
"vue": "^2.6.10",
"vuepress": "^1.0.3",
"vuex": "^3.1.1",
"vuex-persist": "^2.2.0"
},
"engines": {
"node": ">= 8",
"npm": ">= 5",
"yarn": ">= 1"
},
"homepage": "https://github.com/championswimmer/vuex-module-decorators#readme",
"keywords": [
"vuex",
"vue",
"typescript",
"decorators"
],
"license": "MIT",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"name": "vuex-module-decorators",
"peerDependencies": {
"vue": ">=2",
"vuex": "3"
},
"repository": {
"type": "git",
"url": "git+https://github.com/championswimmer/vuex-module-decorators.git"
},
"scripts": {
"build": "rollup -c",
"clean": "rimraf dist .rpt2_cache",
"cover": "nyc npm test",
"distclean": "rimraf .nyc_output coverage dist .rpt2_cache",
"docs:build": "vuepress build docs",
"docs:serve": "vuepress dev docs",
"lint": "tslint -p tsconfig.json",
"lint:fix": "tslint -p tsconfig.json --fix",
"prebuild": "npm run clean",
"prepublishOnly": "npm run build",
"prereport": "npm run cover",
"pretest": "npm run build && npm run lint",
"report": "nyc report --reporter lcov --reporter html",
"test": "cd test && mocha -r ts-node/register \"**/*.ts\"",
"test:dirty": "cd test && mocha -r ts-node/register \"**/*.ts\""
},
"types": "dist/types/index.d.ts",
"typings": "dist/types/index.d.ts",
"version": "0.16.1"
}
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"module": "es2015",
"target": "es5",
"moduleResolution": "node",
"lib": [
"dom", "es2015"
],
"importHelpers": true,
"sourceMap": true,
"declaration": true,
"declarationDir": "dist/types",
"rootDir": "src",
"outDir": "dist",
"sourceRoot": "src",
"strict": true,
"removeComments": false,
"strictNullChecks": true
},
"include": [
"src"
],
"exclude": [
"node_modules",
"test"
]
}
+19
View File
@@ -0,0 +1,19 @@
{
"defaultSeverity": "error",
"extends": ["tslint-config-standard", "tslint-config-prettier"],
"jsRules": {},
"rules": {
"prettier": [
true,
{
"semi": false,
"arrowParens": "always",
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100
}
],
"radix": false
},
"rulesDirectory": ["tslint-plugin-prettier"]
}