@axi-engine/states 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,132 @@
1
+ let _axi_engine_utils = require("@axi-engine/utils");
2
+
3
+ //#region src/state-machine.ts
4
+ /**
5
+ * A minimal, type-safe finite state machine.
6
+ * It manages states, transitions, and associated lifecycle hooks (`onEnter`, `onExit`).
7
+ *
8
+ * @template T The type used for state identifiers (e.g., a string or an enum).
9
+ * @template P The default payload type for state handlers. Can be overridden per state.
10
+ * @example
11
+ * enum PlayerState { Idle, Walk, Run }
12
+ *
13
+ * const playerFsm = new StateMachine<PlayerState>();
14
+ *
15
+ * playerFsm.register(PlayerState.Idle, () => console.log('Player is now idle.'));
16
+ * playerFsm.register(PlayerState.Walk, () => console.log('Player is walking.'));
17
+ *
18
+ * async function start() {
19
+ * await playerFsm.call(PlayerState.Idle);
20
+ * await playerFsm.call(PlayerState.Walk);
21
+ * }
22
+ */
23
+ var StateMachine = class {
24
+ /**
25
+ * @protected
26
+ * The internal representation of the current state.
27
+ */
28
+ _state;
29
+ /**
30
+ * @protected
31
+ * A map storing all registered state configurations.
32
+ */
33
+ states = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Public emitter that fires an event whenever the state changes.
36
+ * The event provides the old state, the new state, and the payload.
37
+ * @see Emitter
38
+ * @example
39
+ * fsm.onChange.subscribe((from, to, payload) => {
40
+ * console.log(`State transitioned from ${from} to ${to}`);
41
+ * });
42
+ */
43
+ onChange = new _axi_engine_utils.Emitter();
44
+ /**
45
+ * Gets the current state of the machine.
46
+ * @returns The current state identifier, or `undefined` if the machine has not been started.
47
+ */
48
+ get state() {
49
+ return this._state;
50
+ }
51
+ /**
52
+ * Registers a state and its associated handler or configuration.
53
+ * If a handler is already registered for the given state, it will be overwritten.
54
+ *
55
+ * @param state The identifier for the state to register.
56
+ * @param handler A handler function (`onEnter`) or a full configuration object.
57
+ * @example
58
+ * // Simple registration
59
+ * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
60
+ *
61
+ * // Advanced registration
62
+ * fsm.register(MyState.Walking, {
63
+ * onEnter: () => console.log('Start walking animation'),
64
+ * onExit: () => console.log('Stop walking animation'),
65
+ * allowedFrom: [MyState.Idle]
66
+ * });
67
+ */
68
+ register(state, handler) {
69
+ if ((0, _axi_engine_utils.isUndefined)(handler) || typeof handler === "function") this.states.set(state, { onEnter: handler });
70
+ else this.states.set(state, handler);
71
+ }
72
+ /**
73
+ * Transitions the machine to a new state.
74
+ * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
75
+ * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
76
+ *
77
+ * @param newState The identifier of the state to transition to.
78
+ * @param payload An optional payload to pass to the new state's `onEnter` handler.
79
+ * @returns A promise that resolves when the transition is complete.
80
+ * @throws {Error} if the `newState` has not been registered.
81
+ * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
82
+ * @example
83
+ * try {
84
+ * await fsm.call(PlayerState.Run, { speed: 10 });
85
+ * } catch (e) {
86
+ * console.error('State transition failed:', e.message);
87
+ * }
88
+ */
89
+ async call(newState, payload) {
90
+ const oldState = this._state;
91
+ const oldStateConfig = this._state ? this.states.get(this._state) : void 0;
92
+ const newStateConfig = this.states.get(newState);
93
+ (0, _axi_engine_utils.throwIfEmpty)(newStateConfig, `State ${String(newState)} is not registered.`);
94
+ (0, _axi_engine_utils.throwIf)(!(0, _axi_engine_utils.isNullOrUndefined)(newStateConfig.allowedFrom) && !(0, _axi_engine_utils.isNullOrUndefined)(oldState) && !newStateConfig.allowedFrom.includes(oldState), `Transition from ${String(oldState)} to ${String(newState)} is not allowed.`);
95
+ await oldStateConfig?.onExit?.();
96
+ this._state = newState;
97
+ await newStateConfig.onEnter?.(payload);
98
+ this.onChange.emit(oldState, newState, payload);
99
+ }
100
+ /**
101
+ * Removes a single state configuration from the machine.
102
+ * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
103
+ *
104
+ * @param state The identifier of the state to remove.
105
+ * @returns `true` if the state was found and removed, otherwise `false`.
106
+ * @example
107
+ * fsm.register(MyState.Temp, () => {});
108
+ * // ...
109
+ * const wasRemoved = fsm.unregister(MyState.Temp);
110
+ * console.log('Temporary state removed:', wasRemoved);
111
+ */
112
+ unregister(state) {
113
+ if (this._state === state) this._state = void 0;
114
+ return this.states.delete(state);
115
+ }
116
+ /**
117
+ * Removes all registered states and resets the machine to its initial, undefined state.
118
+ * This does not clear `onChange` subscribers.
119
+ * @example
120
+ * fsm.register(MyState.One);
121
+ * fsm.register(MyState.Two);
122
+ * // ...
123
+ * fsm.clear(); // The machine is now empty.
124
+ */
125
+ clear() {
126
+ this.states.clear();
127
+ this._state = void 0;
128
+ }
129
+ };
130
+
131
+ //#endregion
132
+ exports.StateMachine = StateMachine;
@@ -0,0 +1,120 @@
1
+ import { Emitter } from "@axi-engine/utils";
2
+
3
+ //#region src/state-handler.d.ts
4
+ type StateHandler<P = void> = P extends void ? () => void | Promise<void> : (payload: P) => void | Promise<void>;
5
+ interface StateHandlerConfig<T, P = void> {
6
+ onEnter?: StateHandler<P>;
7
+ onExit?: () => void | Promise<void>;
8
+ allowedFrom?: T[];
9
+ }
10
+ type StateHandlerRegistration<T, P = void> = StateHandler<P> | StateHandlerConfig<T, P>;
11
+ //#endregion
12
+ //#region src/state-machine.d.ts
13
+ /**
14
+ * A minimal, type-safe finite state machine.
15
+ * It manages states, transitions, and associated lifecycle hooks (`onEnter`, `onExit`).
16
+ *
17
+ * @template T The type used for state identifiers (e.g., a string or an enum).
18
+ * @template P The default payload type for state handlers. Can be overridden per state.
19
+ * @example
20
+ * enum PlayerState { Idle, Walk, Run }
21
+ *
22
+ * const playerFsm = new StateMachine<PlayerState>();
23
+ *
24
+ * playerFsm.register(PlayerState.Idle, () => console.log('Player is now idle.'));
25
+ * playerFsm.register(PlayerState.Walk, () => console.log('Player is walking.'));
26
+ *
27
+ * async function start() {
28
+ * await playerFsm.call(PlayerState.Idle);
29
+ * await playerFsm.call(PlayerState.Walk);
30
+ * }
31
+ */
32
+ declare class StateMachine<T, P = void> {
33
+ /**
34
+ * @protected
35
+ * The internal representation of the current state.
36
+ */
37
+ protected _state?: T;
38
+ /**
39
+ * @protected
40
+ * A map storing all registered state configurations.
41
+ */
42
+ protected states: Map<T, StateHandlerConfig<T, P> | undefined>;
43
+ /**
44
+ * Public emitter that fires an event whenever the state changes.
45
+ * The event provides the old state, the new state, and the payload.
46
+ * @see Emitter
47
+ * @example
48
+ * fsm.onChange.subscribe((from, to, payload) => {
49
+ * console.log(`State transitioned from ${from} to ${to}`);
50
+ * });
51
+ */
52
+ readonly onChange: Emitter<[from?: T | undefined, to?: T | undefined, payload?: P | undefined]>;
53
+ /**
54
+ * Gets the current state of the machine.
55
+ * @returns The current state identifier, or `undefined` if the machine has not been started.
56
+ */
57
+ get state(): T | undefined;
58
+ /**
59
+ * Registers a state and its associated handler or configuration.
60
+ * If a handler is already registered for the given state, it will be overwritten.
61
+ *
62
+ * @param state The identifier for the state to register.
63
+ * @param handler A handler function (`onEnter`) or a full configuration object.
64
+ * @example
65
+ * // Simple registration
66
+ * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
67
+ *
68
+ * // Advanced registration
69
+ * fsm.register(MyState.Walking, {
70
+ * onEnter: () => console.log('Start walking animation'),
71
+ * onExit: () => console.log('Stop walking animation'),
72
+ * allowedFrom: [MyState.Idle]
73
+ * });
74
+ */
75
+ register(state: T, handler?: StateHandlerRegistration<T, P>): void;
76
+ /**
77
+ * Transitions the machine to a new state.
78
+ * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
79
+ * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
80
+ *
81
+ * @param newState The identifier of the state to transition to.
82
+ * @param payload An optional payload to pass to the new state's `onEnter` handler.
83
+ * @returns A promise that resolves when the transition is complete.
84
+ * @throws {Error} if the `newState` has not been registered.
85
+ * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
86
+ * @example
87
+ * try {
88
+ * await fsm.call(PlayerState.Run, { speed: 10 });
89
+ * } catch (e) {
90
+ * console.error('State transition failed:', e.message);
91
+ * }
92
+ */
93
+ call(newState: T, payload?: P): Promise<void>;
94
+ /**
95
+ * Removes a single state configuration from the machine.
96
+ * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
97
+ *
98
+ * @param state The identifier of the state to remove.
99
+ * @returns `true` if the state was found and removed, otherwise `false`.
100
+ * @example
101
+ * fsm.register(MyState.Temp, () => {});
102
+ * // ...
103
+ * const wasRemoved = fsm.unregister(MyState.Temp);
104
+ * console.log('Temporary state removed:', wasRemoved);
105
+ */
106
+ unregister(state: T): boolean;
107
+ /**
108
+ * Removes all registered states and resets the machine to its initial, undefined state.
109
+ * This does not clear `onChange` subscribers.
110
+ * @example
111
+ * fsm.register(MyState.One);
112
+ * fsm.register(MyState.Two);
113
+ * // ...
114
+ * fsm.clear(); // The machine is now empty.
115
+ */
116
+ clear(): void;
117
+ }
118
+ //#endregion
119
+ export { StateHandler, StateHandlerConfig, StateHandlerRegistration, StateMachine };
120
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/state-handler.ts","../src/state-machine.ts"],"mappings":";;;KAAY,YAAA,aACV,CAAA,6BACe,OAAA,UAAA,OAAA,EACD,CAAA,YAAa,OAAA;AAAA,UAGZ,kBAAA;EAAA,OAAA,GACL,YAAA,CAAa,CAAA;EAAA,MAAA,gBACD,OAAA;EAAA,WAAA,GACR,CAAA;AAAA;AAAA,KAGJ,wBAAA,gBAAwC,YAAA,CAAa,CAAA,IAAK,kBAAA,CAAmB,CAAA,EAAG,CAAA;;;;ACW5F;;;;;;;;;;;;;;;;;;cAAa,YAAA;EAAA;;;;EAAA,UAAA,MAAA,GAKQ,CAAA;EAAA;;;;EAAA,UAAA,MAAA,EAMD,GAAA,CAAI,CAAA,EAAG,kBAAA,CAAmB,CAAA,EAAG,CAAA;EAAA;;;;;;;;;EAAA,SAAA,QAAA,EAW9B,OAAA,EAAA,IAAA,GAAA,CAAA,cAAA,EAAA,GAAA,CAAA,cAAA,OAAA,GAAA,CAAA;EAAA;;;;EAAA,IAAA,MAAA,GAMJ,CAAA;EAAA;;;;;;;;;;;;;;;;;EAAA,SAAA,KAAA,EAqBG,CAAA,EAAA,OAAA,GAAa,wBAAA,CAAyB,CAAA,EAAG,CAAA;EAAA;;;;;;;;;;;;;;;;;EAAA,KAAA,QAAA,EAyBpC,CAAA,EAAA,OAAA,GAAa,CAAA,GAAI,OAAA;EAAA;;;;;;;;;;;;EAAA,WAAA,KAAA,EAmCpB,CAAA;EAAA;;;;;;;;;EAAA,MAAA;AAAA"}
package/dist/index.d.mts CHANGED
@@ -1,13 +1,15 @@
1
- import { Emitter } from '@axi-engine/utils';
1
+ import { Emitter } from "@axi-engine/utils";
2
2
 
