@fsmoothy/core
Version:
FSMoothy is a feature-rich and easy-to-use finite state machine for TypeScript.
1 lines • 54.7 kB
Source Map (JSON)
{"version":3,"file":"index.esm.mjs","sources":["../src/fsm.error.ts","../src/symbols.ts","../src/heplers.ts","../src/transition.ts","../src/fsm.ts","../src/nested.ts"],"sourcesContent":["import { AllowedNames } from './types';\n\nexport class StateMachineTransitionError extends Error {\n constructor(\n id: string,\n from: AllowedNames,\n event: AllowedNames,\n cause?: unknown,\n ) {\n super(\n `Event ${String(event)} is not allowed in state ${String(from)} of ${id}`,\n );\n this.name = 'StateMachineTransitionError';\n this.cause = cause;\n }\n}\n\nexport const isStateMachineTransitionError = (\n error: unknown,\n): error is StateMachineTransitionError =>\n error instanceof StateMachineTransitionError;\n","/**\n * Symbol that can be used to represent all states or events.\n */\nexport const All = Symbol('All') as any;\n","import { All } from './symbols';\nimport {\n AllowedNames,\n FsmContext,\n IInternalTransition,\n StateMachineParameters,\n Transition,\n Subscribers,\n Callback,\n Nested,\n} from './types';\n\nexport const InitialEvent = Symbol('InitialEvent') as any;\n\nexport function capitalize(parameter: string) {\n return parameter.charAt(0).toUpperCase() + parameter.slice(1);\n}\n\nconst SpecialSymbols = new Set([All, InitialEvent]);\n\nexport function initialTransition<\n State extends AllowedNames,\n Event extends AllowedNames,\n Context extends FsmContext<unknown> = FsmContext<never>,\n>(state: State): IInternalTransition<State, Event, Context> {\n return {\n from: state,\n event: InitialEvent,\n to: state,\n _original: {\n from: state,\n event: InitialEvent,\n to: state,\n },\n };\n}\n\nexport function addIsChecker(this: any, state: AllowedNames) {\n if (typeof state !== 'string') {\n return;\n }\n\n const capitalized = capitalize(state);\n\n this[`is${capitalized}`] = () => this.is(state);\n}\n\nexport function prepareStates<State extends AllowedNames>(\n this: any,\n parameters: StateMachineParameters<any, any, any>,\n) {\n const states = new Map<State, Nested | null>();\n const statesFromParameters = parameters.states?.(parameters) ?? {};\n\n for (const { from, to } of parameters.transitions ?? []) {\n if (Array.isArray(from)) {\n for (const state of from) {\n states.set(state, null);\n }\n } else {\n states.set(from, null);\n }\n states.set(to, null);\n }\n\n for (const [state, nested] of Object.entries(statesFromParameters)) {\n if (!nested) {\n continue;\n }\n\n (nested as any)._parent = this;\n states.set(state as State, nested);\n }\n\n return states;\n}\n\nexport function prepareTransitions(\n this: any,\n transitions: Array<Transition<AllowedNames, AllowedNames, any>> = [],\n) {\n return transitions.reduce((accumulator, transition) => {\n const { from, event } = transition;\n const froms = Array.isArray(from) ? from : [from];\n\n if (!accumulator.has(event)) {\n accumulator.set(event, new Map());\n }\n\n const transitionsByState = accumulator.get(event);\n\n for (const from of froms) {\n if (!transitionsByState?.has(from)) {\n transitionsByState?.set(from, []);\n }\n\n transitionsByState?.get(from)?.push(this.bindToCallbacks(transition));\n }\n\n return accumulator;\n }, new Map());\n}\n\nexport function prepareSubscribers<\n Event extends AllowedNames,\n Context extends FsmContext<unknown>,\n>(this: any, subscribers?: Subscribers<Event, Context>) {\n const subscribersMap = new Map<\n Event,\n Map<Callback<Context>, Callback<Context>>\n >();\n\n if (!subscribers) {\n return subscribersMap;\n }\n\n if (All in subscribers) {\n for (const callback of subscribers[All as keyof typeof subscribers]!) {\n subscribersMap.set(All, new Map());\n subscribersMap.get(All)?.set(callback, callback.bind(this));\n }\n }\n\n for (const [event, callbacks] of Object.entries(subscribers)) {\n if (!subscribersMap.has(event as Event)) {\n subscribersMap.set(event as Event, new Map());\n }\n\n for (const callback of callbacks as Array<Callback<Context>>) {\n subscribersMap.get(event as Event)?.set(callback, callback.bind(this));\n }\n }\n\n return subscribersMap;\n}\n\nexport function populateEventMethods(\n this: any,\n parameters: StateMachineParameters<any, any, any>,\n) {\n const nestedEvents = this.nested.flatMap((nested: Nested) => {\n if (nested.type === 'parallel') {\n return nested.machines.flatMap((m) => m.events);\n }\n\n return nested.events;\n });\n\n const events = new Set([\n ...(parameters.transitions?.map((t) => t.event) ?? []),\n ...nestedEvents,\n ]);\n\n for (const event of events) {\n if (SpecialSymbols.has(event)) {\n continue;\n }\n\n addEventMethods.call(this, event);\n }\n}\n\nexport function populateCheckers(\n this: any,\n parameters: StateMachineParameters<any, any, any>,\n) {\n const nestedStates = this.nested.flatMap((nested: Nested) => {\n if (nested.type === 'parallel') {\n return nested.machines.flatMap((m) => m.states);\n }\n\n return nested.states;\n });\n\n const states = new Set([\n ...(parameters.transitions?.map((t) => t.from) ?? []),\n ...(parameters.transitions?.map((t) => t.to) ?? []),\n ...nestedStates,\n ]);\n\n for (const state of states) {\n if (SpecialSymbols.has(state)) {\n continue;\n }\n\n addIsChecker.call(this, state);\n }\n}\n\nexport function addEventMethods<Event extends AllowedNames>(\n this: any,\n event: Event,\n) {\n if (typeof event !== 'string') {\n // this could happen if the `event` is `All` or `IdentityEvent`\n return;\n }\n\n const capitalizedEvent = capitalize(event);\n\n this[event] = async (...arguments_: Array<unknown>) => {\n await this.transition(event, ...arguments_);\n };\n\n this[`can${capitalizedEvent}`] = (...arguments_: Array<unknown>) =>\n this.can(event, ...arguments_);\n}\n","import { AllowedNames, Callback, Guard, Transition, FsmContext } from './types';\n\nexport interface TransitionOptions<Context extends FsmContext<unknown>> {\n onExit?: Callback<Context>;\n onEnter?: Callback<Context>;\n onLeave?: Callback<Context>;\n guard?: Guard<Context>;\n}\n\n/**\n * Creates a new transition.\n *\n * @param from - From state.\n * @param event - Event name.\n * @param to - To state.\n * @param guard - Guard function.\n *\n * @overload\n * @param from - From state.\n * @param event - Event name.\n * @param to - To state.\n * @param options - Transition options.\n */\nexport const t = <\n const State extends AllowedNames,\n const Event extends AllowedNames,\n Context extends FsmContext<unknown> = FsmContext<unknown>,\n>(\n from: ReadonlyArray<State> | State,\n event: Event,\n to: State,\n guardOrOptions: Guard<Context> | TransitionOptions<Context> = {},\n): Transition<State, Event, Context> => {\n if (typeof guardOrOptions === 'function') {\n return {\n from,\n event,\n to,\n guard: guardOrOptions,\n };\n }\n const { onExit, onEnter, onLeave, guard, ...rest } = guardOrOptions;\n\n return {\n ...rest,\n from,\n event,\n to,\n onLeave,\n onExit,\n onEnter,\n guard,\n };\n};\n","import {\n StateMachineTransitionError,\n isStateMachineTransitionError,\n} from './fsm.error';\nimport {\n initialTransition,\n prepareStates,\n prepareTransitions,\n prepareSubscribers,\n populateEventMethods,\n populateCheckers,\n addIsChecker,\n addEventMethods,\n} from './heplers';\nimport { All } from './symbols';\nimport { TransitionOptions, t } from './transition';\nimport {\n AllowedNames,\n Callback,\n Transition,\n FsmContext,\n Guard,\n IStateMachine,\n ParallelState,\n INestedStateMachine,\n HydratedState,\n Nested,\n StateMachineConstructor,\n StateMachineParameters,\n States,\n TransitionsStorage,\n IStateMachineInspectRepresentation,\n TransitionInspectRepresentation,\n} from './types';\n\nexport class _StateMachine<\n const State extends AllowedNames,\n const Event extends AllowedNames,\n Context extends FsmContext<unknown>,\n> {\n protected _context = {} as Context;\n\n constructor(parameters: StateMachineParameters<State, Event, Context>) {\n this.#initialParameters = parameters;\n this.#id = parameters.id ?? 'fsm';\n this.#last = initialTransition(parameters.initial);\n\n this.#states = (prepareStates<State>).call(this, parameters);\n\n this.#transitions = prepareTransitions.call(this, parameters.transitions);\n this.#subscribers = (prepareSubscribers<Event, Context>).call(\n this,\n parameters.subscribers,\n );\n\n populateEventMethods.call(this, parameters);\n populateCheckers.call(this, parameters);\n this.populateContext(parameters);\n }\n\n #last: Transition<State, Event, Context>;\n #id: string;\n #contextPromise: Promise<Context> | null = null;\n #boundTo: any = this;\n #dataPromise: Promise<Context['data']> | null = null;\n\n /**\n * Active nested state machine.\n */\n #activeChild: INestedStateMachine<any, any, any> | null = null;\n /**\n * Active parallel state machine.\n */\n #activeParallelState: ParallelState<any, any, any> | null = null;\n\n /**\n * Map of nested states.\n */\n #states: States<State>;\n\n /**\n * Map of transitions by event and from-state.\n */\n #transitions: TransitionsStorage<State, Event, Context>;\n\n #subscribers = new Map<\n Event,\n /**\n * Map of original callbacks by bound callbacks.\n */\n Map<Callback<Context>, Callback<Context>>\n >();\n\n /**\n * We're saving initial parameters mostly for nested states when history = none\n */\n #initialParameters: StateMachineParameters<State, Event, Context>;\n\n get context(): Context {\n return this._context;\n }\n\n /**\n * Current state.\n */\n get current(): State {\n return this.#last.to;\n }\n\n /**\n * Data object.\n */\n get data(): Context['data'] {\n return this._context.data;\n }\n\n /**\n * Active child state machine.\n */\n get child() {\n return this.#activeChild;\n }\n\n /**\n * All events in the state machine.\n */\n get events(): Array<Event> {\n return Array.from(this.#transitions.keys());\n }\n\n /**\n * All states in the state machine.\n */\n get states(): Array<State> {\n return Array.from(this.#states.keys());\n }\n\n get nested(): Array<Nested> {\n return Array.from(this.#states.values()).filter(\n (v) => v !== null,\n ) as Array<Nested>;\n }\n\n /**\n * Add transition to the state machine.\n *\n * @param transition - Transition to add.\n * @returns New state machine.\n */\n addTransition<const NewState extends State, const NewEvent extends Event>(\n from: ReadonlyArray<NewState> | NewState,\n event: Event,\n to: NewState,\n guardOrOptions?: Guard<Context> | TransitionOptions<Context>,\n ) {\n const transition = t(from, event, to, guardOrOptions);\n const states = new Set(Array.isArray(from) ? [...from] : [from]);\n\n addEventMethods.call(this, event);\n\n const eventMap = this.#transitions.get(event) ?? new Map();\n\n for (const state of states) {\n this.#states.set(state, null);\n addIsChecker.call(this, state);\n\n if (!eventMap?.has(state)) {\n eventMap?.set(state, []);\n }\n eventMap?.get(state)?.push(this.bindToCallbacks(transition));\n }\n\n this.#transitions.set(event, eventMap);\n\n return this as unknown as IStateMachine<\n State | NewState,\n Event | NewEvent,\n Context\n >;\n }\n\n /**\n * Add nested state machine.\n *\n * @param state - State to add.\n * @param nestedState - Nested state machine.\n */\n addNestedMachine(state: State, nestedState: Nested) {\n this.#states.set(state, nestedState);\n\n if (nestedState.type === 'parallel') {\n return this;\n }\n\n (nestedState as any)._parent = this;\n\n const nestedEvents = nestedState.events;\n\n for (const event of nestedEvents) {\n addEventMethods.call(this, event);\n }\n\n const nestedStates = nestedState.states;\n\n for (const nestedState of nestedStates) {\n addIsChecker.call(this, nestedState as State);\n }\n\n return this;\n }\n\n /**\n * Removes all nested state machines by state.\n *\n * @param state - State to remove.\n */\n removeState(state: State) {\n if (this.current === state) {\n this.#activeChild = null;\n this.#activeParallelState = null;\n }\n\n this.#states.delete(state);\n\n return this;\n }\n\n /**\n * Checks if the state machine is in the given state.\n *\n * @param state - State to check.\n */\n is(state: State): boolean {\n if (this.#activeChild?.is(state)) {\n return true;\n }\n\n return this.current === state;\n }\n\n /**\n * Checks if the event can be triggered in the current state.\n *\n * @param event - Event to check.\n */\n async can<Arguments extends Array<unknown> = Array<unknown>>(\n event: Event,\n ...arguments_: Arguments\n ) {\n if (await this.#activeChild?.can(event, ...arguments_)) {\n return true;\n }\n\n const transitionsByState = this.#transitions.get(event);\n\n // check has from: all\n if (transitionsByState?.has(All)) {\n for (const t of transitionsByState.get(All) ?? []) {\n const result = await (t.guard?.(this._context, ...arguments_) ?? true);\n\n if (result) {\n return true;\n }\n }\n }\n\n if (!transitionsByState?.has(this.current)) {\n return false;\n }\n\n const transitions = transitionsByState.get(this.current) ?? [];\n\n for (const transition of transitions) {\n const { guard } = transition;\n\n const result = await (guard?.(this._context, ...arguments_) ?? true);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Subscribe to event. Will execute after transition.\n *\n * @param event - Event to subscribe to.\n * @param callback - Callback to execute.\n *\n * @overload\n * Without providing event will subscribe to `All` event.\n *\n * @param callback - Callback to execute.\n */\n on(event: Event, callback: Callback<Context>): this;\n on(callback: Callback<Context>): this;\n on(eventOrCallback: Event | Callback<Context>, callback?: Callback<Context>) {\n if (typeof eventOrCallback === 'function') {\n return this.on(All, eventOrCallback);\n }\n\n const event = eventOrCallback;\n\n if (!this.#subscribers.has(event)) {\n this.#subscribers.set(event, new Map());\n }\n\n const callbacks = this.#subscribers.get(event);\n if (callback) {\n callbacks?.set(callback, callback.bind(this.#boundTo));\n }\n\n return this;\n }\n\n /**\n * Unsubscribe from event.\n *\n * @param event - Event to unsubscribe from.\n * @param callback - Callback to unsubscribe.\n *\n * @overload\n * Unsubscribe from `All` event.\n *\n * @param callback - Callback to unsubscribe.\n */\n off(event: Event, callback: Callback<Context>): this;\n off(callback: Callback<Context>): this;\n off(\n eventOrCallback: Event | Callback<Context>,\n callback?: Callback<Context>,\n ) {\n if (typeof eventOrCallback === 'function') {\n return this.off(All, eventOrCallback);\n }\n\n const event = eventOrCallback;\n if (!this.#subscribers.has(event)) {\n return;\n }\n\n const callbacks = this.#subscribers.get(event);\n callbacks?.delete(callback!);\n\n return this;\n }\n\n /**\n * Transitions the state machine to the next state.\n *\n * @param event - Event to trigger.\n * @param arguments_ - Arguments to pass to lifecycle hooks.\n */\n async transition<Arguments extends Array<unknown> = Array<unknown>>(\n event: Event,\n ...arguments_: Arguments\n ): Promise<this> {\n // check nested state machine\n if (await this.makeNestedTransition(event, ...arguments_)) {\n return this;\n }\n // propagate to parent\n\n if (!(await this.can(event, ...arguments_))) {\n throw new StateMachineTransitionError(this.#id, this.current, event);\n }\n\n const transition = (await this.getAllowedTransition(event, ...arguments_))!;\n\n if (this.#contextPromise) {\n for (const [key, value] of Object.entries(await this.#contextPromise)) {\n this._context[key as keyof Context] = value as Context[keyof Context];\n }\n this.#contextPromise = null;\n }\n\n if (this.#dataPromise) {\n this._context.data = await this.#dataPromise;\n this.#dataPromise = null;\n }\n\n await this.executeTransition(transition, ...arguments_);\n\n return this;\n }\n\n /**\n * Tries to transition the state machine to the next state.\n * Returns `false` if the transition is not allowed instead of throwing an error.\n */\n async tryTransition<Arguments extends Array<unknown> = Array<unknown>>(\n event: Event,\n ...arguments_: Arguments\n ): Promise<boolean> {\n try {\n await this.transition(event, ...arguments_);\n return true;\n } catch (error) {\n if (isStateMachineTransitionError(error)) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Will remove all transitions with the given from, to and event.\n */\n removeTransition(from: State, event: Event, to: State) {\n const transitions = this.#transitions.get(event)?.get(from);\n\n if (!transitions) {\n return this;\n }\n\n const newTransitions = transitions.filter((t) => t.to !== to);\n this.#transitions.get(event)?.set(from, newTransitions);\n\n return this;\n }\n\n /**\n * Binds external context to the state machine callbacks.\n *\n * @param this - Context to bind.\n * @returns state machine instance.\n */\n bind<T>(_this: T) {\n for (const callbacks of this.#subscribers.values()) {\n for (const callback of callbacks.keys()) {\n callbacks.set(callback, callback.bind(_this));\n }\n }\n\n for (const transitionsByState of this.#transitions.values()) {\n for (const transition of transitionsByState.values()) {\n for (const t of transition) {\n t.onEnter = t._original.onEnter?.bind(_this);\n t.onExit = t._original.onExit?.bind(_this);\n t.onLeave = t._original.onLeave?.bind(_this);\n t.guard = t._original.guard?.bind(_this);\n }\n }\n }\n\n this.#boundTo = _this;\n\n return this;\n }\n\n /**\n * Injects service into the state machine context.\n */\n inject<const Key extends keyof Omit<Context, 'data'>>(\n key: Key,\n service: Context[Key],\n ) {\n this._context[key] = service;\n\n return this;\n }\n\n /**\n * Injects service into the state machine context using factory function.\n *\n * @param key - Key to inject.\n * @param service - Service factory function.\n */\n injectAsync<const Key extends keyof Omit<Context, 'data'>>(\n key: Key,\n service: (fsm: this) => Promise<Context[Key]> | Context[Key],\n ) {\n const contextValue = service(this);\n\n if (contextValue instanceof Promise) {\n this.#contextPromise ??= Promise.resolve({} as Context);\n this.#contextPromise.then((context) => {\n return contextValue.then((value) => {\n context[key as keyof Context] = value;\n return context;\n });\n });\n } else {\n this._context[key as keyof Context] = contextValue;\n }\n\n return this;\n }\n\n /**\n * Hydrates the state machine to plain object.\n *\n * @returns Hydrated JSON.\n */\n dehydrate(): HydratedState<State, Context['data']> {\n const hydrated: HydratedState<State, Context['data']> = {\n current: this.current,\n data: this._context.data,\n };\n\n if (this.#activeChild) {\n hydrated.nested = this.#activeChild.dehydrate();\n }\n\n return hydrated;\n }\n\n /**\n * Apply hydrated plain object to the state machine.\n *\n * @param hydrated - Hydrated JSON.\n */\n hydrate(hydrated: HydratedState<State, Context['data']>) {\n this.#last = initialTransition(hydrated.current);\n this._context.data = hydrated.data;\n\n if (this.#activeChild && hydrated.nested) {\n this.#activeChild.hydrate(hydrated.nested);\n }\n\n return this;\n }\n\n /**\n * Inspects the state machine.\n *\n * @returns representation of the state machine.\n */\n inspect(): IStateMachineInspectRepresentation {\n const transitions = [];\n for (const [event, transitions_] of this.#transitions.entries()) {\n for (const [from, transitions__] of transitions_.entries()) {\n for (const transition of transitions__) {\n const t: TransitionInspectRepresentation = {\n from,\n event,\n to: transition.to,\n hasGuard: Boolean(transition.guard),\n hasOnEnter: Boolean(transition.onEnter),\n hasOnExit: Boolean(transition.onExit),\n hasOnLeave: Boolean(transition.onLeave),\n };\n\n transitions.push(t);\n }\n }\n }\n\n return {\n currentState: this.current.toString(),\n transitions,\n id: this.#id,\n states: this.states,\n data: this._context.data,\n };\n }\n\n protected populateContext(parameters: StateMachineParameters<any, any, any>) {\n this.#contextPromise = Promise.resolve({} as Context);\n\n for (const [key, value] of Object.entries(parameters.inject ?? {})) {\n const contextValue =\n typeof value === 'function'\n ? value(this as IStateMachine<any, any, any>)\n : value;\n\n if (contextValue instanceof Promise) {\n this.#contextPromise = this.#contextPromise.then((context: any) => {\n return contextValue.then((value) => {\n context[key] = value;\n return context;\n });\n });\n } else {\n this._context[key as keyof Context] = contextValue;\n }\n }\n\n const data = parameters.data?.(parameters) ?? {};\n\n if (data instanceof Promise) {\n this.#dataPromise = data;\n this._context.data = {};\n } else {\n this._context.data = data;\n }\n }\n\n private async makeNestedTransition(\n event: Event,\n ...arguments_: Array<unknown>\n ) {\n let hasExecuted = false;\n\n if (!this.#activeChild && !this.#activeParallelState) {\n return hasExecuted;\n }\n\n const children = this.#activeParallelState?.machines ?? [this.#activeChild];\n\n for (const child of children) {\n if (child && (await child.can(event, ...arguments_))) {\n const _child = child;\n\n this.#activeChild = _child;\n await child?.transition(event, ...arguments_);\n hasExecuted = true;\n }\n }\n\n return hasExecuted;\n }\n\n private async getAllowedTransition(\n event: Event,\n ...arguments_: Array<unknown>\n ) {\n const transitionsByState = this.#transitions.get(event);\n\n if (!transitionsByState) {\n return null;\n }\n\n const transitions = transitionsByState.get(this.current);\n\n if (transitions) {\n for (const t of transitions) {\n const { guard } = t;\n\n const result = await (guard?.(this._context, ...arguments_) ?? true);\n\n if (result) {\n return t;\n }\n }\n }\n\n // Handle from All\n const allTransitions = transitionsByState.get(All);\n if (allTransitions) {\n for (const t of allTransitions) {\n const result = await (t.guard?.(this._context, ...arguments_) ?? true);\n\n if (result) {\n return t;\n }\n }\n }\n\n return null;\n }\n\n /**\n * This method binds the callbacks of the transition to the state machine instance.\n * It useful in case if we need to access the state machine instance from the callbacks.\n */\n private bindToCallbacks(transition: Transition<State, Event, Context>) {\n return {\n ...transition,\n onLeave: transition.onLeave?.bind(this.#boundTo),\n onEnter: transition.onEnter?.bind(this.#boundTo),\n onExit: transition.onExit?.bind(this.#boundTo),\n guard: transition.guard?.bind(this.#boundTo),\n _original: transition,\n };\n }\n\n private switchNestedState(transition: Transition<State, Event, Context>) {\n let child = this.#states.get(transition.to);\n\n if (!child) {\n this.#activeChild = null;\n this.#activeParallelState = null;\n return;\n }\n\n if (child.type === 'parallel') {\n this.#activeParallelState = child;\n\n // we start processing from the first nested machine\n child = child.machines[0];\n\n return;\n }\n\n switch (child.history) {\n case 'none': {\n this.#activeChild = new (child as any).constructor(\n child.#initialParameters,\n this,\n );\n break;\n }\n case 'deep': {\n this.#activeChild = child;\n }\n }\n }\n\n private makeTransition(transition: Transition<State, Event, Context>) {\n this.#last = transition ?? this.#last;\n }\n\n private async executeTransition<\n Arguments extends Array<unknown> = Array<unknown>,\n >(transition: Transition<State, Event, Context>, ...arguments_: Arguments) {\n const { onEnter, onExit, event } = transition ?? {};\n\n const subscribers = this.#subscribers.get(event);\n const allSubscribers = this.#subscribers.get(All);\n\n await this.#last.onLeave?.(this.context, ...arguments_);\n await onEnter?.(this.context, ...arguments_);\n this.makeTransition(transition);\n this.switchNestedState(transition);\n\n for (const subscriber of subscribers?.values() ?? []) {\n await subscriber(this.context, ...arguments_);\n }\n\n for (const subscriber of allSubscribers?.values() ?? []) {\n await subscriber(this.context, ...arguments_);\n }\n\n await onExit?.(this.context, ...arguments_);\n }\n}\n\n/**\n * Creates a new state machine.\n *\n * @param parameters - State machine parameters.\n * @param parameters.id - State machine id. Used in error messages.\n * @param parameters.initial - Initial state.\n * @param parameters.ctx - Context object.\n * @param parameters.transitions - Transitions.\n * @param parameters.transitions[].from - From state.\n * @param parameters.transitions[].from[] - From states.\n * @param parameters.transitions[].event - Event name.\n * @param parameters.transitions[].to - To state.\n * @param parameters.transitions[].onEnter - Callback to execute on enter.\n * @param parameters.transitions[].onExit - Callback to execute on exit.\n * @param parameters.transitions[].onLeave - Callback to execute on transition to the next state.\n * @param parameters.transitions[].guard - Guard function.\n *\n * @example\n * const stateMachine = new StateMachine({\n * id: '1',\n * initial: State.idle,\n * transitions: [\n * t(State.idle, Event.fetch, State.pending),\n * t(State.pending, Event.resolve, State.idle),\n * ],\n * });\n *\n * @returns New state machine.\n *\n */\nexport const StateMachine = _StateMachine as unknown as StateMachineConstructor;\n","import { _StateMachine } from './fsm';\nimport {\n AllowedNames,\n FsmContext,\n HistoryTypes,\n INestedStateMachine,\n INestedStateMachineParameters,\n NestedStateMachineConstructor,\n ParallelState,\n} from './types';\n\ntype NestedStateMachineParent = _StateMachine<any, any, any>;\n\nexport class _NestedStateMachine<\n const State extends AllowedNames,\n const Event extends AllowedNames,\n Context extends FsmContext<unknown>,\n> extends _StateMachine<State, Event, Context> {\n readonly type = 'nested';\n readonly history: HistoryTypes;\n\n constructor(\n parameters: INestedStateMachineParameters<State, Event, Context>,\n protected _parent: NestedStateMachineParent | null = null,\n ) {\n super(parameters);\n this.history = parameters.history ?? 'deep';\n }\n\n get context(): Context {\n return { ...this._parent?.context, ...this._context };\n }\n}\n\nexport const NestedStateMachine =\n _NestedStateMachine as unknown as NestedStateMachineConstructor;\n\n/**\n * Creates a nested state machine.\n *\n * @param machineParameters The parameters of the nested state machine.\n * @param options The options of the nested state machine.\n * @returns A nested state machine.\n */\nexport function nested<\n const State extends AllowedNames,\n const Event extends AllowedNames,\n Context extends FsmContext<unknown>,\n>(\n machineParameters: INestedStateMachineParameters<State, Event, Context>,\n): INestedStateMachine<State, Event, Context> {\n return new NestedStateMachine(machineParameters);\n}\n\n/**\n * Creates a parallel state. Parallel states execute all nested state machines at the same time.\n *\n * @param nested The nested state machines.\n */\nexport function parallel<\n NestedMachines extends ReadonlyArray<\n INestedStateMachine<State, Event, Context>\n >,\n const State extends AllowedNames = NestedMachines[number]['current'],\n const Event extends AllowedNames = NestedMachines[number]['events'][number],\n Context extends FsmContext<unknown> = NestedMachines[number]['context'],\n>(...nested: NestedMachines): ParallelState<State, Event, Context> {\n return {\n type: 'parallel',\n machines: nested,\n };\n}\n"],"names":["StateMachineTransitionError","_Error","id","from","event","cause","_this","call","String","name","_inheritsLoose","_wrapNativeSuper","Error","isStateMachineTransitionError","error","All","Symbol","InitialEvent","capitalize","parameter","charAt","toUpperCase","slice","SpecialSymbols","Set","initialTransition","state","to","_original","addIsChecker","_this2","this","is","prepareStates","parameters","_parameters$states","_step","states","Map","statesFromParameters","_iterator","_createForOfIteratorHelperLoose","_parameters$transitio","transitions","done","_step$value","value","Array","isArray","_step2","_iterator2","set","_i","_Object$entries","Object","entries","length","_Object$entries$_i","nested","_parent","prepareTransitions","_this3","reduce","accumulator","transition","froms","has","_step3","transitionsByState","get","_iterator3","_transitionsByState$g","push","bindToCallbacks","prepareSubscribers","subscribers","subscribersMap","_iterator4","_step4","_subscribersMap$get","callback","bind","_i2","_Object$entries2","_Object$entries2$_i","callbacks","_step5","_iterator5","_subscribersMap$get2","populateEventMethods","_parameters$transitio2","_parameters$transitio3","_step6","nestedEvents","flatMap","type","machines","m","events","concat","map","t","_iterator6","addEventMethods","populateCheckers","_parameters$transitio4","_parameters$transitio5","_parameters$transitio6","_parameters$transitio7","_step7","nestedStates","_iterator7","capitalizedEvent","Promise","resolve","apply","arguments","then","e","reject","can","guardOrOptions","guard","onExit","onEnter","onLeave","_extends","_objectWithoutPropertiesLoose","_excluded","_iteratorSymbol","iterator","_settle","pact","_Pact","s","o","v","observer","prototype","onFulfilled","onRejected","result","thenable","_last","_classPrivateFieldLooseKey","_forOf","target","body","check","step","_cycle","next","_isSettledPact","_fixup","TypeError","values","i","array","_forTo","_id","_StateMachine","_parameters$id","_context","defineProperty","writable","_contextPromise","_boundTo","_dataPromise","_activeChild","_activeParallelState","_states","_transitions","_subscribers","_initialParameters","_classPrivateFieldLooseBase","initial","populateContext","_proto","addTransition","_classPrivateFieldLoo","eventMap","_eventMap$get","addNestedMachine","nestedState","removeState","current","_classPrivateFieldLoo2","_classPrivateFieldLoo4","arguments_","_classPrivateFieldLoo3","_exit2","_temp3","_result2","_exit3","_temp","_guard","_result3","_temp2","_transitionsByState$g2","_t$guard","on","eventOrCallback","off","_exit4","makeNestedTransition","_this3$makeNestedTran","_this3$can","getAllowedTransition","_temp9","_temp7","executeTransition","_temp6","_classPrivateFieldLoo6","data","_temp8","_temp5","_classPrivateFieldLoo5","_temp4","_ref","tryTransition","_this4","_arguments3","_catch","removeTransition","_classPrivateFieldLoo7","_classPrivateFieldLoo8","newTransitions","filter","keys","_step8","_iterator8","_t$_original$onEnter","_t$_original$onExit","_t$_original$onLeave","_t$_original$guard","inject","key","service","injectAsync","_classPrivateFieldLoo9","contextValue","_classPrivateFieldLoo10","context","dehydrate","hydrated","hydrate","inspect","_step9","_iterator9","_step10","_step9$value","transitions_","_iterator10","_step11","_step10$value","transitions__","_iterator11","hasGuard","Boolean","hasOnEnter","hasOnExit","hasOnLeave","currentState","toString","_parameters$data","_this5","_loop","_parameters$inject","_classPrivateFieldLoo11","_classPrivateFieldLoo12","_this6","hasExecuted","_temp12","child","_child$can","_child","_temp17","_exit6","_result5","_exit7","allTransitions","_temp15","_t$guard2","_this7","_result7","_temp16","_guard2","_transition$onLeave","_transition$onEnter","_transition$onExit","_transition$guard","switchNestedState","history","constructor","makeTransition","_classPrivateFieldLoo13","_classPrivateFieldLoo14","_this8","_ref2","allSubscribers","_subscribers$values","_temp21","_allSubscribers$value","_temp19","_temp18","subscriber","_temp20","_createClass","StateMachine","NestedStateMachine","_StateMachine2","_NestedStateMachine","_parameters$history","_this$_parent","machineParameters","parallel"],"mappings":"g8FAEA,IAAaA,eAA4B,SAAAC,GACvC,SAAAD,EACEE,EACAC,EACAC,EACAC,OAAeC,EAMI,OAJnBA,EAAAL,EAAAM,KACWC,KAAAA,SAAAA,OAAOJ,GAAkCI,4BAAAA,OAAOL,UAAYD,UAElEO,KAAO,8BACZH,EAAKD,MAAQA,EAAMC,CACrB,QAACI,EAAAV,EAAAC,GAAAD,CAAA,CAZsC,cAYtCW,EAZ8CC,QAepCC,EAAgC,SAC3CC,GAAc,OAEdA,aAAiBd,CAA2B,ECjBjCe,EAAMC,OAAO,OCSbC,EAAeD,OAAO,gBAEnB,SAAAE,EAAWC,GACzB,OAAOA,EAAUC,OAAO,GAAGC,cAAgBF,EAAUG,MAAM,EAC7D,CAEA,IAAMC,EAAiB,IAAIC,IAAI,CAACT,EAAKE,IAErB,SAAAQ,EAIdC,GACA,MAAO,CACLvB,KAAMuB,EACNtB,MAAOa,EACPU,GAAID,EACJE,UAAW,CACTzB,KAAMuB,EACNtB,MAAOa,EACPU,GAAID,GAGV,CAEM,SAAUG,EAAwBH,GAAmBI,IAAAA,EACzDC,KAAqB,iBAAVL,IAMXK,KAAI,KAFgBb,EAAWQ,IAEJ,WAAM,OAAAI,EAAKE,GAAGN,EAAM,EACjD,CAEgB,SAAAO,EAEdC,GAKA,IALiDC,IAAAA,EAKMC,EAHjDC,EAAS,IAAIC,IACbC,EAAsDJ,OAAlCA,EAAGD,MAAAA,EAAWG,YAAXH,EAAAA,EAAWG,OAASH,IAAWC,EAAI,CAAA,EAEhEK,EAAAC,EAAiD,OAAjDC,EAA2BR,EAAWS,aAAWD,EAAI,MAAEN,EAAAI,KAAAI,MAAE,CAAAF,IAAAA,EAAAG,EAAAT,EAAAU,MAA5C3C,EAAI0C,EAAJ1C,KAAMw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