Initial commit

This commit is contained in:
Dmitriy Pleshevskiy 2019-10-11 10:54:07 +03:00
commit 60f5763b8b
8 changed files with 5238 additions and 0 deletions

95
.gitignore vendored Normal file
View file

@ -0,0 +1,95 @@
# Created by https://www.gitignore.io/api/vim,node
# Edit at https://www.gitignore.io/?templates=vim,node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
### Vim ###
# Swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]
# Session
Session.vim
Sessionx.vim
# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~
# End of https://www.gitignore.io/api/vim,node
# IDE
.idea/
.c9/
# build artifacts
src/**/*.js
src/**/*.d.ts
# in development
.travis*

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 IceTemple
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.

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# IT FSM
Simple finite state machine

8
jest.config.js Normal file
View file

@ -0,0 +1,8 @@
module.exports = {
testRegex: 'tests/.*\\.spec\\.ts',
testEnvironment: 'node',
preset: 'ts-jest',
moduleFileExtensions: ['ts', 'js', 'json'],
collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],
};

4953
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

44
package.json Normal file
View file

@ -0,0 +1,44 @@
{
"name": "it-fsm",
"version": "1.0.2",
"description": "Simple finite state machine for nodejs",
"main": "./src/index.js",
"types": "./src/index.d.ts",
"readme": "README.md",
"files": [
"src",
"!*.spec.ts",
"!*.ts",
"*.d.ts"
],
"scripts": {
"test": "jest",
"prepublishOnly": "tsc",
"report-coverage": "cat coverage/lcov.info | coveralls"
},
"repository": {
"type": "git",
"url": "git+https://github.com/icetemple/npm-it-fsm.git"
},
"keywords": [
"fsm",
"finite",
"state",
"machine",
"icetemple",
"it"
],
"author": "Dmitriy Pleshevskiy <dmitriy@ideascup.me>",
"license": "MIT",
"bugs": {
"url": "https://github.com/icetemple/npm-it-fsm/issues"
},
"homepage": "https://github.com/icetemple/npm-it-fsm#readme",
"devDependencies": {
"@types/jest": "^24.0.15",
"coveralls": "^3.0.5",
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"
}
}

88
src/index.ts Normal file
View file

@ -0,0 +1,88 @@
export type Payload = Record<string, any>
export type SystemEvent = (event: string, fromState: string, toState: string,
payload: Payload) => Promise<any>
export interface StateEvents {
[key: string]: string
}
export class StateMachine {
[key: string]: any;
private _currentState: string;
private _onEnter: SystemEvent;
private _eventsByState: Record<string, Record<string, (payload: Payload) => any>> = {};
private _statesByState: Record<string, string[]> = {};
constructor(initial: string, config: Record<string, StateEvents | SystemEvent>) {
this._currentState = initial;
for (let fromState in config) {
if (fromState === 'onEnter') {
this._onEnter = config.onEnter as SystemEvent;
continue
}
this._statesByState[fromState] = [];
let events = config[fromState] as StateEvents;
for (let eventName in events) {
let toState: string = events[eventName];
this._statesByState[fromState].push(toState);
this._initChangeState(eventName, fromState, toState)
}
}
}
private _initChangeState(eventName: string, fromState: string, toState: string): void {
if (!this._eventsByState[fromState]) {
this._eventsByState[fromState] = {};
}
this._eventsByState[fromState][eventName] = async (payload: Payload = {}) => {
if (this._currentState !== fromState) {
return;
}
await this._onEnter(eventName, fromState, toState, payload);
this._currentState = toState;
return this;
};
if (!this[eventName]) {
this[eventName] = async (payload: Payload = {}) => {
if (this._eventsByState[this._currentState]
&& this._eventsByState[this._currentState][eventName]) {
return this._eventsByState[this._currentState][eventName](payload);
}
}
}
}
public getCurrentState(): string {
return this._currentState;
}
public can(eventName: string): boolean {
const events = this._eventsByState[this._currentState];
if (!events) {
return false;
}
return Object.keys(events).includes(eventName);
}
public canToState(stateName: string) {
const states = this._statesByState[this._currentState];
if (!states) {
return false;
}
return states.includes(stateName);
}
}

26
tsconfig.json Normal file
View file

@ -0,0 +1,26 @@
{
"compilerOptions": {
"allowJs": false,
"lib": [
"dom",
"es7"
],
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"target": "es6",
"charset": "utf-8",
"pretty": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedParameters": true,
"strictNullChecks": true,
"outDir": "./src"
},
"exclude": [
"node_modules",
"coverage",
"tests"
]
}