3
+ //#region src/state-handler.d.ts
3
4
  type StateHandler<P = void> = P extends void ? () => void | Promise<void> : (payload: P) => void | Promise<void>;
4
5
  interface StateHandlerConfig<T, P = void> {
5
- onEnter?: StateHandler<P>;
6
- onExit?: () => void | Promise<void>;
7
- allowedFrom?: T[];
6
+ onEnter?: StateHandler<P>;
7
+ onExit?: () => void | Promise<void>;
8
+ allowedFrom?: T[];
8
9
  }
9
10
  type StateHandlerRegistration<T, P = void> = StateHandler<P> | StateHandlerConfig<T, P>;
10
-
11
+ //#endregion
12
+ //#region src/state-machine.d.ts
11
13
  /**
12
14
  * A minimal, type-safe finite state machine.
13
15
  * It manages states, transitions, and associated lifecycle hooks (`onEnter`, `onExit`).
@@ -28,90 +30,91 @@ type StateHandlerRegistration<T, P = void> = StateHandler<P> | StateHandlerConfi
28
30
  * }
29
31
  */
30
32
  declare class StateMachine<T, P = void> {
31
- /**
32
- * @protected
33
- * The internal representation of the current state.
34
- */
35
- protected _state?: T;
36
- /**
37
- * @protected
38
- * A map storing all registered state configurations.
39
- */
40
- protected states: Map<T, StateHandlerConfig<T, P> | undefined>;
41
- /**
42
- * Public emitter that fires an event whenever the state changes.
43
- * The event provides the old state, the new state, and the payload.
44
- * @see Emitter
45
- * @example
46
- * fsm.onChange.subscribe((from, to, payload) => {
47
- * console.log(`State transitioned from ${from} to ${to}`);
48
- * });
49
- */
50
- readonly onChange: Emitter<[from?: T | undefined, to?: T | undefined, payload?: P | undefined]>;
51
- /**
52
- * Gets the current state of the machine.
53
- * @returns The current state identifier, or `undefined` if the machine has not been started.
54
- */
55
- get state(): T | undefined;
56
- /**
57
- * Registers a state and its associated handler or configuration.
58
- * If a handler is already registered for the given state, it will be overwritten.
59
- *
60
- * @param state The identifier for the state to register.
61
- * @param handler A handler function (`onEnter`) or a full configuration object.
62
- * @example
63
- * // Simple registration
64
- * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
65
- *
66
- * // Advanced registration
67
- * fsm.register(MyState.Walking, {
68
- * onEnter: () => console.log('Start walking animation'),
69
- * onExit: () => console.log('Stop walking animation'),
70
- * allowedFrom: [MyState.Idle]
71
- * });
72
- */
73
- register(state: T, handler?: StateHandlerRegistration<T, P>): void;
74
- /**
75
- * Transitions the machine to a new state.
76
- * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
77
- * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
78
- *
79
- * @param newState The identifier of the state to transition to.
80
- * @param payload An optional payload to pass to the new state's `onEnter` handler.
81
- * @returns A promise that resolves when the transition is complete.
82
- * @throws {Error} if the `newState` has not been registered.
83
- * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
84
- * @example
85
- * try {
86
- * await fsm.call(PlayerState.Run, { speed: 10 });
87
- * } catch (e) {
88
- * console.error('State transition failed:', e.message);
89
- * }
90
- */
91
- call(newState: T, payload?: P): Promise<void>;
92
- /**
93
- * Removes a single state configuration from the machine.
94
- * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
95
- *
96
- * @param state The identifier of the state to remove.
97
- * @returns `true` if the state was found and removed, otherwise `false`.
98
- * @example
99
- * fsm.register(MyState.Temp, () => {});
100
- * // ...
101
- * const wasRemoved = fsm.unregister(MyState.Temp);
102
- * console.log('Temporary state removed:', wasRemoved);
103
- */
104
- unregister(state: T): boolean;
105
- /**
106
- * Removes all registered states and resets the machine to its initial, undefined state.
107
- * This does not clear `onChange` subscribers.
108
- * @example
109
- * fsm.register(MyState.One);
110
- * fsm.register(MyState.Two);
111
- * // ...
112
- * fsm.clear(); // The machine is now empty.
113
- */
114
- clear(): void;
33
+ /**
34
+ * @protected
35
+ * The internal representation of the current state.
36
+ */
37
+ protected _state?: T;
38
+ /**
39
+ * @protected
40
+ * A map storing all registered state configurations.
41
+ */
42
+ protected states: Map<T, StateHandlerConfig<T, P> | undefined>;
43
+ /**
44
+ * Public emitter that fires an event whenever the state changes.
45
+ * The event provides the old state, the new state, and the payload.
46
+ * @see Emitter
47
+ * @example
48
+ * fsm.onChange.subscribe((from, to, payload) => {
49
+ * console.log(`State transitioned from ${from} to ${to}`);
50
+ * });
51
+ */
52
+ readonly onChange: Emitter<[from?: T | undefined, to?: T | undefined, payload?: P | undefined]>;
53
+ /**
54
+ * Gets the current state of the machine.
55
+ * @returns The current state identifier, or `undefined` if the machine has not been started.
56
+ */
57
+ get state(): T | undefined;
58
+ /**
59
+ * Registers a state and its associated handler or configuration.
60
+ * If a handler is already registered for the given state, it will be overwritten.
61
+ *
62
+ * @param state The identifier for the state to register.
63
+ * @param handler A handler function (`onEnter`) or a full configuration object.
64
+ * @example
65
+ * // Simple registration
66
+ * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
67
+ *
68
+ * // Advanced registration
69
+ * fsm.register(MyState.Walking, {
70
+ * onEnter: () => console.log('Start walking animation'),
71
+ * onExit: () => console.log('Stop walking animation'),
72
+ * allowedFrom: [MyState.Idle]
73
+ * });
74
+ */
75
+ register(state: T, handler?: StateHandlerRegistration<T, P>): void;
76
+ /**
77
+ * Transitions the machine to a new state.
78
+ * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
79
+ * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
80
+ *
81
+ * @param newState The identifier of the state to transition to.
82
+ * @param payload An optional payload to pass to the new state's `onEnter` handler.
83
+ * @returns A promise that resolves when the transition is complete.
84
+ * @throws {Error} if the `newState` has not been registered.
85
+ * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
86
+ * @example
87
+ * try {
88
+ * await fsm.call(PlayerState.Run, { speed: 10 });
89
+ * } catch (e) {
90
+ * console.error('State transition failed:', e.message);
91
+ * }
92
+ */
93
+ call(newState: T, payload?: P): Promise<void>;
94
+ /**
95
+ * Removes a single state configuration from the machine.
96
+ * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
97
+ *
98
+ * @param state The identifier of the state to remove.
99
+ * @returns `true` if the state was found and removed, otherwise `false`.
100
+ * @example
101
+ * fsm.register(MyState.Temp, () => {});
102
+ * // ...
103
+ * const wasRemoved = fsm.unregister(MyState.Temp);
104
+ * console.log('Temporary state removed:', wasRemoved);
105
+ */
106
+ unregister(state: T): boolean;
107
+ /**
108
+ * Removes all registered states and resets the machine to its initial, undefined state.
109
+ * This does not clear `onChange` subscribers.
110
+ * @example
111
+ * fsm.register(MyState.One);
112
+ * fsm.register(MyState.Two);
113
+ * // ...
114
+ * fsm.clear(); // The machine is now empty.
115
+ */
116
+ clear(): void;
115
117
  }
