fsm-light v1.0.2
fsm-light
A lightweight, easy-to-use finite state machine (FSM) for managing entity status transitions in JavaScript/TypeScript projects.
Table of Contents
Introduction
fsm-light is a simple, lightweight library for implementing finite state machines in JavaScript or TypeScript. It helps you define the possible transitions of an entity between states (statuses) in a clean, declarative way. You can easily check whether a transition can be performed and then execute that transition.
Features
- Lightweight: Minimal overhead, easy to integrate.
- TypeScript Support: Includes type definitions.
- Declarative Transitions: Clearly define
from
andto
states for each action. - Readable and Maintainable: Centralized state transition logic.
- CJM, ESM support: Supports both CommonJS and ES modules.
Installation
npm install fsm-light
Or with Yarn:
yarn add fsm-light
Usage
Import StateMachine
:
import StateMachine from 'fsm-light';
Create a new instance of StateMachine
by providing a definition object:
const userFsm = new StateMachine({
initial: 'invited',
transitions: {
activate: { from: ['blocked', 'archived'], to: 'active' },
archive: { from: ['active'], to: 'archived' },
block: { from: ['active', 'archived'], to: 'blocked' },
signUp: { from: ['invited'], to: 'active' }
}
});
Create an entity and transition its status:
(The entity has to respond to status
!!!)
const user = new User({
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
status: 'active'
});
user.status // 'active'
userFsm.can(user, 'archive') // true
userFsm.can(user, 'activate') // false
userFsm.transit(user, 'archive')
user.status // 'archived'
License
This project is licensed under the MIT License.
Package URL
https://www.npmjs.com/package/fsm-light
Code repository
https://bitbucket.org/endeavia/fsm-light/src/master/