/** * Event Engine Core state module. * * @internal */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Event, EventOfType, GenericInvocation, GenericMap, InvocationTypeFromMap } from './types'; /** @internal */ export type TransitionFunction< Context, Events extends GenericMap, Effects extends GenericMap, EventType extends Event, > = { (context: Context, event: EventType): Transition | void; }; /** @internal */ export type Transition = [ State, Context, InvocationTypeFromMap[], ]; /** * Event engine current state object. * * State contains current context and list of invocations which should be performed by the Event Engine. * * @internal */ export class State { private transitionMap: Map> = new Map(); transition(context: Context, event: EventOfType) { if (this.transitionMap.has(event.type)) { return this.transitionMap.get(event.type)?.(context, event); } return undefined; } constructor(public label: string) {} on( eventType: K, transition: TransitionFunction>, ) { this.transitionMap.set(eventType, transition); return this; } with(context: Context, effects?: InvocationTypeFromMap[]): Transition { return [this, context, effects ?? []]; } enterEffects: ((context: Context) => InvocationTypeFromMap)[] = []; exitEffects: ((context: Context) => InvocationTypeFromMap)[] = []; onEnter(effect: (context: Context) => GenericInvocation) { this.enterEffects.push(effect); return this; } onExit(effect: (context: Context) => GenericInvocation) { this.exitEffects.push(effect); return this; } }