116
-
117
- export { type StateHandler, type StateHandlerConfig, type StateHandlerRegistration, StateMachine };
118
+ //#endregion
119
+ export { StateHandler, StateHandlerConfig, StateHandlerRegistration, StateMachine };
120
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/state-handler.ts","../src/state-machine.ts"],"mappings":";;;KAAY,YAAA,aACV,CAAA,6BACe,OAAA,UAAA,OAAA,EACD,CAAA,YAAa,OAAA;AAAA,UAGZ,kBAAA;EAAA,OAAA,GACL,YAAA,CAAa,CAAA;EAAA,MAAA,gBACD,OAAA;EAAA,WAAA,GACR,CAAA;AAAA;AAAA,KAGJ,wBAAA,gBAAwC,YAAA,CAAa,CAAA,IAAK,kBAAA,CAAmB,CAAA,EAAG,CAAA;;;;ACW5F;;;;;;;;;;;;;;;;;;cAAa,YAAA;EAAA;;;;EAAA,UAAA,MAAA,GAKQ,CAAA;EAAA;;;;EAAA,UAAA,MAAA,EAMD,GAAA,CAAI,CAAA,EAAG,kBAAA,CAAmB,CAAA,EAAG,CAAA;EAAA;;;;;;;;;EAAA,SAAA,QAAA,EAW9B,OAAA,EAAA,IAAA,GAAA,CAAA,cAAA,EAAA,GAAA,CAAA,cAAA,OAAA,GAAA,CAAA;EAAA;;;;EAAA,IAAA,MAAA,GAMJ,CAAA;EAAA;;;;;;;;;;;;;;;;;EAAA,SAAA,KAAA,EAqBG,CAAA,EAAA,OAAA,GAAa,wBAAA,CAAyB,CAAA,EAAG,CAAA;EAAA;;;;;;;;;;;;;;;;;EAAA,KAAA,QAAA,EAyBpC,CAAA,EAAA,OAAA,GAAa,CAAA,GAAI,OAAA;EAAA;;;;;;;;;;;;EAAA,WAAA,KAAA,EAmCpB,CAAA;EAAA;;;;;;;;;EAAA,MAAA;AAAA"}
package/dist/index.mjs CHANGED
@@ -1,117 +1,133 @@
1
- // src/state-machine.ts
2
1
  import { Emitter, isNullOrUndefined, isUndefined, throwIf, throwIfEmpty } from "@axi-engine/utils";
2
+
3
+ //#region src/state-machine.ts
4
+ /**
5
+ * A minimal, type-safe finite state machine.
6
+ * It manages states, transitions, and associated lifecycle hooks (`onEnter`, `onExit`).
7
+ *
8
+ * @template T The type used for state identifiers (e.g., a string or an enum).
9
+ * @template P The default payload type for state handlers. Can be overridden per state.
10
+ * @example
11
+ * enum PlayerState { Idle, Walk, Run }
12
+ *
13
+ * const playerFsm = new StateMachine<PlayerState>();
14
+ *
15
+ * playerFsm.register(PlayerState.Idle, () => console.log('Player is now idle.'));
16
+ * playerFsm.register(PlayerState.Walk, () => console.log('Player is walking.'));
17
+ *
18
+ * async function start() {
19
+ * await playerFsm.call(PlayerState.Idle);
20
+ * await playerFsm.call(PlayerState.Walk);
21
+ * }
22
+ */
3
23
  var StateMachine = class {
4
- constructor() {
5
- /**
6
- * @protected
7
- * A map storing all registered state configurations.
8
- */
9
- this.states = /* @__PURE__ */ new Map();
10
- /**
11
- * Public emitter that fires an event whenever the state changes.
12
- * The event provides the old state, the new state, and the payload.
13
- * @see Emitter
14
- * @example
15
- * fsm.onChange.subscribe((from, to, payload) => {
16
- * console.log(`State transitioned from ${from} to ${to}`);
17
- * });
18
- */
19
- this.onChange = new Emitter();
20
- }
21
- /**
22
- * Gets the current state of the machine.
23
- * @returns The current state identifier, or `undefined` if the machine has not been started.
24
- */
25
- get state() {
26
- return this._state;
27
- }
28
- /**
29
- * Registers a state and its associated handler or configuration.
30
- * If a handler is already registered for the given state, it will be overwritten.
31
- *
32
- * @param state The identifier for the state to register.
33
- * @param handler A handler function (`onEnter`) or a full configuration object.
34
- * @example
35
- * // Simple registration
36
- * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
37
- *
38
- * // Advanced registration
39
- * fsm.register(MyState.Walking, {
40
- * onEnter: () => console.log('Start walking animation'),
41
- * onExit: () => console.log('Stop walking animation'),
42
- * allowedFrom: [MyState.Idle]
43
- * });
44
- */
45
- register(state, handler) {
46
- if (isUndefined(handler) || typeof handler === "function") {
47
- this.states.set(state, { onEnter: handler });
48
- } else {
49
- this.states.set(state, handler);
50
- }
51
- }
52
- /**
53
- * Transitions the machine to a new state.
54
- * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
55
- * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
56
- *
57
- * @param newState The identifier of the state to transition to.
58
- * @param payload An optional payload to pass to the new state's `onEnter` handler.
59
- * @returns A promise that resolves when the transition is complete.
60
- * @throws {Error} if the `newState` has not been registered.
61
- * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
62
- * @example
63
- * try {
64
- * await fsm.call(PlayerState.Run, { speed: 10 });
65
- * } catch (e) {
66
- * console.error('State transition failed:', e.message);
67
- * }
68
- */
69
- async call(newState, payload) {
70
- const oldState = this._state;
71
- const oldStateConfig = this._state ? this.states.get(this._state) : void 0;
72
- const newStateConfig = this.states.get(newState);
73
- throwIfEmpty(newStateConfig, `State ${String(newState)} is not registered.`);
74
- throwIf(
75
- !isNullOrUndefined(newStateConfig.allowedFrom) && !isNullOrUndefined(oldState) && !newStateConfig.allowedFrom.includes(oldState),
76
- `Transition from ${String(oldState)} to ${String(newState)} is not allowed.`
77
- );
78
- await oldStateConfig?.onExit?.();
79
- this._state = newState;
80
- await newStateConfig.onEnter?.(payload);
81
- this.onChange.emit(oldState, newState, payload);
82
- }
83
- /**
84
- * Removes a single state configuration from the machine.
85
- * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
86
- *
87
- * @param state The identifier of the state to remove.
88
- * @returns `true` if the state was found and removed, otherwise `false`.
89
- * @example
90
- * fsm.register(MyState.Temp, () => {});
91
- * // ...
92
- * const wasRemoved = fsm.unregister(MyState.Temp);
93
- * console.log('Temporary state removed:', wasRemoved);
94
- */
95
- unregister(state) {
96
- if (this._state === state) {
97
- this._state = void 0;
98
- }
99
- return this.states.delete(state);
100
- }
101
- /**
102
- * Removes all registered states and resets the machine to its initial, undefined state.
103
- * This does not clear `onChange` subscribers.
104
- * @example
105
- * fsm.register(MyState.One);
106
- * fsm.register(MyState.Two);
107
- * // ...
108
- * fsm.clear(); // The machine is now empty.
109
- */
110
- clear() {
111
- this.states.clear();
112
- this._state = void 0;
113
- }
114
- };
115
- export {
116
- StateMachine
24
+ /**
25
+ * @protected
26
+ * The internal representation of the current state.
27
+ */
28
+ _state;
29
+ /**
30
+ * @protected
31
+ * A map storing all registered state configurations.
32
+ */
33
+ states = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Public emitter that fires an event whenever the state changes.
36
+ * The event provides the old state, the new state, and the payload.
37
+ * @see Emitter
38
+ * @example
39
+ * fsm.onChange.subscribe((from, to, payload) => {
40
+ * console.log(`State transitioned from ${from} to ${to}`);
41
+ * });
42
+ */
43
+ onChange = new Emitter();
44
+ /**
45
+ * Gets the current state of the machine.
46
+ * @returns The current state identifier, or `undefined` if the machine has not been started.
47
+ */
48
+ get state() {
49
+ return this._state;
50
+ }
51
+ /**
52
+ * Registers a state and its associated handler or configuration.
53
+ * If a handler is already registered for the given state, it will be overwritten.
54
+ *
55
+ * @param state The identifier for the state to register.
56
+ * @param handler A handler function (`onEnter`) or a full configuration object.
57
+ * @example
58
+ * // Simple registration
59
+ * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
60
+ *
61
+ * // Advanced registration
62
+ * fsm.register(MyState.Walking, {
63
+ * onEnter: () => console.log('Start walking animation'),
64
+ * onExit: () => console.log('Stop walking animation'),
65
+ * allowedFrom: [MyState.Idle]
66
+ * });
67
+ */
68
+ register(state, handler) {
69
+ if (isUndefined(handler) || typeof handler === "function") this.states.set(state, { onEnter: handler });
70
+ else this.states.set(state, handler);
71
+ }
72
+ /**
73
+ * Transitions the machine to a new state.
74
+ * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
75
+ * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
76
+ *
77
+ * @param newState The identifier of the state to transition to.
78
+ * @param payload An optional payload to pass to the new state's `onEnter` handler.
79
+ * @returns A promise that resolves when the transition is complete.
80
+ * @throws {Error} if the `newState` has not been registered.
81
+ * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
82
+ * @example
83
+ * try {
84
+ * await fsm.call(PlayerState.Run, { speed: 10 });
85
+ * } catch (e) {
86
+ * console.error('State transition failed:', e.message);
87
+ * }
88
+ */
89
+ async call(newState, payload) {
90
+ const oldState = this._state;
91
+ const oldStateConfig = this._state ? this.states.get(this._state) : void 0;
92
+ const newStateConfig = this.states.get(newState);
93
+ throwIfEmpty(newStateConfig, `State ${String(newState)} is not registered.`);
94
+ throwIf(!isNullOrUndefined(newStateConfig.allowedFrom) && !isNullOrUndefined(oldState) && !newStateConfig.allowedFrom.includes(oldState), `Transition from ${String(oldState)} to ${String(newState)} is not allowed.`);
95
+ await oldStateConfig?.onExit?.();
96
+ this._state = newState;
97
+ await newStateConfig.onEnter?.(payload);
98
+ this.onChange.emit(oldState, newState, payload);
99
+ }
100
+ /**
101
+ * Removes a single state configuration from the machine.
102
+ * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
103
+ *
104
+ * @param state The identifier of the state to remove.
105
+ * @returns `true` if the state was found and removed, otherwise `false`.
106
+ * @example
107
+ * fsm.register(MyState.Temp, () => {});
108
+ * // ...
109
+ * const wasRemoved = fsm.unregister(MyState.Temp);
110
+ * console.log('Temporary state removed:', wasRemoved);
111
+ */
112
+ unregister(state) {
113
+ if (this._state === state) this._state = void 0;
114
+ return this.states.delete(state);
115
+ }
116
+ /**
117
+ * Removes all registered states and resets the machine to its initial, undefined state.
118
+ * This does not clear `onChange` subscribers.
119
+ * @example
120
+ * fsm.register(MyState.One);
121
+ * fsm.register(MyState.Two);
122
+ * // ...
123
+ * fsm.clear(); // The machine is now empty.
124
+ */
125
+ clear() {
126
+ this.states.clear();
127
+ this._state = void 0;
128
+ }
117
129
  };
130
+
131
+ //#endregion
132
+ export { StateMachine };
133
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/state-machine.ts"],"sourcesContent":["import {StateHandlerConfig, StateHandlerRegistration} from \"./state-handler\";\r\nimport {Emitter, isNullOrUndefined, isUndefined, throwIf, throwIfEmpty} from '@axi-engine/utils';\r\n\r\n\r\n/**\r\n * A minimal, type-safe finite state machine.\r\n * It manages states, transitions, and associated lifecycle hooks (`onEnter`, `onExit`).\r\n *\r\n * @template T The type used for state identifiers (e.g., a string or an enum).\r\n * @template P The default payload type for state handlers. Can be overridden per state.\r\n * @example\r\n * enum PlayerState { Idle, Walk, Run }\r\n *\r\n * const playerFsm = new StateMachine<PlayerState>();\r\n *\r\n * playerFsm.register(PlayerState.Idle, () => console.log('Player is now idle.'));\r\n * playerFsm.register(PlayerState.Walk, () => console.log('Player is walking.'));\r\n *\r\n * async function start() {\r\n * await playerFsm.call(PlayerState.Idle);\r\n * await playerFsm.call(PlayerState.Walk);\r\n * }\r\n */\r\nexport class StateMachine<T, P = void> {\r\n /**\r\n * @protected\r\n * The internal representation of the current state.\r\n */\r\n protected _state?: T;\r\n\r\n /**\r\n * @protected\r\n * A map storing all registered state configurations.\r\n */\r\n protected states: Map<T, StateHandlerConfig<T, P> | undefined> = new Map();\r\n\r\n /**\r\n * Public emitter that fires an event whenever the state changes.\r\n * The event provides the old state, the new state, and the payload.\r\n * @see Emitter\r\n * @example\r\n * fsm.onChange.subscribe((from, to, payload) => {\r\n * console.log(`State transitioned from ${from} to ${to}`);\r\n * });\r\n */\r\n readonly onChange = new Emitter<[from?: T, to?: T, payload?: P]>();\r\n\r\n /**\r\n * Gets the current state of the machine.\r\n * @returns The current state identifier, or `undefined` if the machine has not been started.\r\n */\r\n get state(): T | undefined {\r\n return this._state;\r\n }\r\n\r\n /**\r\n * Registers a state and its associated handler or configuration.\r\n * If a handler is already registered for the given state, it will be overwritten.\r\n *\r\n * @param state The identifier for the state to register.\r\n * @param handler A handler function (`onEnter`) or a full configuration object.\r\n * @example\r\n * // Simple registration\r\n * fsm.register(MyState.Idle, () => console.log('Entering Idle'));\r\n *\r\n * // Advanced registration\r\n * fsm.register(MyState.Walking, {\r\n * onEnter: () => console.log('Start walking animation'),\r\n * onExit: () => console.log('Stop walking animation'),\r\n * allowedFrom: [MyState.Idle]\r\n * });\r\n */\r\n register(state: T, handler?: StateHandlerRegistration<T, P>): void {\r\n if (isUndefined(handler) || typeof handler === 'function') {\r\n this.states.set(state, {onEnter: handler});\r\n } else {\r\n this.states.set(state, handler);\r\n }\r\n }\r\n\r\n /**\r\n * Transitions the machine to a new state.\r\n * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.\r\n * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.\r\n *\r\n * @param newState The identifier of the state to transition to.\r\n * @param payload An optional payload to pass to the new state's `onEnter` handler.\r\n * @returns A promise that resolves when the transition is complete.\r\n * @throws {Error} if the `newState` has not been registered.\r\n * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.\r\n * @example\r\n * try {\r\n * await fsm.call(PlayerState.Run, { speed: 10 });\r\n * } catch (e) {\r\n * console.error('State transition failed:', e.message);\r\n * }\r\n */\r\n async call(newState: T, payload?: P): Promise<void> {\r\n const oldState = this._state;\r\n const oldStateConfig = this._state ? this.states.get(this._state) : undefined;\r\n const newStateConfig = this.states.get(newState);\r\n\r\n throwIfEmpty(newStateConfig, `State ${String(newState)} is not registered.`);\r\n\r\n throwIf(\r\n !isNullOrUndefined(newStateConfig.allowedFrom) &&\r\n !isNullOrUndefined(oldState) &&\r\n !newStateConfig.allowedFrom.includes(oldState),\r\n `Transition from ${String(oldState)} to ${String(newState)} is not allowed.`\r\n );\r\n\r\n await oldStateConfig?.onExit?.();\r\n\r\n this._state = newState;\r\n\r\n await (newStateConfig.onEnter as (payload?: P) => void | Promise<void>)?.(payload);\r\n\r\n this.onChange.emit(oldState, newState, payload);\r\n }\r\n\r\n /**\r\n * Removes a single state configuration from the machine.\r\n * If the removed state is the currently active one, the machine's state will be reset to `undefined`.\r\n *\r\n * @param state The identifier of the state to remove.\r\n * @returns `true` if the state was found and removed, otherwise `false`.\r\n * @example\r\n * fsm.register(MyState.Temp, () => {});\r\n * // ...\r\n * const wasRemoved = fsm.unregister(MyState.Temp);\r\n * console.log('Temporary state removed:', wasRemoved);\r\n */\r\n unregister(state: T): boolean {\r\n if (this._state === state) {\r\n this._state = undefined;\r\n }\r\n return this.states.delete(state);\r\n }\r\n\r\n /**\r\n * Removes all registered states and resets the machine to its initial, undefined state.\r\n * This does not clear `onChange` subscribers.\r\n * @example\r\n * fsm.register(MyState.One);\r\n * fsm.register(MyState.Two);\r\n * // ...\r\n * fsm.clear(); // The machine is now empty.\r\n */\r\n clear(): void {\r\n this.states.clear();\r\n this._state = undefined;\r\n }\r\n}\r\n\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,eAAb,MAAuC;;;;;CAKrC,AAAU;;;;;CAMV,AAAU,yBAAuD,IAAI,KAAK;;;;;;;;;;CAW1E,AAAS,WAAW,IAAI,SAA0C;;;;;CAMlE,IAAI,QAAuB;AACzB,SAAO,KAAK;;;;;;;;;;;;;;;;;;;CAoBd,SAAS,OAAU,SAAgD;AACjE,MAAI,YAAY,QAAQ,IAAI,OAAO,YAAY,WAC7C,MAAK,OAAO,IAAI,OAAO,EAAC,SAAS,SAAQ,CAAC;MAE1C,MAAK,OAAO,IAAI,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;CAqBnC,MAAM,KAAK,UAAa,SAA4B;EAClD,MAAM,WAAW,KAAK;EACtB,MAAM,iBAAiB,KAAK,SAAS,KAAK,OAAO,IAAI,KAAK,OAAO,GAAG;EACpE,MAAM,iBAAiB,KAAK,OAAO,IAAI,SAAS;AAEhD,eAAa,gBAAgB,SAAS,OAAO,SAAS,CAAC,qBAAqB;AAE5E,UACE,CAAC,kBAAkB,eAAe,YAAY,IAC9C,CAAC,kBAAkB,SAAS,IAC5B,CAAC,eAAe,YAAY,SAAS,SAAS,EAC9C,mBAAmB,OAAO,SAAS,CAAC,MAAM,OAAO,SAAS,CAAC,kBAC5D;AAED,QAAM,gBAAgB,UAAU;AAEhC,OAAK,SAAS;AAEd,QAAO,eAAe,UAAoD,QAAQ;AAElF,OAAK,SAAS,KAAK,UAAU,UAAU,QAAQ;;;;;;;;;;;;;;CAejD,WAAW,OAAmB;AAC5B,MAAI,KAAK,WAAW,MAClB,MAAK,SAAS;AAEhB,SAAO,KAAK,OAAO,OAAO,MAAM;;;;;;;;;;;CAYlC,QAAc;AACZ,OAAK,OAAO,OAAO;AACnB,OAAK,SAAS"}
package/package.json CHANGED
@@ -1,39 +1,47 @@
1
- {
2
- "name": "@axi-engine/states",
3
- "version": "0.1.0",
4
- "description": "A minimal, type-safe state machine for the Axi Engine, designed for managing game logic and component states with a simple API.",
5
- "license": "MIT",
6
- "keywords": [
7
- "axi-engine",
8
- "typescript",
9
- "gamedev",
10
- "game-development",
11
- "game-engine",
12
- "state-machine",
13
- "finite-state-machine",
14
- "fsm",
15
- "state-management",
16
- "events"
17
- ],
18
- "types": "./dist/index.d.ts",
19
- "main": "./dist/index.js",
20
- "module": "./dist/index.mjs",
21
- "exports": {
22
- ".": {
23
- "types": "./dist/index.d.ts",
24
- "import": "./dist/index.mjs",
25
- "require": "./dist/index.js"
26
- }
27
- },
28
- "scripts": {
29
- "build": "tsup",
30
- "docs": "typedoc src/index.ts --out docs/api --options ../../typedoc.json",
31
- "test": "echo 'No tests yet for @axi-engine/states'"
32
- },
33
- "files": [
34
- "dist"
35
- ],
36
- "dependencies": {
37
- "@axi-engine/utils": "^0.1.5"
38
- }
39
- }
1
+ {
2
+ "name": "@axi-engine/states",
3
+ "version": "0.1.2",
4
+ "description": "A minimal, type-safe state machine for the Axi Engine, designed for managing game logic and component states with a simple API.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/axijs/engine.git",
9
+ "directory": "packages/states"
10
+ },
11
+ "keywords": [
12
+ "axi-engine",
13
+ "typescript",
14
+ "gamedev",
15
+ "game-development",
16
+ "game-engine",
17
+ "state-machine",
18
+ "finite-state-machine",
19
+ "fsm",
20
+ "state-management",
21
+ "events"
22
+ ],
23
+ "types": "./dist/index.d.ts",
24
+ "main": "./dist/index.js",
25
+ "module": "./dist/index.mjs",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.mjs",
30
+ "require": "./dist/index.js"
31
+ }
32
+ },
33
+ "scripts": {
34
+ "build": "tsdown",
35
+ "docs": "typedoc src/index.ts --out docs/api --options ../../typedoc.json",
36
+ "test": "echo 'No tests yet for @axi-engine/states'"
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "devDependencies": {
42
+ "@axi-engine/utils": "^0.1.6"
43
+ },
44
+ "peerDependencies": {
45
+ "@axi-engine/utils": "^0.1.6"
46
+ }
47
+ }
package/dist/index.d.ts DELETED
@@ -1,117 +0,0 @@
1
- import { Emitter } from '@axi-engine/utils';
2
-
3
- type StateHandler<P = void> = P extends void ? () => void | Promise<void> : (payload: P) => void | Promise<void>;
4
- interface StateHandlerConfig<T, P = void> {
5
- onEnter?: StateHandler<P>;
6
- onExit?: () => void | Promise<void>;
7
- allowedFrom?: T[];
8
- }
9
- type StateHandlerRegistration<T, P = void> = StateHandler<P> | StateHandlerConfig<T, P>;
10
-
11
- /**
12
- * A minimal, type-safe finite state machine.
13
- * It manages states, transitions, and associated lifecycle hooks (`onEnter`, `onExit`).
14
- *
15
- * @template T The type used for state identifiers (e.g., a string or an enum).
16
- * @template P The default payload type for state handlers. Can be overridden per state.
17
- * @example
18
- * enum PlayerState { Idle, Walk, Run }
19
- *
20
- * const playerFsm = new StateMachine<PlayerState>();
21
- *
22
- * playerFsm.register(PlayerState.Idle, () => console.log('Player is now idle.'));
23
- * playerFsm.register(PlayerState.Walk, () => console.log('Player is walking.'));
24
- *
25
- * async function start() {
26
- * await playerFsm.call(PlayerState.Idle);
27
- * await playerFsm.call(PlayerState.Walk);
28
- * }
29
- */
30
- declare class StateMachine<T, P = void> {
31
- /**
32
- * @protected
33
- * The internal representation of the current state.
34
- */
35
- protected _state?: T;
36
- /**
37
- * @protected
38
- * A map storing all registered state configurations.
39
- */
40
- protected states: Map<T, StateHandlerConfig<T, P> | undefined>;
41
- /**
42
- * Public emitter that fires an event whenever the state changes.
43
- * The event provides the old state, the new state, and the payload.
44
- * @see Emitter
45
- * @example
46
- * fsm.onChange.subscribe((from, to, payload) => {
47
- * console.log(`State transitioned from ${from} to ${to}`);
48
- * });
49
- */
50
- readonly onChange: Emitter<[from?: T | undefined, to?: T | undefined, payload?: P | undefined]>;
51
- /**
52
- * Gets the current state of the machine.
53
- * @returns The current state identifier, or `undefined` if the machine has not been started.
54
- */
55
- get state(): T | undefined;
56
- /**
57
- * Registers a state and its associated handler or configuration.
58
- * If a handler is already registered for the given state, it will be overwritten.
59
- *
60
- * @param state The identifier for the state to register.
61
- * @param handler A handler function (`onEnter`) or a full configuration object.
62
- * @example
63
- * // Simple registration
64
- * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
65
- *
66
- * // Advanced registration
67
- * fsm.register(MyState.Walking, {
68
- * onEnter: () => console.log('Start walking animation'),
69
- * onExit: () => console.log('Stop walking animation'),
70
- * allowedFrom: [MyState.Idle]
71
- * });
72
- */
73
- register(state: T, handler?: StateHandlerRegistration<T, P>): void;
74
- /**
75
- * Transitions the machine to a new state.
76
- * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
77
- * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
78
- *
79
- * @param newState The identifier of the state to transition to.
80
- * @param payload An optional payload to pass to the new state's `onEnter` handler.
81
- * @returns A promise that resolves when the transition is complete.
82
- * @throws {Error} if the `newState` has not been registered.
83
- * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
84
- * @example
85
- * try {
86
- * await fsm.call(PlayerState.Run, { speed: 10 });
87
- * } catch (e) {
88
- * console.error('State transition failed:', e.message);
89
- * }
90
- */
91
- call(newState: T, payload?: P): Promise<void>;
92
- /**
93
- * Removes a single state configuration from the machine.
94
- * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
95
- *
96
- * @param state The identifier of the state to remove.
97
- * @returns `true` if the state was found and removed, otherwise `false`.
98
- * @example
99
- * fsm.register(MyState.Temp, () => {});
100
- * // ...
101
- * const wasRemoved = fsm.unregister(MyState.Temp);
102
- * console.log('Temporary state removed:', wasRemoved);
103
- */
104
- unregister(state: T): boolean;
105
- /**
106
- * Removes all registered states and resets the machine to its initial, undefined state.
107
- * This does not clear `onChange` subscribers.
108
- * @example
109
- * fsm.register(MyState.One);
110
- * fsm.register(MyState.Two);
111
- * // ...
112
- * fsm.clear(); // The machine is now empty.
113
- */
114
- clear(): void;
115
- }
116
-
117
- export { type StateHandler, type StateHandlerConfig, type StateHandlerRegistration, StateMachine };
package/dist/index.js DELETED
@@ -1,144 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- StateMachine: () => StateMachine
24
- });
25
- module.exports = __toCommonJS(index_exports);
26
-
27
- // src/state-machine.ts
28
- var import_utils = require("@axi-engine/utils");
29
- var StateMachine = class {
30
- constructor() {
31
- /**
32
- * @protected
33
- * A map storing all registered state configurations.
34
- */
35
- this.states = /* @__PURE__ */ new Map();
36
- /**
37
- * Public emitter that fires an event whenever the state changes.
38
- * The event provides the old state, the new state, and the payload.
39
- * @see Emitter
40
- * @example
41
- * fsm.onChange.subscribe((from, to, payload) => {
42
- * console.log(`State transitioned from ${from} to ${to}`);
43
- * });
44
- */
45
- this.onChange = new import_utils.Emitter();
46
- }
47
- /**
48
- * Gets the current state of the machine.
49
- * @returns The current state identifier, or `undefined` if the machine has not been started.
50
- */
51
- get state() {
52
- return this._state;
53
- }
54
- /**
55
- * Registers a state and its associated handler or configuration.
56
- * If a handler is already registered for the given state, it will be overwritten.
57
- *
58
- * @param state The identifier for the state to register.
59
- * @param handler A handler function (`onEnter`) or a full configuration object.
60
- * @example
61
- * // Simple registration
62
- * fsm.register(MyState.Idle, () => console.log('Entering Idle'));
63
- *
64
- * // Advanced registration
65
- * fsm.register(MyState.Walking, {
66
- * onEnter: () => console.log('Start walking animation'),
67
- * onExit: () => console.log('Stop walking animation'),
68
- * allowedFrom: [MyState.Idle]
69
- * });
70
- */
71
- register(state, handler) {
72
- if ((0, import_utils.isUndefined)(handler) || typeof handler === "function") {
73
- this.states.set(state, { onEnter: handler });
74
- } else {
75
- this.states.set(state, handler);
76
- }
77
- }
78
- /**
79
- * Transitions the machine to a new state.
80
- * This method is asynchronous to accommodate async `onEnter` and `onExit` handlers.
81
- * It will execute the `onExit` handler of the old state, then the `onEnter` handler of the new state.
82
- *
83
- * @param newState The identifier of the state to transition to.
84
- * @param payload An optional payload to pass to the new state's `onEnter` handler.
85
- * @returns A promise that resolves when the transition is complete.
86
- * @throws {Error} if the `newState` has not been registered.
87
- * @throws {Error} if the transition from the current state to the `newState` is not allowed by the `allowedFrom` rule.
88
- * @example
89
- * try {
90
- * await fsm.call(PlayerState.Run, { speed: 10 });
91
- * } catch (e) {
92
- * console.error('State transition failed:', e.message);
93
- * }
94
- */
95
- async call(newState, payload) {
96
- const oldState = this._state;
97
- const oldStateConfig = this._state ? this.states.get(this._state) : void 0;
98
- const newStateConfig = this.states.get(newState);
99
- (0, import_utils.throwIfEmpty)(newStateConfig, `State ${String(newState)} is not registered.`);
100
- (0, import_utils.throwIf)(
101
- !(0, import_utils.isNullOrUndefined)(newStateConfig.allowedFrom) && !(0, import_utils.isNullOrUndefined)(oldState) && !newStateConfig.allowedFrom.includes(oldState),
102
- `Transition from ${String(oldState)} to ${String(newState)} is not allowed.`
103
- );
104
- await oldStateConfig?.onExit?.();
105
- this._state = newState;
106
- await newStateConfig.onEnter?.(payload);
107
- this.onChange.emit(oldState, newState, payload);
108
- }
109
- /**
110
- * Removes a single state configuration from the machine.
111
- * If the removed state is the currently active one, the machine's state will be reset to `undefined`.
112
- *
113
- * @param state The identifier of the state to remove.
114
- * @returns `true` if the state was found and removed, otherwise `false`.
115
- * @example
116
- * fsm.register(MyState.Temp, () => {});
117
- * // ...
118
- * const wasRemoved = fsm.unregister(MyState.Temp);
119
- * console.log('Temporary state removed:', wasRemoved);
120
- */
121
- unregister(state) {
122
- if (this._state === state) {
123
- this._state = void 0;
124
- }
125
- return this.states.delete(state);
126
- }
127
- /**
128
- * Removes all registered states and resets the machine to its initial, undefined state.
129
- * This does not clear `onChange` subscribers.
130
- * @example
131
- * fsm.register(MyState.One);
132
- * fsm.register(MyState.Two);
133
- * // ...
134
- * fsm.clear(); // The machine is now empty.
135
- */
136
- clear() {
137
- this.states.clear();
138
- this._state = void 0;
139
- }
140
- };
141
- // Annotate the CommonJS export names for ESM import in node:
142
- 0 && (module.exports = {
143
- StateMachine
144
- });