xstate 6.0.0-alpha.48 → 6.0.0-alpha.49
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/README.md +23 -0
- package/dist/{StateMachine-b09d2b00.cjs.js → StateMachine-0adb3a70.cjs.js} +1 -1
- package/dist/{StateMachine-b3a890bf.development.cjs.js → StateMachine-29450e6d.development.cjs.js} +1 -1
- package/dist/{StateMachine-8329769a.esm.js → StateMachine-2af31c11.esm.js} +1 -1
- package/dist/{StateMachine-88b3c26a.development.esm.js → StateMachine-faf50c5c.development.esm.js} +1 -1
- package/dist/{createActor-27287c65.esm.js → createActor-268165d4.esm.js} +1 -1
- package/dist/{createActor-309d77eb.development.esm.js → createActor-88709f74.development.esm.js} +1 -1
- package/dist/{createActor-cc3d6dde.development.cjs.js → createActor-a1e0dffb.development.cjs.js} +0 -3
- package/dist/{createActor-9b41ade9.cjs.js → createActor-b4dd05ae.cjs.js} +0 -3
- package/dist/declarations/src/fsm/createFSMActor.d.ts +67 -0
- package/dist/declarations/src/fsm/index.d.ts +2 -0
- package/dist/declarations/src/fsm.d.ts +5 -4
- package/dist/{effectDescriptor-b1f5deb6.esm.js → effectDescriptor-30c9a744.esm.js} +1 -1
- package/dist/{effectDescriptor-7707794b.development.esm.js → effectDescriptor-39d22100.development.esm.js} +1 -1
- package/dist/{effectDescriptor-a1678d06.development.cjs.js → effectDescriptor-7ff6802f.development.cjs.js} +1 -1
- package/dist/{effectDescriptor-bd36a33e.cjs.js → effectDescriptor-be348e50.cjs.js} +1 -1
- package/dist/fsm-7a2e9697.cjs.js +777 -0
- package/dist/fsm-b804b3e9.esm.js +775 -0
- package/dist/fsm-c1316948.development.cjs.js +777 -0
- package/dist/fsm-e18a7cb4.development.esm.js +775 -0
- package/dist/{types-81d03bef.esm.js → types-3c3455f7.esm.js} +1 -1
- package/dist/{types-1793b8b6.development.esm.js → types-adda3842.development.esm.js} +1 -1
- package/dist/{types-7e468202.development.cjs.js → types-b3fea5bd.development.cjs.js} +1 -1
- package/dist/{types-9c1bc85f.cjs.js → types-fbabaeee.cjs.js} +1 -1
- package/dist/xstate-actors.cjs.js +1 -1
- package/dist/xstate-actors.development.cjs.js +1 -1
- package/dist/xstate-actors.development.esm.js +2 -2
- package/dist/xstate-actors.esm.js +2 -2
- package/dist/xstate-durable.cjs.js +2 -2
- package/dist/xstate-durable.development.cjs.js +2 -2
- package/dist/xstate-durable.development.esm.js +2 -2
- package/dist/xstate-durable.esm.js +2 -2
- package/dist/xstate-fsm.cjs.d.mts +2 -0
- package/dist/xstate-fsm.cjs.d.ts +2 -0
- package/dist/xstate-fsm.cjs.js +409 -0
- package/dist/xstate-fsm.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.cjs.js +409 -0
- package/dist/xstate-fsm.development.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.esm.js +403 -0
- package/dist/xstate-fsm.esm.js +403 -0
- package/dist/xstate-fsm.umd.min.js +2 -0
- package/dist/xstate-fsm.umd.min.js.map +1 -0
- package/dist/xstate-graph.cjs.js +2 -2
- package/dist/xstate-graph.development.cjs.js +2 -2
- package/dist/xstate-graph.development.esm.js +2 -2
- package/dist/xstate-graph.esm.js +2 -2
- package/dist/xstate-scxml.cjs.js +3 -3
- package/dist/xstate-scxml.development.cjs.js +3 -3
- package/dist/xstate-scxml.development.esm.js +3 -3
- package/dist/xstate-scxml.esm.js +3 -3
- package/dist/xstate-validation.cjs.js +1 -1
- package/dist/xstate-validation.development.cjs.js +1 -1
- package/dist/xstate-validation.development.esm.js +1 -1
- package/dist/xstate-validation.esm.js +1 -1
- package/dist/xstate.cjs.js +6 -380
- package/dist/xstate.development.cjs.js +6 -380
- package/dist/xstate.development.esm.js +10 -384
- package/dist/xstate.esm.js +10 -384
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/fsm/package.json +8 -0
- package/package.json +18 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xstate.umd.min.js","sources":["../src/Mailbox.ts","../src/constants.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actions.ts","../src/actorSource.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/actors/subscription.ts","../src/actorScope.ts","../src/transitionActions.ts","../src/delay.ts","../src/snapshotActorRef.ts","../src/getNextSnapshot.ts","../src/stateUtils.ts","../src/utils.ts","../src/remoteActorRef.ts","../src/State.ts","../src/runtimeHelpers.ts","../src/system.ts","../src/createActor.ts","../src/validation.ts","../src/actors/logic.ts","../src/actors/callback.ts","../src/actors/observable.ts","../src/actors/promise.ts","../src/actors/index.ts","../src/memo.ts","../src/StateNode.ts","../src/StateMachine.ts","../src/spawn.ts","../src/createMachine.ts","../src/fsm.ts","../src/createMachineFromConfig.ts","../src/serialize.ts","../src/machineVersions.ts","../src/setup.ts","../src/types.ts","../src/transition.ts","../src/waitFor.ts","../src/SimulatedClock.ts","../src/assert.ts","../src/effectDescriptor.ts","../src/schema.types.ts","../src/mapState.ts","../src/toPromise.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = '@xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\nexport const XSTATE_STOP = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\nexport function createAfterEventId(delayRef: number | string, id: string) {\n return `xstate.after.${delayRef}.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout', stateId: id };\n}\n\nexport function createTimeoutEventId(id: string) {\n return `xstate.timeout.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createInvokeTimeoutEventId(invokeId: string) {\n return `xstate.timeout.actor.${invokeId}`;\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import isDevelopment from '#is-development';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : `Only event objects may be used with sendTo`\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n _event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, sendId: string) => {\n return actorScope.system.cancelTimer(actorScope.self, sendId);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","import type { AnyActorLogic } from './types.ts';\n\nconst sourceKeyCaches = new WeakMap<object, Map<AnyActorLogic, string>>();\n\n/** @internal */\nexport function resolveRegisteredActorSource(\n actors: Record<string, AnyActorLogic>,\n logic: AnyActorLogic\n): string | undefined {\n let cache = sourceKeyCaches.get(actors);\n if (!cache) {\n cache = new Map();\n for (const key of Object.keys(actors)) {\n const registeredLogic = actors[key];\n // Several source keys may intentionally share one implementation. The\n // first key is its canonical persistence identity when spawning by the\n // raw logic value, which cannot retain which alias was used to access it.\n if (!cache.has(registeredLogic)) {\n cache.set(registeredLogic, key);\n }\n }\n sourceKeyCaches.set(actors, cache);\n }\n\n return cache.get(logic);\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n return {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n 'xstate.listener'\n );\n}\n\n// Singleton logic instance\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, 'xstate.subscription');\n}\n\n// Singleton logic instance\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\n","import type { AnyActor, AnyActorScope } from './types.ts';\n\n/** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */\nexport const lazyActorScope = Symbol();\n\ntype InternalActorScope = AnyActorScope & {\n _parent?: AnyActor;\n [lazyActorScope]?: true;\n};\n\n/** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */\nexport function isLazyActorScope(actorScope: AnyActorScope): boolean {\n return !!(actorScope as InternalActorScope)[lazyActorScope];\n}\n\n/** Reads parent metadata without otherwise touching actor capabilities. @internal */\nexport function getActorScopeParent(\n actorScope: AnyActorScope\n): AnyActor | undefined {\n return isLazyActorScope(actorScope)\n ? (actorScope as InternalActorScope)._parent\n : actorScope.self._parent;\n}\n\n/** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */\nexport function withActorSelf<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> {\n if (!isLazyActorScope(actorScope)) {\n return Object.assign(args, { self: actorScope.self });\n }\n Object.defineProperty(args, 'self', {\n enumerable: true,\n get: () => actorScope.self\n });\n return args as T & Pick<AnyActorScope, 'self'>;\n}\n\n/** Adds the actor reference and parent without exposing the system. @internal */\nexport function withActorSelfAndParent<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined } {\n if (!isLazyActorScope(actorScope)) {\n const self = actorScope.self;\n return Object.assign(args, { self, parent: self._parent });\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined };\n}\n\n/** Adds actor capabilities without reading them until the callback does. @internal */\nexport function withActorScope<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n } {\n if (!isLazyActorScope(actorScope)) {\n const actorArgs = args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n const self = actorScope.self;\n actorArgs.self = self;\n actorArgs.system = actorScope.system;\n actorArgs.parent = self._parent;\n return actorArgs;\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n system: { enumerable: true, get: () => actorScope.system },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n}\n","import isDevelopment from '#is-development';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport { createErrorPlatformEvent } from './eventUtils.ts';\nimport {\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime\n} from './system.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport { getEventOutput } from './utils.ts';\nimport type {\n Action,\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableActionObject,\n CustomExecutableActionObject,\n EmitExecutableActionObject,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n RaiseExecutableActionObject,\n SendToExecutableActionObject,\n Snapshot,\n SpecialExecutableAction,\n SpawnExecutableActionObject,\n StartExecutableActionObject,\n StopExecutableActionObject,\n TerminateExecutableActionObject\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableActionObject\n): void | PromiseLike<void> | undefined {\n return this.action?.(...this.args);\n}\n\nfunction execEmitEffect(\n this: EmitExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.emitEvent!(this.source, this.event);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableActionObject {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableActionObject {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay ?? 0);\n}\n\nfunction execSendToEffect(\n this: SendToExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, this.id);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableActionObject,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableAction(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n if (!snapshot.timers?.[effect.id]) {\n return snapshot;\n }\n const timers = { ...snapshot.timers };\n delete timers[effect.id];\n return { ...snapshot, timers };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n let nextTimerId = snapshot._nextTimerId ?? 0;\n const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;\n effect.id = id;\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n\n return {\n ...snapshot,\n timers: {\n ...snapshot.timers,\n [id]: {\n id,\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n }\n },\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : `Cannot stop non-child actor ${update.actor.id}`\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(`Actor source '${source}' is not provided`);\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved namespace.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (isDevelopment && prefix.startsWith('xstate.')) {\n throw new Error(\n `Child actor ids with the \"xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : `Child actor id '${id}' is already in use`\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n if (typeof raisedEvent === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${raisedEvent}\" }) instead`\n : `Only event objects may be used with raise`\n );\n }\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? src ?? (logic as any).id\n } as AnyActor;\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n if (!actor) {\n internalEvents.push(\n createErrorPlatformEvent('communication', {\n message: 'Unable to send event to an undefined actor',\n event\n })\n );\n return;\n }\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n return createEnqueueObject(props, (action, ...args) => {\n pushBuiltInAction(actions, action, ...args);\n });\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableAction> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, id] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n id\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\nfunction createStartEffect(actor: AnyActor): StartExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\nexport function createSpawnEffect(\n actor: AnyActor\n): SpawnExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableActionObject {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error('Cannot terminate an active or stopped actor');\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableActionObject>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableActionObject>\n): StartExecutableActionObject[] {\n const attachedStarts: StartExecutableActionObject[] = [];\n const childStarts: StartExecutableActionObject[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\nexport function isBuiltInExecutableAction(\n action: ExecutableActionObject\n): action is SpecialExecutableAction {\n return action.kind === 'builtin';\n}\n\n/** Executes transition effects sequentially, awaiting each runtime operation. */\nexport async function executeEffects(\n effects: readonly ExecutableActionObject[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of actions) {\n const actionArgs = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n },\n actorScope\n )\n : {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n };\n\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...actionRecord.args)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (resolvedAction && '_special' in resolvedAction) {\n executableActions.push({\n kind: 'action',\n exec: execCustomEffect,\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : ((action as any).type ?? '(anonymous)')\n : action.name || '(anonymous)',\n params: actionParams,\n args: [],\n action: undefined\n });\n\n const specialAction = resolvedAction as unknown as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n\n const res = specialAction(actionArgs as any, emptyEnqueueObject);\n\n if (res && ('context' in res || 'children' in res)) {\n // Special-action patches never change `nodes`, so a shallow clone is\n // equivalent to `cloneMachineSnapshot` — and keeps this module (and\n // non-machine logic like `createFSM`) independent of State.ts.\n intermediateSnapshot = {\n ...intermediateSnapshot,\n ...(res.context !== undefined\n ? {\n context: mergeContextPatch(\n intermediateSnapshot.context,\n res.context\n )\n }\n : {}),\n ...('children' in res ? { children: res.children } : {})\n };\n }\n continue;\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, action.args)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action ? action.args : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableAction = executableAction as ExecutableActionObject;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableAction,\n actorScope\n );\n executableActions.push(typedExecutableAction);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n\nconst emptyEnqueueObject = createEnqueueObject({}, noop);\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\n}\n","import { hasAmbientInspector } from './inspectionAmbient.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${String(registryKey)}' already exists.`\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import { createActor } from './createActor.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport {\n createSnapshotSystem,\n getSnapshotActorRef,\n getSnapshotActorRefProvider,\n peekSnapshotActorRef,\n setLazySnapshotActorRef,\n setSnapshotActorRef,\n type SnapshotActorRef\n} from './snapshotActorRef.ts';\nimport {\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport { lazyActorScope } from './actorScope.ts';\n\n/** @internal */\nexport function setInertActorScopeSnapshot<T>(\n actorScope: AnyActorScope,\n snapshot: T,\n attachActorRef = true\n): T {\n const lazyState = getLazyInertActorState(actorScope);\n if (lazyState) {\n lazyState.snapshot = snapshot;\n if (lazyState.materialized) {\n (lazyState.materialized.self as any)._snapshot = snapshot;\n }\n } else {\n (actorScope.self as any)._snapshot = snapshot;\n }\n if (attachActorRef && snapshot && typeof snapshot === 'object') {\n setSnapshotActorRef(snapshot as any, actorScope.self);\n }\n return snapshot;\n}\n\n/** @internal */\nexport function isInertActorScope(actorScope: AnyActorScope): boolean {\n return (\n !!getLazyInertActorState(actorScope) ||\n !!(actorScope.self as any).options?._inert\n );\n}\n\n/** @internal */\nexport function attachSnapshotActorRef<TSnapshot>(\n actorScope: AnyActorScope,\n snapshot: TSnapshot\n): TSnapshot {\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const lazyState = getLazyInertActorState(actorScope);\n snapshotActorScopes.set(snapshot as object, actorScope);\n const create = () => {\n setSnapshotActorRef(\n snapshot as Snapshot<unknown>,\n actorScope.self,\n actorScope.system\n );\n return getSnapshotActorRef(snapshot as Snapshot<unknown>)!;\n };\n if (lazyState) {\n if (lazyState.materialized) {\n lazyState.identityProvider = create;\n } else {\n lazyState.identityProvider ??= create;\n }\n }\n setLazySnapshotActorRef(snapshot as Snapshot<unknown>, create);\n return snapshot;\n}\n\ntype LazyInertActorState = {\n snapshot: unknown;\n materialized?: AnyActorScope;\n sourceRef?: () => SnapshotActorRef;\n sourceChildren: Record<string, AnyActor | undefined>;\n identityProvider?: () => SnapshotActorRef;\n parent?: AnyActor;\n parentKnown: boolean;\n materialize: () => AnyActorScope;\n};\n\nconst lazyInertActorState = Symbol();\ntype LazyInertActorScope = AnyActorScope & {\n [lazyInertActorState]?: LazyInertActorState;\n};\nconst snapshotActorScopes = new WeakMap<object, AnyActorScope>();\nlet inertActorMaterializationObserver: (() => void) | undefined;\n\nfunction getLazyInertActorState(\n actorScope: AnyActorScope\n): LazyInertActorState | undefined {\n return (actorScope as LazyInertActorScope)[lazyInertActorState];\n}\n\nfunction materializeInertActorScope(actorScope: AnyActorScope): AnyActorScope {\n return getLazyInertActorState(actorScope)!.materialize();\n}\n\nconst lazyInertActorScopePrototype = {\n [lazyActorScope]: true,\n get _parent() {\n const actorScope = this as AnyActorScope;\n const state = getLazyInertActorState(actorScope)!;\n return state.parentKnown\n ? state.parent\n : materializeInertActorScope(actorScope).self._parent;\n },\n get self() {\n return materializeInertActorScope(this as AnyActorScope).self;\n },\n get defer() {\n return materializeInertActorScope(this as AnyActorScope).defer;\n },\n get id() {\n return materializeInertActorScope(this as AnyActorScope).id;\n },\n get logger() {\n return materializeInertActorScope(this as AnyActorScope).logger;\n },\n get sessionId() {\n return materializeInertActorScope(this as AnyActorScope).sessionId;\n },\n get stopChild() {\n return materializeInertActorScope(this as AnyActorScope).stopChild;\n },\n get system() {\n return materializeInertActorScope(this as AnyActorScope).system;\n },\n get emit() {\n return materializeInertActorScope(this as AnyActorScope).emit;\n },\n get actionExecutor() {\n return materializeInertActorScope(this as AnyActorScope).actionExecutor;\n }\n};\n\n/** Test-only allocation instrumentation. @internal */\nexport function setInertActorMaterializationObserver(\n observer: (() => void) | undefined\n): void {\n inertActorMaterializationObserver = observer;\n}\n\nfunction createMaterializedInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n sourceRef: (() => SnapshotActorRef) | undefined,\n sourceChildren: Record<string, AnyActor | undefined>,\n currentSnapshot: SnapshotFrom<T> | undefined,\n sourceSelf?: AnyActor\n): AnyActorScope {\n inertActorMaterializationObserver?.();\n const snapshotRef = sourceRef?.();\n const previousSelf = sourceSelf ?? snapshotRef?.actor;\n const baseSystem = previousSelf?.system;\n const system =\n previousSelf && baseSystem\n ? createSnapshotSystem(\n baseSystem,\n sourceChildren,\n sourceSelf ? undefined : snapshotRef?.systemState\n )\n : undefined;\n const self = createActor(\n actorLogic as AnyActorLogic,\n {\n _inert: true,\n ...(previousSelf\n ? {\n id: previousSelf.id,\n _sessionId: previousSelf.sessionId\n }\n : {}),\n ...(system ? { _systemRef: { current: system } } : {})\n } as any\n );\n if (previousSelf?._parent) {\n self._parent = previousSelf._parent;\n // `address` memoizes on first read assuming `_parent` is final; nothing\n // reads it between construction and this assignment, but drop any memo so\n // a future construction-time read cannot pin a root-shaped address.\n (self as unknown as { _address?: string })._address = undefined;\n }\n if (currentSnapshot) {\n (self as any)._snapshot = currentSnapshot;\n }\n\n // Reuse the branch actor's scope while keeping planning transactional.\n return Object.create((self as any)._actorScope, {\n defer: { value: () => {} },\n stopChild: { value: (child: AnyActor) => (child as any)._stop() },\n actionExecutor: { value: () => {} }\n });\n}\n\n/** @internal */\nexport function createInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot?: SnapshotFrom<T>,\n sourceSelf?: AnyActor,\n sourceActorScope?: AnyActorScope\n): AnyActorScope {\n const sourceScope =\n sourceActorScope ??\n (snapshot && typeof snapshot === 'object'\n ? snapshotActorScopes.get(snapshot as object)\n : undefined);\n const sourceState = sourceScope\n ? getLazyInertActorState(sourceScope)\n : undefined;\n const eagerSourceRef =\n snapshot && typeof snapshot === 'object'\n ? peekSnapshotActorRef(snapshot as Snapshot<unknown>)\n : undefined;\n const sourceRef =\n sourceState?.identityProvider ??\n (snapshot && typeof snapshot === 'object'\n ? getSnapshotActorRefProvider(snapshot as Snapshot<unknown>)\n : undefined);\n const state = {\n snapshot,\n sourceRef,\n sourceChildren: isMachineSnapshot(snapshot)\n ? (snapshot as any).children\n : {},\n identityProvider: sourceState?.identityProvider ?? sourceRef,\n parent:\n sourceSelf?._parent ??\n sourceState?.parent ??\n eagerSourceRef?.actor._parent,\n parentKnown:\n !!sourceSelf ||\n !!sourceState?.parentKnown ||\n !!eagerSourceRef ||\n !snapshot\n } as LazyInertActorState;\n state.materialize = () =>\n (state.materialized ??= createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n state.snapshot as SnapshotFrom<T>,\n sourceSelf\n ));\n if (!state.identityProvider && !snapshot) {\n const identitySnapshot = {} as Snapshot<unknown>;\n const identitySourceRef = state.sourceRef;\n const identitySourceChildren = state.sourceChildren;\n let identityScope: AnyActorScope | undefined;\n let identityRef: SnapshotActorRef | undefined;\n const getIdentityScope = () =>\n (identityScope ??= createMaterializedInertActorScope(\n actorLogic,\n identitySourceRef,\n identitySourceChildren,\n undefined,\n sourceSelf\n ));\n state.materialize = () => {\n const scope = getIdentityScope();\n if (state.snapshot !== undefined) {\n (scope.self as any)._snapshot = state.snapshot;\n }\n return (state.materialized = scope);\n };\n state.identityProvider = () => {\n if (identityRef) {\n return identityRef;\n }\n const scope = getIdentityScope();\n setSnapshotActorRef(identitySnapshot, scope.self, scope.system);\n return (identityRef = getSnapshotActorRef(identitySnapshot)!);\n };\n }\n const actorScope = Object.create(lazyInertActorScopePrototype) as ActorScope<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n any,\n EmittedFrom<T>\n >;\n (actorScope as LazyInertActorScope)[lazyInertActorState] = state;\n return actorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nexport function getInitialSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.initialTransition(input, actorScope)[0];\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @deprecated Use `transition(…)` instead.\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * undefined, // snapshot (or initial state if undefined)\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * nextSnapshot, // snapshot\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nexport function getNextSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic, snapshot);\n const transitionResult = actorLogic.transition(snapshot, event, actorScope);\n const nextSnapshot = Array.isArray(transitionResult)\n ? transitionResult[0]\n : transitionResult;\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n return nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(actorScope, nextSnapshot);\n}\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport {\n createAfterEvent,\n createAfterEventId,\n createDoneStateEvent,\n createInvokeTimeoutEvent,\n createInvokeTimeoutEventId,\n createTimeoutEvent,\n createTimeoutEventId\n} from './eventUtils.ts';\nimport {\n XSTATE_INIT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n XSTATE_TIMER\n} from './constants.ts';\nimport {\n getEventOutput,\n isErrorEvent,\n matchesEvent,\n matchesEventDescriptor\n} from './utils.ts';\nimport {\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n ExecutableActionObject,\n HistoryValue,\n MachineContext,\n StateValue,\n TransitionDefinition,\n AnyAction,\n AnyTransitionConfig,\n AnyActor,\n AnyActorScope,\n DoneStateEvent\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n resolveReferencedActor,\n toTransitionConfigArray\n} from './utils.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n assertChildIdFree,\n createEnqueueObject,\n createTerminationEffect,\n createTransitionEnqueue,\n createSendToEffect,\n deriveDeferredStarts,\n mergeContextPatch,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { parseDurationToMilliseconds } from './delay.ts';\nimport { transitionEffectSignal, transitionEffectTargets } from './system.ts';\nimport { isInertActorScope } from './getNextSnapshot.ts';\nimport {\n getActorScopeParent,\n isLazyActorScope,\n withActorSelfAndParent,\n withActorScope\n} from './actorScope.ts';\n\ntype AnyStateNodeIterable = Iterable<AnyStateNode>;\n\nfunction getConfiguredDelayValue(\n delay: number | string,\n delaySource: Record<string, any>\n) {\n if (typeof delay !== 'string') {\n return delay;\n }\n\n const referencedDelay = delaySource[delay];\n if (referencedDelay !== undefined) {\n return referencedDelay;\n }\n\n return parseDurationToMilliseconds(delay) ?? delay;\n}\n\nfunction resolveDelay(\n delay: number | string | ((args: any) => number),\n delaySource: Record<string, any>,\n args: {\n context: MachineContext;\n event: EventObject;\n stateNode: AnyStateNode;\n input?: Record<string, unknown>;\n }\n) {\n if (typeof delay === 'function') {\n return delay(args);\n }\n\n const configuredDelay = getConfiguredDelayValue(delay, delaySource);\n if (typeof configuredDelay === 'function') {\n return configuredDelay(args);\n }\n\n return configuredDelay;\n}\n\nfunction getStateInput(snapshot: AnyMachineSnapshot, stateNodeId: string) {\n return snapshot._stateInputs?.[stateNodeId];\n}\n\nexport function isAtomicStateNode(stateNode: AnyStateNode) {\n return (\n stateNode.type === 'atomic' ||\n stateNode.type === 'final' ||\n stateNode.type === 'choice'\n );\n}\n\nfunction getChildren(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nexport function getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n const activeParentSet = new Set<AnyStateNode>();\n for (const stateNode of nodeSet) {\n if (stateNode.parent) {\n activeParentSet.add(stateNode.parent);\n }\n }\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && !activeParentSet.has(s)) {\n for (const sn of getInitialStateNodes(s)) {\n nodeSet.add(sn);\n }\n continue;\n }\n\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodes(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n\n // add all ancestors\n // Stop walking up as soon as we hit a node already in the set: its own\n // ancestor chain is guaranteed to be added when it is visited by this loop\n // (Set iteration visits elements added during iteration), so shared ancestor\n // chains are never re-walked once per descendant.\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m && !nodeSet.has(m)) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n const adjList = new Map<AnyStateNode, Array<AnyStateNode>>();\n\n for (const s of config) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (!s.parent) {\n continue;\n }\n\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n\n const getValueFromAdj = (baseNode: AnyStateNode): StateValue => {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (!childStateNode) {\n return {};\n }\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode);\n }\n\n return stateValue;\n };\n\n return getValueFromAdj(rootNode);\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nfunction getLegacyEventType(event: EventObject): string | undefined {\n switch (event.type) {\n case 'xstate.done.actor':\n case 'xstate.error.actor':\n return `${event.type}.${(event as any).actorId}`;\n case 'xstate.snapshot.actor':\n return `xstate.snapshot.${(event as any).actorId}`;\n case 'xstate.done.state':\n return `xstate.done.state.${(event as any).stateId}`;\n case 'xstate.after':\n return `xstate.after.${(event as any).delay}.${(event as any).stateId}`;\n case 'xstate.timeout':\n return `xstate.timeout.${(event as any).stateId}`;\n case 'xstate.timeout.actor':\n return `xstate.timeout.actor.${(event as any).actorId}`;\n default:\n return undefined;\n }\n}\n\nfunction getEventTypeAliases(event: EventObject): string[] {\n const legacyType = getLegacyEventType(event);\n return legacyType ? [event.type, legacyType] : [event.type];\n}\n\nexport function getEventDescriptorKey(event: EventObject): string {\n const legacyType = getLegacyEventType(event);\n return legacyType ? `${event.type}|${legacyType}` : event.type;\n}\n\nexport function matchesActorSession(\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorId: string\n): boolean {\n const child = snapshot.children[actorId];\n if (!child || !('sessionId' in event)) {\n return true;\n }\n // One rule: a ref that knows its incarnation compares it; a remote handle\n // without a host-supplied token (sessionId undefined) defers to the\n // runtime that owns the child.\n return (\n child.sessionId === undefined ||\n child.sessionId === (event as { sessionId?: string }).sessionId\n );\n}\n\nfunction normalizeLegacyInternalEvent(\n event: EventObject,\n machine: AnyStateMachine\n): EventObject {\n if (\n event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.done.state' ||\n event.type === 'xstate.after' ||\n event.type === 'xstate.timeout' ||\n event.type === 'xstate.timeout.actor'\n ) {\n return event;\n }\n\n const normalizeWithId = (\n prefix: string,\n type: string,\n idKey: 'actorId' | 'stateId'\n ) =>\n event.type.startsWith(prefix)\n ? {\n ...event,\n type,\n [idKey]: (event as any)[idKey] ?? event.type.slice(prefix.length)\n }\n : undefined;\n\n const normalized =\n normalizeWithId('xstate.done.actor.', 'xstate.done.actor', 'actorId') ??\n normalizeWithId('xstate.error.actor.', 'xstate.error.actor', 'actorId') ??\n normalizeWithId('xstate.snapshot.', 'xstate.snapshot.actor', 'actorId') ??\n normalizeWithId('xstate.done.state.', 'xstate.done.state', 'stateId') ??\n normalizeWithId(\n 'xstate.timeout.actor.',\n 'xstate.timeout.actor',\n 'actorId'\n ) ??\n normalizeWithId('xstate.timeout.', 'xstate.timeout', 'stateId');\n\n if (normalized) {\n return normalized;\n }\n\n const afterPrefix = 'xstate.after.';\n if (!event.type.startsWith(afterPrefix)) {\n return event;\n }\n\n const stateId = [...machine.idMap.keys()]\n .sort((a, b) => b.length - a.length)\n .find((id) => event.type.endsWith(`.${id}`));\n if (!stateId) {\n return event;\n }\n const delayText = event.type.slice(afterPrefix.length, -stateId.length - 1);\n return {\n ...event,\n type: 'xstate.after',\n delay: Number.isNaN(+delayText) ? delayText : +delayText,\n stateId\n } as AnyEventObject;\n}\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n event: TEvent\n): Array<TransitionDefinition<any, TEvent>> {\n const eventTypes = getEventTypeAliases(event);\n const exactMatches = eventTypes.flatMap(\n (eventType) => stateNode.transitions.get(eventType) ?? []\n );\n const wildcardCandidates = [...stateNode.transitions.keys()]\n .filter(\n (eventDescriptor) =>\n !eventTypes.includes(eventDescriptor) &&\n eventTypes.some((eventType) =>\n matchesEventDescriptor(eventType, eventDescriptor)\n )\n )\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return exactMatches.length\n ? [...exactMatches, ...wildcardCandidates]\n : wildcardCandidates;\n}\n\nfunction scheduleDelayedEvent(\n stateNode: AnyStateNode,\n timerId: string,\n resolveEvent: (args: any) => AnyEventObject,\n resolveScheduledDelay: (x: {\n context: MachineContext;\n event: EventObject;\n delays: Record<string, any>;\n input?: Record<string, unknown>;\n }) => any\n) {\n const oldEntry = stateNode.entry;\n stateNode.entry = (x: any, enq: any) => {\n enq.raise(resolveEvent(x) as any, {\n id: timerId,\n delay: resolveScheduledDelay(x)\n });\n return typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;\n };\n const oldExit = stateNode.exit;\n stateNode.exit = (_: any, enq: any) => {\n enq.cancel(timerId);\n return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;\n };\n}\n\n/** All delayed transitions from the config. */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n const timeoutConfig = (stateNode.config as any).timeout;\n const onTimeoutConfig = (stateNode.config as any).onTimeout;\n const invokeDefs = stateNode.invoke.filter(\n (invokeDef) => invokeDef.timeout !== undefined\n );\n\n if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {\n return [];\n }\n\n if (isDevelopment && timeoutConfig !== undefined && !onTimeoutConfig) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n\n if (isDevelopment) {\n for (const invokeDef of invokeDefs) {\n if (!invokeDef.onTimeout) {\n throw new Error(\n `Invoke on state \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n }\n }\n\n // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and\n // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on\n // entry (and cancelled on exit) plus a transition that catches it. They\n // differ only in the event raised, the transition(s) caught, and whether the\n // delay resolves against the machine's `delays` map (invoke timeouts do not).\n //\n // `xstate.timeout` is a dedicated event category so a state-level `timeout`\n // cannot collide with an explicit `after` entry on the same state. Invoke\n // timeouts are scheduled on the enclosing state; completion transitions\n // cancel the timer separately, so it clears even when the parent stays active.\n const sources: Array<{\n event: AnyEventObject;\n timerId: string;\n resolveEvent?: (args: any) => AnyEventObject;\n eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n delay: any;\n transitions: unknown;\n fromDelaysMap: boolean;\n }> = [];\n\n if (afterConfig) {\n for (const key of Object.keys(afterConfig)) {\n const delay = Number.isNaN(+key) ? key : +key;\n sources.push({\n event: createAfterEvent(delay, stateNode.id),\n timerId: createAfterEventId(delay, stateNode.id),\n delay,\n transitions: afterConfig[key],\n fromDelaysMap: true\n });\n }\n }\n\n if (timeoutConfig !== undefined && onTimeoutConfig) {\n sources.push({\n event: createTimeoutEvent(stateNode.id),\n timerId: createTimeoutEventId(stateNode.id),\n delay: timeoutConfig,\n transitions: onTimeoutConfig,\n fromDelaysMap: true\n });\n }\n\n for (const invokeDef of invokeDefs) {\n sources.push({\n event: createInvokeTimeoutEvent(invokeDef.id),\n timerId: createInvokeTimeoutEventId(invokeDef.id),\n resolveEvent: ({ children }: any) =>\n createInvokeTimeoutEvent(\n invokeDef.id,\n children[invokeDef.id]?.sessionId\n ),\n eventMatcher: (event, snapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id),\n delay: invokeDef.timeout!,\n transitions: invokeDef.onTimeout,\n fromDelaysMap: false\n });\n }\n\n // `delay` here is the raw config value, retained only as metadata on the\n // transition definition — the live delay is resolved at runtime in the\n // scheduled entry action, so no eager resolution is needed.\n const delayedTransitions: Array<\n AnyTransitionConfig & {\n event: string;\n delay: any;\n _eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n }\n > = [];\n\n for (const {\n event,\n timerId,\n resolveEvent,\n eventMatcher,\n delay,\n transitions,\n fromDelaysMap\n } of sources) {\n scheduleDelayedEvent(\n stateNode,\n timerId,\n resolveEvent ?? (() => event),\n (x) =>\n resolveDelay(delay, fromDelaysMap ? x.delays : {}, {\n context: x.context,\n event: x.event,\n stateNode,\n input: x.input\n })\n );\n const { type: eventType, ...eventPattern } = event;\n for (const transition of toTransitionConfigArray(transitions as any)) {\n delayedTransitions.push({\n ...transition,\n matches: {\n ...transition.matches,\n ...Object.fromEntries(\n Object.entries(eventPattern).filter(\n ([, value]) => value !== undefined\n )\n )\n },\n event: eventType,\n delay,\n _eventMatcher: eventMatcher\n });\n }\n }\n\n return delayedTransitions.map((delayedTransition) => ({\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition as AnyTransitionConfig\n ),\n delay: delayedTransition.delay\n }));\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n assertLegalTargetSet(stateNode, target);\n\n const transition = {\n ...transitionConfig,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nfunction isStateNodeDescendantOf(\n stateNode: AnyStateNode,\n ancestor: AnyStateNode\n): boolean {\n for (let current = stateNode.parent; current; current = current.parent) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLeastCommonStateNodeAncestor(\n left: AnyStateNode,\n right: AnyStateNode\n): AnyStateNode | undefined {\n const leftAncestors = new Set<AnyStateNode>();\n for (\n let current: AnyStateNode | undefined = left;\n current;\n current = current.parent\n ) {\n leftAncestors.add(current);\n }\n for (\n let current: AnyStateNode | undefined = right;\n current;\n current = current.parent\n ) {\n if (leftAncestors.has(current)) {\n return current;\n }\n }\n return undefined;\n}\n\nfunction assertLegalTargetSet(\n source: AnyStateNode,\n targets: readonly AnyStateNode[] | undefined\n): void {\n if (!targets || targets.length < 2) {\n return;\n }\n for (let leftIndex = 0; leftIndex < targets.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < targets.length;\n rightIndex++\n ) {\n const left = targets[leftIndex];\n const right = targets[rightIndex];\n const commonAncestor = getLeastCommonStateNodeAncestor(left, right);\n if (\n left === right ||\n isStateNodeDescendantOf(left, right) ||\n isStateNodeDescendantOf(right, left) ||\n commonAncestor?.type !== 'parallel'\n ) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${source.id}': target set is not a legal SCXML configuration.`\n : `Invalid target set for '${source.id}'`\n );\n }\n }\n }\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nexport function formatRouteTransitions(rootStateNode: AnyStateNode): void {\n const routeTransitions: AnyTransitionDefinition[] = [];\n const collectRoutes = (states: Record<string, AnyStateNode>) => {\n Object.values(states).forEach((sn) => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const routeConfig = sn.config.route;\n const routeMatches = ({ event }: { event: any }) =>\n event.to === `#${routeId}`;\n\n if (typeof routeConfig === 'function') {\n // Transition-style route: the function is the guard and resolver.\n // Returning undefined/false blocks the route; returning true or a\n // config object allows it.\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', {\n guard: routeMatches,\n to: (args: any) => {\n const result = routeConfig(args);\n if (!result) {\n return undefined;\n }\n return {\n ...(result === true ? {} : result),\n target: `#${routeId}`\n };\n }\n } as AnyTransitionConfig)\n );\n if (sn.states) {\n collectRoutes(sn.states);\n }\n return;\n }\n\n const { guard: _guard, ...routeOptions } = routeConfig as any;\n const transition: AnyTransitionConfig = {\n ...routeOptions,\n guard: routeMatches,\n target: `#${routeId}`\n };\n\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', transition)\n );\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions as any);\n }\n}\n\nfunction resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map((target) => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n : `Invalid transition for '${stateNode.id}': ${err.message}`\n );\n }\n } else {\n throw new Error(\n isDevelopment\n ? `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n : `Invalid target: \"${target}\"`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition(\n stateNode: AnyStateNode & { type: 'history' }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n if (stateNode.parent!.type === 'parallel') {\n return {\n target: [stateNode.parent!],\n source: stateNode,\n reenter: false,\n eventType: '' as any\n };\n }\n return stateNode.parent!.initial as AnyTransitionDefinition;\n }\n const target = normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n assertLegalTargetSet(stateNode, target);\n return {\n target,\n source: stateNode,\n reenter: false,\n eventType: '' as any,\n to: (stateNode.config as any)._historyDefaultTransition\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const target of descStateNode.initial.target ?? []) {\n iter(target);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n for (const initialState of set) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n set.add(ancestor);\n }\n }\n\n return set;\n}\n\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n const result = stateNode.states?.[stateKey];\n if (!result) {\n throw new Error(\n isDevelopment && !stateNode.states\n ? `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n : `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n );\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift()!;\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nexport function getStateNodes(\n stateNode: AnyStateNode,\n stateValue: StateValue\n): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(\n `State '${stateValue}' does not exist on '${stateNode.id}'`\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = new Array<AnyStateNode>(childStateKeys.length);\n const allStateNodes: Array<AnyStateNode> = [\n stateNode.machine.root,\n stateNode\n ];\n\n for (let i = 0; i < childStateKeys.length; i++) {\n const subStateNode = getStateNode(stateNode, childStateKeys[i]);\n childStateNodes[i] = subStateNode;\n allStateNodes.push(subStateNode);\n }\n\n for (let i = 0; i < childStateKeys.length; i++) {\n allStateNodes.push(\n ...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]!)\n );\n }\n\n return allStateNodes;\n}\n\nexport type TransitionSelectionResult = {\n enabled: boolean;\n result: unknown;\n reusable: boolean;\n};\n\nexport type TransitionSelectionResults = Map<\n AnyTransitionDefinition,\n TransitionSelectionResult\n>;\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any // TStateSchema\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const subStateKeys = Object.keys(stateValue);\n const subStateKey = subStateKeys[0];\n\n if (subStateKeys.length === 1) {\n const childStateNode = getStateNode(stateNode, subStateKey);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKey]!,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of subStateKeys) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return allInnerTransitions;\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction hasDescendantState(\n stateNodes: Set<AnyStateNode>,\n parentStateNode: AnyStateNode\n): boolean {\n for (const stateNode of stateNodes) {\n if (isDescendant(stateNode, parentStateNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const s1Size =\n s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;\n const s2Size =\n s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;\n\n if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {\n [s1, s2] = [s2, s1];\n }\n\n const set1 = s1 instanceof Set ? s1 : new Set(s1);\n for (const item of s2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n const exitSets = new Map<AnyTransitionDefinition, Array<AnyStateNode>>();\n\n const getExitSet = (transition: AnyTransitionDefinition) => {\n let exitSet = exitSets.get(transition);\n if (!exitSet) {\n exitSet = computeExitSet(\n [transition],\n stateNodeSet,\n snapshot,\n resolveTransition\n );\n exitSets.set(transition, exitSet);\n }\n\n return exitSet;\n };\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(getExitSet(t1), getExitSet(t2))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else if (t2.source.type === 'final' && t1.source.type !== 'final') {\n // A transition sourced in a final state yields to a conflicting\n // transition from a live state, so a done region doesn't keep\n // consuming events its siblings can still handle.\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n\n return Array.from(filteredTransitions);\n}\n\ntype ResolvableTransition = Parameters<typeof getTransitionResult>[0];\ntype TransitionResultResolver = (\n transition: ResolvableTransition\n) => ReturnType<typeof getTransitionResult>;\n\nfunction createTransitionResultResolver(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n resolveActions: boolean,\n selectionResults?: TransitionSelectionResults\n): TransitionResultResolver {\n let cache:\n | Map<ResolvableTransition, ReturnType<typeof getTransitionResult>>\n | undefined;\n return (transition) => {\n if (!transition.to) {\n return getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n }\n let result = cache?.get(transition);\n if (!result) {\n result = getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n (cache ??= new Map()).set(transition, result);\n }\n return result;\n };\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target' | 'source'>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const historyValue = snapshot.historyValue;\n const { targets } = resolveTransition(transition);\n if (!targets) {\n return [];\n }\n\n const targetSet = new Set<AnyStateNode>();\n\n for (const targetNode of targets) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targetSet.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n snapshot,\n resolveTransition\n )) {\n targetSet.add(node);\n }\n }\n } else {\n targetSet.add(targetNode);\n }\n }\n\n return [...targetSet];\n}\n\n/**\n * Narrows a parallel domain to the single child region that contains every\n * effective target, so that a transition confined to one region does not exit\n * (and reset) its sibling regions.\n */\nfunction narrowParallelDomain(\n domain: AnyStateNode,\n targetStates: Array<AnyStateNode>\n): AnyStateNode {\n let narrowed = domain;\n while (narrowed.type === 'parallel') {\n const region = getChildren(narrowed).find((child) =>\n targetStates.every(\n (target) => target === child || isDescendant(target, child)\n )\n );\n if (!region) {\n break;\n }\n narrowed = region;\n }\n return narrowed;\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(\n transition,\n snapshot,\n resolveTransition\n );\n\n const { targets, reenter } = resolveTransition(transition);\n\n if (transition._transitionDomain) {\n if (\n transition._transitionDomain === 'internal' &&\n transition.source.type === 'compound' &&\n targetStates.every((target) => isDescendant(target, transition.source))\n ) {\n return transition.source;\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (\n ancestor.type === 'compound' &&\n tail.every((stateNode) => isDescendant(stateNode, ancestor))\n ) {\n return ancestor;\n }\n }\n\n return;\n }\n\n // A history target that restores the source itself must exit and reenter\n // the source (SCXML domain = the source's ancestor), unlike a plain\n // non-reentering self-target: the enter set restores the stored\n // configuration from outside the source, so the exit set must match or the\n // source's invoked actors are re-created without being stopped.\n const restoresSourceViaHistory =\n targets?.some(isHistoryNode) &&\n targetStates.some((target) => target === transition.source);\n\n if (\n !restoresSourceViaHistory &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n // Targets are contained within the source. A reentering transition\n // exits and reenters the source itself; otherwise the domain narrows\n // past parallel nodes so sibling regions are left untouched.\n return reenter\n ? transition.source\n : narrowParallelDomain(transition.source, targetStates);\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n // Find the least common ancestor (LCA) of the source and effective targets.\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n // A cross-region transition (source in one parallel region, targets in\n // another) only exits the region containing its targets; the source\n // region and other sibling regions stay put unless it reenters.\n return reenter ? ancestor : narrowParallelDomain(ancestor, targetStates);\n }\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (reenter) {\n return;\n }\n\n return narrowParallelDomain(transition.source.machine.root, targetStates);\n}\n\nfunction computeExitSet(\n transitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n for (const transition of transitions) {\n const { targets, reenter } = resolveTransition(transition);\n\n if (targets?.length) {\n const domain = getTransitionDomain(\n transition,\n snapshot,\n resolveTransition\n );\n\n if (reenter && transition.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\ntype Microstep = readonly [AnyMachineSnapshot, ExecutableActionObject[]];\n\nexport function initialMicrostep(\n root: AnyStateNode,\n preInitialState: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n initEvent: AnyEventObject,\n internalQueue: AnyEventObject[]\n): Microstep {\n const initialStateNodes = [...getInitialStateNodes(root)];\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const collectDefaultEntryStates = (stateNode: AnyStateNode): void => {\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n for (const target of stateNode.initial.target ?? []) {\n collectDefaultEntryStates(target);\n }\n } else if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n collectDefaultEntryStates(child);\n }\n }\n };\n collectDefaultEntryStates(root);\n return microstep(\n [\n {\n target: initialStateNodes.filter(\n (stateNode) =>\n !initialStateNodes.some(\n (other) => other !== stateNode && isDescendant(other, stateNode)\n )\n ),\n source: root,\n reenter: true,\n eventType: null as any,\n toJSON: null as any,\n _statesForDefaultEntry: [...statesForDefaultEntry]\n } as AnyTransitionDefinition\n ],\n preInitialState,\n actorScope,\n initEvent,\n true,\n internalQueue\n );\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>,\n selectionResults?: TransitionSelectionResults\n): Microstep {\n const executableActions: ExecutableActionObject[] = [];\n\n if (!transitions.length) {\n return [currentSnapshot, executableActions];\n }\n\n {\n const mutStateNodeSet = new Set(currentSnapshot.nodes as StateNode[]);\n let historyValue = currentSnapshot.historyValue;\n const originalContext = currentSnapshot.context;\n\n const filteredTransitions =\n transitions.length === 1\n ? transitions\n : removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n currentSnapshot,\n createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n false,\n selectionResults\n )\n );\n const getCurrentTransitionResult = createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n true,\n selectionResults\n );\n const changesState = filteredTransitions.some((transition) => {\n const { targets, reenter } = getCurrentTransitionResult(transition);\n return !!targets?.length || !!reenter;\n });\n const getStateActionsAndContext = (\n transitionFn: any,\n context: MachineContext,\n children: AnyMachineSnapshot['children'],\n input: Record<string, unknown> | undefined\n ): [\n actions: any[],\n context: MachineContext | undefined,\n internalEvents: EventObject[] | undefined\n ] => {\n if (transitionFn.length === 2) {\n // enqueue action; retrieve\n const actions: any[] = [];\n const internalEvents: EventObject[] = [];\n let updatedContext: MachineContext | undefined;\n\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true\n );\n\n const args = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context,\n event,\n children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n },\n actorScope\n )\n : {\n context,\n event,\n parent: actorScope.self._parent,\n self: actorScope.self,\n children,\n system: actorScope.system,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n };\n const res = transitionFn(args, enqueue);\n\n if (res?.context !== undefined) {\n updatedContext = mergeContextPatch(context, res.context);\n }\n\n return [actions, updatedContext, internalEvents];\n }\n\n // For 1-argument actions, wrap them to include input\n // Preserve _special flag if present (for entry/exit actions)\n const wrappedAction = Object.assign(\n (args: any, enqueue: any) =>\n transitionFn(\n isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: args.context,\n event: args.event,\n output: args.output,\n children: args.children,\n actions: args.actions,\n actors: args.actors,\n input\n },\n actorScope\n )\n : { ...args, input },\n enqueue\n ),\n '_special' in transitionFn ? { _special: true } : {}\n );\n return [[wrappedAction], undefined, undefined];\n };\n\n let nextState = currentSnapshot;\n const getInvokeStopActions = (\n stateNode: AnyStateNode,\n children: AnyMachineSnapshot['children']\n ): AnyAction[] => {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const invokeDef of stateNode.invoke) {\n const child = children[invokeDef.id];\n if (child) {\n enqueue.stop(child);\n }\n }\n return actions;\n };\n const exitStates = () => {\n const statesToExit = computeExitSet(\n filteredTransitions,\n mutStateNodeSet,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: HistoryValue | undefined;\n const currentStateNodes = [...mutStateNodeSet];\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of Object.values(exitStateNode.states)) {\n if (historyNode.type !== 'history') {\n continue;\n }\n\n const predicate =\n historyNode.history === 'deep'\n ? (sn: AnyStateNode) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode)\n : (sn: AnyStateNode) => sn.parent === exitStateNode;\n\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] = currentStateNodes.filter(predicate);\n }\n }\n\n for (const exitStateNode of statesToExit) {\n const stateInput = getStateInput(currentSnapshot, exitStateNode.id);\n\n const [exitActions, nextContext, internalEvents] = exitStateNode.exit\n ? getStateActionsAndContext(\n exitStateNode.exit,\n nextState.context,\n currentSnapshot.children,\n stateInput\n )\n : [[], undefined, undefined];\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n if (nextContext) {\n nextState = cloneMachineSnapshot(nextState, {\n context: nextContext\n });\n }\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n exitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const invokeStopActions = getInvokeStopActions(\n exitStateNode,\n nextState.children\n );\n if (invokeStopActions.length) {\n const [stoppedState, stopEffects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n invokeStopActions\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n }\n\n mutStateNodeSet.delete(exitStateNode);\n }\n\n historyValue = changedHistory || historyValue;\n };\n\n // Exit states\n if (!isInitial && changesState) {\n exitStates();\n }\n\n let context = nextState.context;\n const transitionActions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n\n for (const t of filteredTransitions) {\n if (t.actions) {\n transitionActions.push(...toArray(t.actions));\n }\n const res = getCurrentTransitionResult(t);\n if (res.context !== undefined) {\n context = mergeContextPatch(context, res.context);\n }\n if (res.actions) {\n transitionActions.push(...res.actions);\n }\n if (res.internalEvents) {\n internalEvents.push(...res.internalEvents);\n }\n }\n\n if (internalEvents.length) {\n internalQueue.push(...internalEvents);\n }\n\n const enterStates = () => {\n const getMachineOutput = (rootCompletionNode: AnyStateNode) => {\n const rootNode = nextState.machine.root;\n\n let completionOutput: unknown;\n if (\n rootCompletionNode.output !== undefined &&\n rootCompletionNode.parent\n ) {\n const rootDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootNode.id\n ) as DoneStateEvent | undefined;\n completionOutput =\n rootDoneEvent && rootCompletionNode.parent === rootNode\n ? rootDoneEvent.output\n : resolveOutput(\n rootCompletionNode.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[rootCompletionNode.id]\n );\n } else if (rootCompletionNode.type === 'parallel') {\n const parallelDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootCompletionNode.id\n ) as DoneStateEvent | undefined;\n completionOutput = parallelDoneEvent?.output;\n }\n\n if (rootNode.output === undefined) {\n return rootCompletionNode.parent === rootNode\n ? completionOutput\n : undefined;\n }\n\n return resolveOutput(\n rootNode.output,\n nextState.context,\n createDoneStateEvent(rootCompletionNode.id, completionOutput),\n actorScope.self\n );\n };\n\n const statesToEnter = new Set<AnyStateNode>();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const historyDefaultsByParent = new Map<\n AnyStateNode,\n AnyTransitionDefinition[]\n >();\n const addAncestorStatesToEnter = (\n ancestors: AnyStateNode[],\n reentrancyDomain: AnyStateNode | undefined\n ) => {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n }\n };\n\n const addDescendantStatesToEnter = (stateNode: AnyStateNode) => {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s);\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n } else {\n const historyDefaultTransition =\n resolveHistoryDefaultTransition(stateNode);\n const historyParent = stateNode.parent!;\n statesForDefaultEntry.add(historyParent);\n const defaults = historyDefaultsByParent.get(historyParent) ?? [];\n defaults.push(historyDefaultTransition);\n historyDefaultsByParent.set(historyParent, defaults);\n const { targets } = getCurrentTransitionResult(\n historyDefaultTransition\n );\n for (const s of targets ?? []) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(s);\n }\n\n for (const s of targets ?? []) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n }\n return;\n }\n\n if (stateNode.type === 'compound') {\n const initialStates =\n getCurrentTransitionResult(stateNode.initial).targets ?? [];\n\n for (const initialState of initialStates) {\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n }\n }\n statesForDefaultEntry.add(stateNode);\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(initialState);\n }\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n getProperAncestors(initialState, stateNode),\n undefined\n );\n }\n return;\n }\n\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n };\n\n for (const transition of filteredTransitions) {\n const domain = getTransitionDomain(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n const { targets, reenter } = getCurrentTransitionResult(transition);\n\n for (const targetNode of targets ?? []) {\n if (\n !isHistoryNode(targetNode) &&\n (transition.source !== targetNode ||\n transition.source !== domain ||\n reenter)\n ) {\n statesToEnter.add(targetNode);\n statesForDefaultEntry.add(targetNode);\n }\n addDescendantStatesToEnter(targetNode);\n }\n const targetStates = getEffectiveTargetStates(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(\n ancestors,\n !transition.source.parent && reenter ? undefined : domain\n );\n }\n if (reenter && domain === transition.source) {\n // A reentering transition whose domain is its own source exits and\n // reenters the source, so the source must be entered explicitly —\n // it has no ancestor inside the domain to add it.\n statesToEnter.add(transition.source);\n }\n }\n\n if (isInitial) {\n for (const stateNode of (filteredTransitions[0] as any)\n ._statesForDefaultEntry ?? [currentSnapshot.machine.root]) {\n statesForDefaultEntry.add(stateNode);\n }\n }\n\n const stateInputMap: Record<string, Record<string, unknown>> = {\n ...currentSnapshot._stateInputs\n };\n let stateInputsChanged = false;\n for (const transition of filteredTransitions) {\n const { targets, input } = getCurrentTransitionResult(transition);\n if (input && targets) {\n for (const targetNode of targets) {\n stateInputMap[targetNode.id] = input;\n stateInputsChanged = true;\n }\n }\n }\n\n const completedNodes = new Set<AnyStateNode>();\n const children = { ...nextState.children };\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: AnyAction[] = [];\n\n let invoked = false;\n for (const invokeDef of stateNodeToEnter.invoke) {\n invoked = true;\n\n let src = invokeDef.logic;\n if (typeof src === 'function') {\n src = src({\n actors: currentSnapshot.machine.sources.actors,\n context: nextState.context,\n event,\n self: actorScope.self\n });\n }\n\n const logic =\n typeof src === 'string'\n ? resolveReferencedActor(currentSnapshot.machine, src)\n : src;\n\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in machine '${currentSnapshot.machine.id}'`\n : `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented`\n );\n }\n\n const input =\n typeof invokeDef.input === 'function'\n ? invokeDef.input({\n self: actorScope.self,\n context: nextState.context,\n event,\n output: getEventOutput(event)\n })\n : invokeDef.input;\n\n assertChildIdFree(actorScope, invokeDef.id);\n const actor = actorScope.system.createActorRef(logic, {\n ...invokeDef,\n input,\n parent: actorScope.self,\n syncSnapshot: !!invokeDef.onSnapshot\n });\n\n actions.push({\n action: builtInActions['@xstate.spawn'],\n args: [actor]\n });\n\n if (invokeDef.id) {\n children[invokeDef.id] = actor;\n }\n }\n\n if (invoked) {\n nextState = cloneMachineSnapshot(nextState, { children });\n }\n let context = nextState.context;\n let contextChangedByEntry = false;\n\n const stateInput = stateInputMap[stateNodeToEnter.id];\n\n if (stateNodeToEnter.entry) {\n const [resultActions, nextContext, nextInternalEvents] =\n getStateActionsAndContext(\n stateNodeToEnter.entry,\n context,\n children,\n stateInput\n );\n actions.push(...resultActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n if (nextContext) {\n context = nextContext;\n contextChangedByEntry = true;\n }\n }\n\n if (contextChangedByEntry) {\n nextState.context = context;\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const defaultTransitions = [\n stateNodeToEnter.initial,\n ...(historyDefaultsByParent.get(stateNodeToEnter) ?? [])\n ].filter(Boolean);\n for (const defaultTransition of defaultTransitions) {\n const {\n actions: initialActions,\n context: initialContext,\n input: initialInput,\n internalEvents: initialInternalEvents\n } = getTransitionResult(\n defaultTransition,\n nextState,\n event,\n actorScope\n );\n if (initialActions) {\n actions.push(...initialActions);\n }\n if (initialInternalEvents?.length) {\n internalQueue.push(...initialInternalEvents);\n }\n if (initialContext !== undefined) {\n nextState.context = mergeContextPatch(\n nextState.context,\n initialContext\n );\n }\n if (initialInput && defaultTransition.target) {\n for (const targetNode of defaultTransition.target) {\n stateInputMap[targetNode.id] = initialInput;\n stateInputsChanged = true;\n }\n }\n }\n }\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n actions.length = 0;\n executableActions.push(...resolvedActions);\n\n if (stateNodeToEnter.type !== 'final') {\n continue;\n }\n\n const parent = stateNodeToEnter.parent;\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent.id,\n stateNodeToEnter.output !== undefined\n ? resolveOutput(\n stateNodeToEnter.output,\n nextState.context,\n event,\n actorScope.self,\n stateInput\n )\n : undefined\n )\n );\n }\n\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n const regionOutput: Record<string, unknown> = {};\n for (const region of getChildren(ancestorMarker)) {\n if (region.type === 'final') {\n regionOutput[region.key] =\n region.output !== undefined\n ? resolveOutput(\n region.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[region.id]\n )\n : undefined;\n continue;\n }\n\n if (region.type === 'parallel') {\n const regionDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === region.id\n ) as DoneStateEvent | undefined;\n regionOutput[region.key] = regionDoneEvent?.output;\n continue;\n }\n\n const finalChild = getChildren(region).find(\n (s) => s.type === 'final' && mutStateNodeSet.has(s)\n );\n regionOutput[region.key] =\n finalChild?.output !== undefined\n ? resolveOutput(\n finalChild.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[finalChild.id]\n )\n : undefined;\n }\n internalQueue.push(\n createDoneStateEvent(ancestorMarker.id, regionOutput)\n );\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextState = cloneMachineSnapshot(nextState, {\n status: 'done',\n output: getMachineOutput(rootCompletionNode)\n });\n }\n\n if (stateInputsChanged) {\n nextState = cloneMachineSnapshot(nextState, {\n _stateInputs: stateInputMap\n });\n }\n };\n\n // Execute transition content\n const [resolvedTransitionState, transitionExecutableActions] =\n resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n transitionActions\n );\n nextState = resolvedTransitionState;\n executableActions.push(...transitionExecutableActions);\n if (context && context !== currentSnapshot.context) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n // Enter states\n if (isInitial || changesState) {\n enterStates();\n }\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n const allExitActions: AnyAction[] = [];\n const nextStateNodesToExit = nextStateNodes.sort(\n (a, b) => b.order - a.order\n );\n\n nextStateNodesToExit.forEach((stateNode) => {\n if (stateNode.exit) {\n const stateInput = getStateInput(nextState, stateNode.id);\n const [exitActions, , nextInternalEvents] = getStateActionsAndContext(\n stateNode.exit,\n nextState.context,\n nextState.children,\n stateInput\n );\n allExitActions.push(...exitActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n }\n });\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n allExitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const [stoppedState, stopEffects] = stopChildren(\n nextState,\n event,\n actorScope\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n\n const [withoutTimers, cancelEffects] = cancelTimers(\n nextState,\n event,\n actorScope\n );\n nextState = withoutTimers;\n executableActions.push(...cancelEffects);\n }\n\n if (\n historyValue === currentSnapshot.historyValue &&\n currentSnapshot.nodes.length === mutStateNodeSet.size &&\n currentSnapshot.nodes.every((node) =>\n mutStateNodeSet.has(node as StateNode)\n )\n ) {\n // If context was changed (e.g. by entry actions during self-transition),\n // clone to ensure reference inequality for eventless transition re-evaluation\n if (nextState.context !== originalContext) {\n return [\n nextState === currentSnapshot\n ? cloneMachineSnapshot(nextState)\n : nextState,\n executableActions\n ];\n }\n return [nextState, executableActions];\n }\n\n return [\n cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }),\n executableActions\n ];\n }\n}\n\n/**\n * Gets the transition result for a given transition without executing the\n * transition.\n */\nexport function getTransitionResult(\n transition: Pick<AnyTransitionDefinition, 'target' | 'to' | 'source'> & {\n reenter?: AnyTransitionDefinition['reenter'];\n input?: AnyTransitionDefinition['input'];\n context?: AnyTransitionDefinition['context'];\n },\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n options?: {\n resolveActions?: boolean;\n selectionResult?: TransitionSelectionResult;\n }\n): {\n targets: Readonly<AnyStateNode[]> | undefined;\n context: MachineContext | undefined;\n actions: AnyAction[] | undefined;\n reenter?: boolean;\n internalEvents: EventObject[] | undefined;\n input: Record<string, unknown> | undefined;\n} {\n let transitionArgs: any;\n const getTransitionArgs = () =>\n (transitionArgs ??= isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n },\n actorScope\n )\n : {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n system: actorScope.system,\n parent: actorScope.self._parent,\n self: actorScope.self,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n });\n\n if (transition.to) {\n const actions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n const res = options?.selectionResult?.reusable\n ? options.selectionResult.result\n : transition.to(\n getTransitionArgs(),\n createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true,\n options?.resolveActions ?? true\n )\n );\n\n const targets = res?.target\n ? resolveTarget(transition.source, toArray(res.target) as string[])\n : undefined;\n\n const resolvedInput =\n res?.input ??\n (typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input);\n\n return {\n targets: targets,\n context: res?.context,\n reenter: res?.reenter,\n actions,\n internalEvents,\n input: resolvedInput\n };\n }\n\n // Resolve input for regular transitions\n const resolvedInput =\n typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input;\n const resolvedContext =\n typeof transition.context === 'function'\n ? transition.context(getTransitionArgs())\n : transition.context;\n\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: resolvedContext,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: resolvedInput\n };\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[],\n initialMicrosteps: Microstep[] = []\n): {\n snapshot: typeof snapshot;\n microsteps: Microstep[];\n} {\n let nextSnapshot = snapshot;\n const microsteps: Microstep[] = initialMicrosteps.slice();\n\n function removeTerminatedChild(terminalEvent: EventObject) {\n if (\n terminalEvent.type !== 'xstate.done.actor' &&\n terminalEvent.type !== 'xstate.error.actor'\n ) {\n return;\n }\n\n const { actorId, sessionId } = terminalEvent as AnyEventObject & {\n actorId?: string;\n sessionId?: string;\n };\n if (!actorId) {\n return;\n }\n const child = nextSnapshot.children[actorId];\n if (!child) {\n return;\n }\n // The same staleness rule matchesActorSession applies to transition\n // selection: a completion from a different incarnation must not remove\n // the still-running child either.\n if (child.sessionId !== undefined && child.sessionId !== sessionId) {\n return;\n }\n\n const children = { ...nextSnapshot.children };\n delete children[actorId];\n actorScope.system._unregister(child);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { children });\n\n if (microsteps.length) {\n const [, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [nextSnapshot, lastEffects];\n } else {\n microsteps.push([nextSnapshot, []]);\n }\n }\n\n function completeMacrostep() {\n const effects = microsteps.flatMap(([, actions]) => actions);\n const starts = deriveDeferredStarts(effects);\n const shouldTerminate =\n (snapshot.status === 'active' || initialMicrosteps.length > 0) &&\n (nextSnapshot.status === 'done' || nextSnapshot.status === 'error');\n\n if (starts.length || shouldTerminate) {\n const terminalEffects = shouldTerminate\n ? [...starts, createTerminationEffect(actorScope, nextSnapshot)]\n : starts;\n if (microsteps.length) {\n const [lastSnapshot, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n lastSnapshot,\n [...lastEffects, ...terminalEffects]\n ];\n } else {\n microsteps.push([nextSnapshot, terminalEffects]);\n }\n }\n\n return { snapshot: nextSnapshot, microsteps };\n }\n\n function addMicrostep(\n step: Microstep,\n transitions: AnyTransitionDefinition[]\n ) {\n // collect microsteps; surfaced on the enclosing '@xstate.transition' event\n // via its `microsteps[]` facet (there is no standalone microstep event)\n if (\n !isInertActorScope(actorScope) &&\n (event.type === XSTATE_INIT ||\n (actorScope.system._hasInspectionObservers?.() ?? true))\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(...transitions);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n microsteps.push(step);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n const [stoppedChildrenSnapshot, stopEffects] = stopChildren(\n nextSnapshot,\n event,\n actorScope\n );\n const [withoutTimers, cancelEffects] = cancelTimers(\n stoppedChildrenSnapshot,\n event,\n actorScope\n );\n nextSnapshot = cloneMachineSnapshot(withoutTimers, {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);\n return completeMacrostep();\n }\n\n let nextEvent = normalizeLegacyInternalEvent(event, snapshot.machine);\n\n if (event.type === XSTATE_TIMER) {\n const timer = nextSnapshot.timers[(event as any).id];\n if (!timer) {\n return completeMacrostep();\n }\n\n const timers = { ...nextSnapshot.timers };\n delete timers[timer.id];\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { timers });\n if (timer.type === '@xstate.raise') {\n internalQueue.push(timer.event);\n addMicrostep([nextSnapshot, []], []);\n } else {\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n addMicrostep(\n [nextSnapshot, [createSendToEffect(actorScope, target, timer.event)]],\n []\n );\n }\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT && nextEvent.type !== XSTATE_TIMER) {\n const currentEvent = nextEvent;\n const isErr = isErrorEvent(currentEvent);\n const selectionResults: TransitionSelectionResults = new Map();\n\n const transitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n currentEvent,\n actorScope,\n selectionResults\n );\n\n if (isErr && !transitions.length) {\n if (\n currentEvent.type === 'xstate.error.actor' &&\n !matchesActorSession(\n currentEvent,\n nextSnapshot,\n (currentEvent as AnyEventObject).actorId\n )\n ) {\n return completeMacrostep();\n }\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], []);\n removeTerminatedChild(currentEvent);\n return completeMacrostep();\n }\n const step = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n addMicrostep(step, transitions);\n removeTerminatedChild(currentEvent);\n }\n\n if (\n !internalQueue.length &&\n snapshot.machine._hasEventlessTransitions === false\n ) {\n return completeMacrostep();\n }\n\n let shouldSelectEventlessTransitions = true;\n const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;\n let iterationCount = 0;\n\n let microstepCount = 0;\n while (nextSnapshot.status === 'active') {\n microstepCount++;\n if (microstepCount > 1000) {\n throw new Error('Microstep count exceeded 1000');\n }\n iterationCount++;\n if (iterationCount > maxIterations) {\n throw new Error(\n isDevelopment\n ? `Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`\n : `Infinite loop detected (>${maxIterations} microsteps)`\n );\n }\n\n let selectionResults: TransitionSelectionResults | undefined;\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope)\n : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n selectionResults = new Map();\n enabledTransitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n nextEvent,\n actorScope,\n selectionResults\n );\n }\n\n const step = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, enabledTransitions);\n removeTerminatedChild(nextEvent);\n }\n\n return completeMacrostep();\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, allStateNodes);\n}\n\nexport function hasEffect(\n transition: AnyTransitionDefinition,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope\n): boolean {\n if (transition.to) {\n return evaluateTransitionFunction(\n transition.to,\n context,\n event,\n snapshot,\n actorScope,\n snapshot.machine.sources,\n transition.source.id\n ).enabled;\n }\n\n return false;\n}\n\nconst triggerTransitionEffect = () => {\n throw transitionEffectSignal;\n};\nlet transitionEffectEnqueue: ReturnType<typeof createEnqueueObject> | undefined;\nfunction getTransitionEffectEnqueue() {\n return (transitionEffectEnqueue ??= createEnqueueObject(\n {\n emit: triggerTransitionEffect,\n cancel: triggerTransitionEffect,\n log: triggerTransitionEffect,\n raise: triggerTransitionEffect,\n spawn: triggerTransitionEffect,\n sendTo: triggerTransitionEffect,\n stop: triggerTransitionEffect,\n listen: triggerTransitionEffect,\n subscribeTo: triggerTransitionEffect\n },\n triggerTransitionEffect\n ));\n}\n\nfunction evaluateTransitionFunction(\n transitionTo: NonNullable<AnyTransitionDefinition['to']>,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n sources: AnyMachineSnapshot['machine']['sources'],\n sourceId: string\n): TransitionSelectionResult {\n let res;\n const parent = getActorScopeParent(actorScope);\n if (parent) {\n transitionEffectTargets.push(parent);\n }\n\n try {\n res = transitionTo(\n withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: sources.actions,\n actors: sources.actors,\n guards: sources.guards,\n delays: sources.delays,\n input: getStateInput(snapshot, sourceId)\n },\n actorScope\n ),\n getTransitionEffectEnqueue()\n );\n } catch (err) {\n if (err === transitionEffectSignal) {\n return { enabled: true, result: undefined, reusable: false };\n }\n throw err;\n } finally {\n if (parent) {\n transitionEffectTargets.pop();\n }\n }\n\n return { enabled: res !== undefined, result: res, reusable: true };\n}\n\nfunction stopChildren(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let children: AnyActor[];\n if (\n !snapshot.children ||\n (children = Object.values(snapshot.children).filter(Boolean) as AnyActor[])\n .length === 0\n ) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const child of children) {\n enqueue.stop(child);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction cancelTimers(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n const timerIds = Object.keys(snapshot.timers);\n if (!timerIds.length) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const id of timerIds) {\n enqueue.cancel(id);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction selectEventlessTransitions(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = snapshot.nodes.filter(isAtomicStateNode);\n\n for (const atomicStateNode of atomicStates) {\n loop: for (\n let stateNode: AnyStateNode | undefined = atomicStateNode;\n stateNode;\n stateNode = stateNode.parent\n ) {\n if (!stateNode.always) {\n continue;\n }\n for (const transition of stateNode.always) {\n if (\n evaluateCandidate(transition, event, snapshot, stateNode, actorScope)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(snapshot.nodes),\n snapshot,\n createTransitionResultResolver(snapshot, event, actorScope, false)\n );\n}\n\nexport function evaluateCandidate(\n candidate: AnyTransitionDefinition,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n stateNode: AnyStateNode,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): boolean {\n if (candidate.matches && !matchesEvent(event, candidate.matches)) {\n return false;\n }\n\n if (candidate._eventMatcher && !candidate._eventMatcher(event, snapshot)) {\n return false;\n }\n\n if (candidate.guard) {\n const guardArgs = withActorSelfAndParent(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n children: snapshot.children,\n actions: stateNode.machine.sources.actions,\n actors: stateNode.machine.sources.actors,\n guards: stateNode.machine.sources.guards,\n delays: stateNode.machine.sources.delays,\n _snapshot: snapshot\n },\n actorScope\n );\n if (!(candidate.guard as (args: typeof guardArgs) => boolean)(guardArgs)) {\n return false;\n }\n }\n\n if (candidate.to) {\n const evaluation = evaluateTransitionFunction(\n candidate.to,\n snapshot.context,\n event,\n snapshot,\n actorScope,\n stateNode.machine.sources,\n candidate.source.id\n );\n selectionResults?.set(candidate, evaluation);\n return evaluation.enabled;\n }\n\n return true;\n}\n","import isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY, WILDCARD } from './constants.ts';\nimport { isStateId } from './stateUtils.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n AnyTransitionConfigFunction,\n ErrorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n OutputArg,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\nexport function checkStateIn(\n snapshot: AnyMachineSnapshot,\n stateValue: StateValue\n) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot.nodes.some((sn) => sn === target);\n }\n\n return snapshot.matches(stateValue);\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n const result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nfunction toStateValue(stateValue: StateLike<any> | StateValue): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nfunction toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActor,\n input?: Record<string, unknown>\n): unknown {\n if (typeof mapper === 'function') {\n const outputMapper = mapper as Mapper<\n TContext,\n TExpressionEvent,\n unknown,\n EventObject\n >;\n const args = {\n context,\n event,\n output: getEventOutput(event),\n self,\n input\n } as unknown as Parameters<typeof outputMapper>[0];\n\n return outputMapper(args);\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function getEventOutput<TEvent extends EventObject>(\n event: TEvent\n): OutputArg<TEvent>['output'] {\n if (isDoneEvent(event)) {\n const doneEvent = event as unknown as EventObject & { output: unknown };\n return doneEvent.output as OutputArg<TEvent>['output'];\n }\n\n return undefined as OutputArg<TEvent>['output'];\n}\n\nfunction isDoneEvent(event: EventObject): boolean {\n return (\n event.type === 'xstate.done.actor' || event.type === 'xstate.done.state'\n );\n}\n\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorEvent(event: AnyEventObject): event is ErrorEvent {\n return event.type.startsWith('xstate.error.');\n}\n\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<\n AnyTransitionConfig | TransitionConfigTarget | AnyTransitionConfigFunction\n >\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n if (typeof transitionLike === 'function') {\n return { to: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.sources.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n const configSrc = (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any // TMeta\n >)\n ).src;\n // A referenced actor may itself be registered by name.\n return typeof configSrc === 'string'\n ? machine.sources.actors[configSrc]\n : configSrc;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot.nodes.flatMap((sn) => sn.ownEvents)])];\n}\n\n/** @internal Events synthesized from active transition descriptors. */\nexport function getAllOwnEvents(snapshot: AnyMachineSnapshot) {\n const events = snapshot.nodes.flatMap((stateNode) =>\n [...stateNode.transitions.values()].flatMap((transitions) =>\n transitions.map((transition) => {\n const event: AnyEventObject = {\n type: transition.eventType,\n ...transition.matches\n };\n if (\n 'actorId' in event &&\n (event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.timeout.actor')\n ) {\n event.sessionId = snapshot.children[event.actorId]?.sessionId;\n }\n return event;\n })\n )\n );\n return events.filter(\n (event, index) =>\n events.findIndex((candidate) => {\n const keys = Object.keys(event);\n return (\n keys.length === Object.keys(candidate).length &&\n keys.every((key) => Object.is(event[key], candidate[key]))\n );\n }) === index\n );\n}\n\nexport function matchesEvent(\n event: EventObject,\n pattern: Record<string, unknown>\n): boolean {\n return Object.entries(pattern).every(([key, value]) =>\n Object.is((event as AnyEventObject)[key], value)\n );\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nexport function matchesEventDescriptor(\n eventType: string,\n descriptor: string\n): boolean {\n if (descriptor === eventType) {\n return true;\n }\n\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n}\n","import { ACTOR_REF_TYPE } from './createActor.ts';\nimport type { AnyActorSystem } from './system.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n Snapshot,\n Subscription\n} from './types.ts';\n\nconst emptySubscription: Subscription = { unsubscribe() {} };\n\nconst restoreHint =\n 'or restore this snapshot with embedded children on the runtime that owns them.';\n\n/** @internal */\nexport function isRemoteActorRef(actorRef: AnyActor): boolean {\n return (actorRef as { _remote?: boolean })._remote === true;\n}\n\n/**\n * The lifecycle-only snapshot a remote handle exposes. `active` is accurate\n * by construction: a completion removes the child from its parent's\n * `children`, so a handle only exists while the child is presumed active,\n * and the terminal result arrives as a completion event instead of a\n * snapshot. Full snapshots are a co-location capability.\n */\nconst remoteSnapshot: Snapshot<undefined> = Object.freeze({\n status: 'active' as const,\n output: undefined,\n error: undefined\n});\n\n/**\n * Creates a location-transparent handle to an actor whose state lives with\n * another runtime. The handle is constructed from identity alone — no lookup\n * — and every send routes through the system's runtime; its state is not\n * synchronously readable.\n *\n * The surface is deliberately minimal: it covers every member the runtime\n * reaches for a restored child (send/_send, lifecycle via start/_stop and\n * system.stopActor, persistence, subscribe/on as inert subscriptions).\n * Members that only make sense for a co-located actor (public stop(),\n * select(), trigger) throw a descriptive error rather than being absent, so\n * calling one reports what went wrong instead of a bare TypeError. Observable\n * interop and _processingStatus are omitted entirely.\n *\n * @internal\n */\nexport function createRemoteActorRef(\n system: AnyActorSystem,\n options: {\n id: string;\n address: string;\n src: string;\n parent: AnyActor | undefined;\n registryKey?: string;\n syncSnapshot?: boolean;\n incarnation?: string;\n }\n): AnyActor {\n const handle = {\n _remote: true as const,\n // Self-reference so context persistence recognizes the handle as an\n // actor reference instead of recursing into it.\n ref: undefined as unknown as AnyActor,\n id: options.id,\n address: options.address,\n src: options.src,\n registryKey: options.registryKey,\n // The host-supplied incarnation token, when present: the owner's\n // sessionId for this child, letting this side drop stale completions and\n // journaled sends name the intended incarnation. Without one the handle\n // does not know the child's incarnation and the owning runtime is the\n // authority on staleness.\n sessionId: options.incarnation as string,\n system,\n _parent: options.parent,\n // Round-trips through persistence verbatim (undefined stays undefined,\n // so re-persisting is byte-stable); a remote handle cannot act on it\n // locally.\n _syncSnapshot: options.syncSnapshot,\n send(event: AnyEventObject) {\n void system.sendEvent(undefined, ref, event);\n },\n _send(event: AnyEventObject) {\n throw new Error(\n `Remote actor '${options.address}' has no local mailbox to receive \"${event.type}\". Its state lives with another runtime; install a runtime that can reach it (via \\`createDurable\\`'s adapter runtime operations, or \\`system.runtime\\`) before sending, ${restoreHint}`\n );\n },\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n getPersistedSnapshot(): never {\n throw new Error(\n `Cannot persist remote actor '${options.address}' from here: its state lives with the runtime that owns it. Persist it there, ${restoreHint}`\n );\n },\n start() {},\n _stop() {},\n stop() {\n throw new Error(\n `Cannot stop remote actor '${options.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\\`system.stopActor(ref)\\`), ${restoreHint}`\n );\n },\n select() {\n throw new Error(\n `Cannot select from remote actor '${options.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${restoreHint}`\n );\n },\n get trigger(): never {\n throw new Error(\n `Remote actor '${options.address}' has no \\`trigger\\` shorthand: it requires a co-located actor. Use \\`send(...)\\`, which routes through the system runtime.`\n );\n },\n // Observation is a co-location capability: a remote handle never emits,\n // so subscriptions are inert rather than errors — generic observers may\n // attach to any ref.\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n _isRunning() {\n return false;\n },\n // The same shape Actor.toJSON produces, so serialized snapshots carry\n // one actor-reference marker whether a child is co-located or remote.\n toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: options.id,\n address: options.address,\n src: options.src\n };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE } from './createActor.ts';\nimport { getStateValue } from './stateUtils.ts';\nimport type {\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyActor,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n StateValueMap,\n AnyActorRef,\n Snapshot,\n MetaObject,\n StateSchema,\n StateId,\n StateIdInputs,\n StateContextFromStateValue,\n SnapshotStatus,\n PersistedHistoryValue,\n AnyStateNode,\n LogicalTimer\n} from './types.ts';\nimport { matchesState } from './utils.ts';\nimport {\n copySnapshotActorRef,\n getSnapshotActorRef,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\nimport { isRemoteActorRef } from './remoteActorRef.ts';\n\nconst emptySnapshotRecord = Object.freeze({});\n\nfunction compactSnapshotRecord<T extends object>(value: T | undefined): T {\n if (value === emptySnapshotRecord) {\n return value;\n }\n return value && Object.keys(value).length\n ? value\n : (emptySnapshotRecord as T);\n}\n\nexport function isMachineSnapshot(value: unknown): value is AnyMachineSnapshot {\n return (\n !!value &&\n typeof value === 'object' &&\n 'machine' in value &&\n 'value' in value\n );\n}\n\ntype Values<T> = T[keyof T];\n\ntype MatchingObjectStateValue<\n TStateValue extends Record<string, unknown>,\n TTestStateValue extends Record<string, unknown>\n> =\n false extends Values<{\n [K in keyof TTestStateValue]: K extends keyof TStateValue\n ? NonNullable<TStateValue[K]> extends StateValue\n ? NonNullable<TTestStateValue[K]> extends StateValue\n ? [\n MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n ] extends [never]\n ? false\n : true\n : false\n : false\n : false;\n }>\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype MatchingStateValue<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = StateValue extends TTestStateValue\n ? TStateValue\n : string extends TTestStateValue\n ? TStateValue\n : TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends Record<string, unknown>\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends Record<string, unknown>\n ? TStateValue extends Record<string, unknown>\n ? MatchingObjectStateValue<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ninterface MachineSnapshotBase<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n _TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: AnyStateMachine;\n /** The tags of the active state nodes that represent the current state value. */\n tags: Set<string>;\n /**\n * The current state value.\n *\n * This represents the active state nodes in the state machine.\n *\n * - For atomic state nodes, it is a string.\n * - For compound parent state nodes, it is an object where:\n *\n * - The key is the parent state node's key\n * - The value is the current state value of the active child state node(s)\n *\n * @example\n *\n * ```ts\n * // single-level state node\n * snapshot.value; // => 'yellow'\n *\n * // nested state nodes\n * snapshot.value; // => { red: 'wait' }\n * ```\n */\n value: TStateValue;\n /** The current status of this snapshot. */\n status: SnapshotStatus;\n error: unknown;\n context: TContext;\n\n historyValue: Readonly<HistoryValue>;\n /** The enabled state nodes representative of the state value. */\n nodes: Array<AnyStateNode>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n /** Pending logical timers owned by this machine snapshot. */\n timers: Readonly<Record<string, LogicalTimer>>;\n /** @internal */\n _stateInputs: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId: number;\n /** @internal */\n _nextActorIds?: Record<string, number>;\n /**\n * Whether the current state value is a subset of the given partial state\n * value.\n *\n * @param partialStateValue\n */\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches(partialStateValue: StateValue): boolean;\n\n /**\n * Whether the current state nodes has a state node with the specified `tag`.\n *\n * @param tag\n */\n hasTag: (tag: TTag) => boolean;\n\n /**\n * Determines whether sending the `event` will cause a non-forbidden\n * transition to be selected, even if the transitions have no actions nor\n * change the state value.\n *\n * @param event The event to test\n * @returns Whether the event will cause a transition\n */\n can: (event: TEvent) => boolean;\n\n getMeta: () => Record<\n StateId<TStateSchema> & string,\n TMeta | undefined // States might not have meta defined\n >;\n\n /**\n * Returns the inputs for the current active state nodes, keyed by state node\n * id.\n */\n getInputs: () => StateIdInputs<TStateSchema>;\n\n toJSON: () => unknown;\n}\n\ninterface ActiveMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'active';\n output: undefined;\n error: undefined;\n}\n\ninterface DoneMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'done';\n output: TOutput;\n error: undefined;\n}\n\ninterface ErrorMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'error';\n output: undefined;\n error: unknown;\n}\n\ninterface StoppedMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\nexport type MachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\n) {\n return matchesState(testValue, this.value);\n};\n\nconst machineSnapshotHasTag = function hasTag(\n this: AnyMachineSnapshot,\n tag: string\n) {\n return this.tags.has(tag);\n};\n\nconst machineSnapshotCan = function can(\n this: AnyMachineSnapshot,\n event: EventObject\n) {\n if (isDevelopment && !this.machine) {\n console.warn(\n `state.can(...) used outside of a machine-created State object; this will always return false.`\n );\n }\n\n // The dry-run logic lives on the machine so that non-machine bundles\n // (e.g. `createFSM`) don't pay for the transition-resolution machinery.\n return this.machine?._canTransition(this, event) ?? false;\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n getMeta,\n getInputs,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return { ...jsonValues, tags: Array.from(tags) };\n};\n\nconst machineSnapshotGetMeta = function getMeta(this: AnyMachineSnapshot) {\n const meta: Record<string, any> = {};\n for (const stateNode of this.nodes) {\n if (stateNode.meta !== undefined) {\n meta[stateNode.id] = stateNode.meta;\n }\n }\n return meta;\n};\n\nconst machineSnapshotGetInputs = function getInputs<\n TStateSchema extends StateSchema\n>(\n this: AnyMachineSnapshot & {\n _stateInputs: StateIdInputs<TStateSchema>;\n }\n): StateIdInputs<TStateSchema> {\n return this._stateInputs;\n};\n\nfunction collectTags(stateNodes: Array<AnyStateNode>): Set<string> {\n const tags = new Set<string>();\n for (const stateNode of stateNodes) {\n for (const tag of stateNode.tags) {\n tags.add(tag);\n }\n }\n return tags;\n}\n\nexport function createMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n>(\n config: StateConfig<TContext, TEvent>,\n machine: AnyStateMachine,\n actorRef?: AnyActor\n): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n const snapshot = {\n status: config.status as never,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n nodes: config._nodes,\n value: (config.value ??\n getStateValue(machine.root, config._nodes)) as never,\n tags: collectTags(config._nodes),\n children: compactSnapshotRecord(config.children) as TChildren,\n timers: compactSnapshotRecord(config.timers),\n historyValue: compactSnapshotRecord(config.historyValue),\n _stateInputs: compactSnapshotRecord(config._stateInputs),\n _nextTimerId: config._nextTimerId ?? 0,\n _nextActorIds: config._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n };\n if (actorRef) {\n setSnapshotActorRef(snapshot, actorRef);\n }\n return snapshot;\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n const configWithSnapshot = {\n ...snapshot,\n ...config\n } as StateConfig<any, any>;\n\n if ((config._nodes ?? snapshot.nodes) === snapshot.nodes) {\n const clonedSnapshot = {\n status: configWithSnapshot.status as never,\n output: configWithSnapshot.output,\n error: configWithSnapshot.error,\n machine: snapshot.machine,\n context: configWithSnapshot.context,\n nodes: snapshot.nodes,\n value: snapshot.value,\n tags: snapshot.tags,\n children: compactSnapshotRecord(configWithSnapshot.children),\n timers: compactSnapshotRecord(configWithSnapshot.timers),\n historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),\n _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),\n _nextTimerId: configWithSnapshot._nextTimerId ?? 0,\n _nextActorIds: configWithSnapshot._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n } as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n }\n\n const clonedSnapshot = createMachineSnapshot(\n {\n ...configWithSnapshot,\n value: undefined\n },\n snapshot.machine\n ) as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n}\n\nfunction serializeHistoryValue(\n historyValue: HistoryValue\n): PersistedHistoryValue {\n const result: PersistedHistoryValue = {};\n\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map((item) => ({ id: item.id }));\n }\n }\n\n return result;\n}\n\nexport function getPersistedSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject\n>(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any // state schema\n >,\n options?: unknown\n): Snapshot<unknown> {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n children,\n timers,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n getInputs,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n const childrenJson: Record<string, unknown> = {};\n const timersJson: Record<string, unknown> = {};\n\n const embedChildren =\n (options as { embedChildren?: boolean } | undefined)?.embedChildren !==\n false;\n for (const id in children) {\n const child = children[id] as any;\n if (\n typeof child.src !== 'string' &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error('An inline child actor cannot be persisted.');\n }\n // Children are referenced by their logical address. Embedding the child\n // state is the co-locating runtime's whole-tree checkpoint capability;\n // remote handles never embed — their state lives with another runtime.\n const embed = embedChildren && !isRemoteActorRef(child);\n if (!embed && typeof child.src !== 'string') {\n // Fail where it is actionable: a by-address reference without a\n // registered source key could be persisted but never restored.\n throw new Error(\n `Unable to persist child '${id}' by address: it requires a registered source key.`\n );\n }\n childrenJson[id as keyof typeof childrenJson] = {\n address: child.address,\n // The explicit marker disambiguates a by-address reference from a child\n // whose own persisted snapshot happens to be undefined.\n ...(embed\n ? { snapshot: child.getPersistedSnapshot(options) }\n : {\n remote: true,\n // A remote handle's sessionId IS the host-supplied incarnation\n // token, round-tripped verbatim. A local child persisted by\n // address never stamps its own sessionId: that value is this\n // incarnation's, not a durable identity, and it would make\n // persisted snapshots nondeterministic across replays.\n incarnation: isRemoteActorRef(child) ? child.sessionId : undefined\n }),\n src: child.src,\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const snapshotActor = getSnapshotActorRef(snapshot)?.actor;\n // Only the wall clock is stamped into persisted timers: a custom clock's\n // readings (a simulated clock, a monotonic counter) are meaningless in any\n // other process, and restoring them under the wall clock would fire every\n // pending delay instantly. Pure-transition snapshots have no local\n // schedule and persist no timestamp.\n const scheduledTimers = snapshotActor?.system?._clock?.now\n ? undefined\n : snapshotActor?.system?._snapshot?._scheduledTimers;\n for (const id in timers) {\n const timer = timers[id];\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n event = { ...event };\n delete (event as EventObject & { sessionId?: string }).sessionId;\n }\n let target: string | { type: 'parent' };\n if (timer.target === 'self') {\n target = 'self';\n } else {\n const childId = Object.entries(children).find(\n ([, child]) => child === timer.target\n )?.[0];\n if (childId) {\n target = childId;\n } else if (\n timer.target === getSnapshotActorRef(snapshot)?.actor._parent\n ) {\n target = { type: 'parent' };\n } else {\n throw new Error(\n `Unable to persist timer '${id}': target actor '${timer.target.id}' is no longer addressable from this snapshot.`\n );\n }\n }\n // A live runtime knows when the timer is due; persist the wall-clock\n // start (dueAt - declared delay) so restore can honor the absolute\n // deadline. Derived from dueAt, not the scheduling moment, so repeated\n // persist/restore cycles keep the same deadline. Without a live schedule\n // (a restored-but-never-started actor, a pure-transition snapshot) the\n // timer's carried-in start — which only a wall-clock actor ever stamped —\n // passes through, so re-persisting cannot push the deadline back.\n const scheduled = scheduledTimers?.[`${snapshotActor!.sessionId}.${id}`];\n const startedAt = scheduled\n ? scheduled.dueAt - timer.delay\n : timer.startedAt;\n timersJson[id] = {\n id: timer.id,\n delay: timer.delay,\n type: timer.type,\n event,\n target,\n ...(startedAt !== undefined && { startedAt })\n };\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n context: persistContext(context) as any,\n children: childrenJson,\n timers: timersJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n\n if (_stateInputs && Object.keys(_stateInputs).length > 0) {\n persisted.stateInputs = _stateInputs;\n }\n\n if (machine.version !== undefined) {\n persisted.machine = {\n id: machine.id,\n version: machine.version\n };\n persisted.version = machine.version;\n }\n\n return persisted as Snapshot<unknown>;\n}\n\nfunction persistContext(contextPart: Record<string, unknown>) {\n let copy: typeof contextPart | undefined;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = {\n xstate$type: ACTOR_REF_TYPE,\n id: (value as any as AnyActor).id\n };\n } else {\n const result = persistContext(value as typeof contextPart);\n if (result !== value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport type { ActorTermination, AnyActor, AnyEventObject } from './types.ts';\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n return (actor.getSnapshot() as { effects?: StepEffects }).effects?.[key];\n}\n\nfunction waitForStep<TStepOutput>(\n actor: AnyActor,\n key: string\n): Promise<TStepOutput> {\n return new Promise((resolve, reject) => {\n const subscription = actor.subscribe((snapshot) => {\n const effect = (snapshot as { effects?: StepEffects }).effects?.[key];\n if (effect?.status === 'done') {\n subscription.unsubscribe();\n resolve(effect.output as TStepOutput);\n } else if (effect?.status === 'error') {\n subscription.unsubscribe();\n reject(effect.error as Error);\n }\n });\n });\n}\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n if (effect?.status === 'active') {\n return waitForStep(actor, key);\n }\n\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n try {\n const output = await exec();\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n return output;\n } catch (error) {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n throw error;\n }\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n assertEventCanBeSent(source, target, event);\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n _lastSourceRef?: AnyActor;\n _send(event: AnyEventObject): void;\n };\n\n runtimeTarget._lastSourceRef = source;\n runtimeTarget._send(event);\n}\n\n/**\n * Ensures internal events cannot cross an actor boundary from an external\n * sender. Host runtimes must call this before taking ownership of delivery.\n */\nexport function assertEventCanBeSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n throw new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","import isDevelopment from '#is-development';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription,\n AnyActorLogic,\n ActorOptions\n} from './types.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { toObserver } from './utils.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n assertEventCanBeSent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n id: string;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, id: string, delay: number): void;\n cancel(source: AnyActor, id: string): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet systemIdPrefix: string | undefined;\nlet nextSystemId = 0;\n\n/** @internal */\nexport const transitionEffectSignal = new Error('Transition effect');\n/** @internal */\nexport const transitionEffectTargets: AnyActor[] = [];\n\nfunction createSystemIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createSystemId(): string {\n systemIdPrefix ??= createSystemIdPrefix();\n return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n systemId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Anonymous machines get the placeholder id '(machine)'; only named logic\n // earns a named id prefix.\n return typeof logicId === 'string' &&\n logicId.length &&\n logicId !== '(machine)'\n ? logicId\n : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.systemId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Publishes an emitted event. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /** Schedules a logical timer. */\n scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, id: string): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry: the default logs in development and emits an\n * inspection event.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: string\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(actor: AnyActor, id: string): ScheduledTimerId {\n return `${actor.sessionId}.${id}` as ScheduledTimerId;\n}\n\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n systemId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n systemId: createSystemId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n ) {\n const restoredSnapshot =\n typeof options.snapshot === 'object' && options.snapshot !== null\n ? (options.snapshot as {\n scheduler?: Record<ScheduledTimerId, ScheduledTimer>;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, id: string, delay: number): void {\n const existingId = createScheduledTimerId(source, id);\n if (this._timerMap?.[existingId] !== undefined) {\n this.cancel(source, id);\n }\n\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n id,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n const scheduledTimerId = createScheduledTimerId(source, id);\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, id });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, id: string): void {\n const scheduledTimerId = createScheduledTimerId(source, id);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.id);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${registryKey as string}' already exists.`\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n assertEventCanBeSent(source, target, event);\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: string\n ): void | PromiseLike<void> {\n this._sendInspectionEvent({\n type: '@xstate.deadletter',\n actorRef: target,\n sourceRef: source,\n event,\n reason\n });\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason);\n }\n if (isDevelopment) {\n console.warn(\n `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n return override(source, id, delay);\n }\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, id);\n }\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, id } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n id,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotFor,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableActionObject,\n Readable,\n ActorLogicTransitionResult\n} from './types.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\n/**\n * Marks a serialized object as an actor reference (`xstate$type` in JSON\n * output and persisted context).\n */\nexport const ACTOR_REF_TYPE = 'actorRef';\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableActionObject[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (event: EventFromLogic<TLogic>) => void;\n private mailbox?: Mailbox<EventFromLogic<TLogic>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableActionObject[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n snapshot: resolvedOptions.snapshot ?? resolvedOptions.state,\n createActorRef\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const persistedState = options?.snapshot ?? options?.state;\n this._restored = persistedState !== undefined;\n try {\n if (persistedState) {\n this._setSnapshot(\n this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n );\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._setSnapshot({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>);\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n this.system.emitEvent(this, event);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableActionObject) => void {\n const actionExecutor = (action: ExecutableActionObject) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : `Cannot stop non-child actor ${child.id}`\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableActionObject): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n void action.exec();\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n type RestoredTimer = { id: string; delay: number; startedAt?: number };\n const timers =\n (\n this._snapshot as unknown as {\n timers?: Record<string, RestoredTimer>;\n }\n ).timers ?? {};\n // startedAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of Object.values(timers)) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.startedAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.startedAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, timer.id, delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n private _error(err: unknown): void {\n this._stopProcedure();\n if (!this.observers?.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n } else {\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n safeCall(errorListener, err);\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(\n this._lastSourceRef,\n this as AnyActor,\n event,\n 'stopped'\n );\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: its `id`, `address`,\n * and registered source key (when the actor was created from one).\n */\n public toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: this.id,\n address: this.address,\n src: typeof this.src === 'string' ? this.src : undefined\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n public getPersistedSnapshot(\n options?: unknown\n ): Snapshot<unknown> & PersistedSnapshotFor<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START,\n XSTATE_STOP\n} from '../constants.ts';\nimport { createInitEvent } from '../eventUtils.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { ActorSystemRuntime, AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n finalizeTransitionResult,\n createCustomEffect,\n createEmitEffect,\n createSendToEffect\n} from '../transitionActions.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n ActorScope,\n AnyActorRef,\n EventObject,\n ExecutableActionObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type LogicSnapshot<TContext, TOutput, TInput> = Snapshot<TOutput> & {\n context: TContext;\n input: TInput | undefined;\n effects?: Record<string, LogicEffectState>;\n};\n\nexport type LogicEffectState =\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown };\n\nexport interface LogicArgs<TContext, TEvent extends EventObject, TInput> {\n context: TContext;\n event: TEvent;\n input: TInput;\n system: AnyActorSystem;\n self: LogicActorRef<TContext, unknown, TEvent, TInput>;\n}\n\nexport type LogicEffect<\n _TEvent extends EventObject,\n _TEmitted extends EventObject\n> = ExecutableActionObject;\n\nexport interface LogicEnqueue<\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n emit: (emitted: TEmitted) => void;\n sendBack: (event: EventObject) => void;\n raise: (event: TEvent) => void;\n effect: {\n (\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n };\n}\n\nexport type LogicPatch<TContext, TOutput, TInput> = Partial<{\n context: TContext;\n input: TInput | undefined;\n status: LogicSnapshot<TContext, TOutput, TInput>['status'];\n output: TOutput;\n error: unknown;\n effects: Record<string, LogicEffectState>;\n}>;\n\nexport type LogicFunction<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> = (\n args: LogicArgs<TContext, TEvent, TInput>,\n enq: LogicEnqueue<TEvent, TEmitted>\n) => void | LogicPatch<TContext, TOutput, TInput>;\n\nexport interface LogicConfig<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n id?: string;\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n context: TContext | ((args: { input: TInput }) => TContext);\n run: LogicFunction<TContext, TOutput, TEvent, TInput, TEmitted>;\n}\n\ninterface LogicTransition<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> {\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): [\n LogicSnapshot<TContext, TOutput, TInput>,\n LogicEffect<TEvent, TEmitted>[]\n ];\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): LogicSnapshot<TContext, TOutput, TInput>;\n}\n\nexport type LogicActorLogic<\n TContext,\n TOutput,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = Omit<\n ActorLogic<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >,\n 'transition'\n> & {\n id?: string;\n transition: LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n};\n\nexport type LogicActorRef<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput\n> = ActorRefFromLogic<LogicActorLogic<TContext, TOutput, TEvent, TInput>>;\n\nconst effectStates = new WeakMap<\n AnyActorRef,\n Map<PropertyKey, { cleanup?: () => void }>\n>();\n\nfunction getEffectState(self: AnyActorRef) {\n let state = effectStates.get(self);\n if (!state) {\n state = new Map();\n effectStates.set(self, state);\n }\n return state;\n}\n\nfunction executeLogicEffect(\n self: AnyActorRef,\n key: string | undefined,\n effect: () => void | (() => void)\n): void {\n const state = getEffectState(self);\n if (key !== undefined && state.has(key)) {\n return;\n }\n const cleanup = effect();\n state.set(key ?? Symbol(), {\n cleanup: typeof cleanup === 'function' ? cleanup : undefined\n });\n}\n\nfunction cleanupLogicEffects(self: AnyActorRef): void {\n const state = effectStates.get(self);\n if (!state) {\n return;\n }\n for (const { cleanup } of state.values()) {\n cleanup?.();\n }\n effectStates.delete(self);\n}\n\nfunction resolveContext<TContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext),\n input: TInput\n) {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : context;\n}\n\nexport function createLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput,\n const TInputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & {\n schemas: { input: TInputSchema; output?: undefined };\n }\n): LogicActorLogic<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: undefined; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> {\n const calculateTransition = ((snapshot, event, actorScope) => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n\n if (event.type === XSTATE_STOP) {\n return [\n {\n ...snapshot,\n status: 'stopped',\n input: undefined\n },\n [\n createCustomEffect('xstate.logic.cleanup', () =>\n cleanupLogicEffects(actorScope.self)\n )\n ]\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_START) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: { status: 'active' }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'done',\n output: (event as any).output\n }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'error',\n error: (event as any).error\n }\n }\n },\n []\n ];\n }\n\n const effects: LogicEffect<TEvent, TEmitted>[] = [];\n const trackedEffects: Record<string, LogicEffectState> = {};\n const enqueueEffect = (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ) => {\n if (snapshot.effects?.[key]) {\n return;\n }\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, key, () => exec(runtime)),\n { key }\n )\n );\n trackedEffects[key] = { status: 'active' };\n };\n const enq: LogicEnqueue<TEvent, TEmitted> = {\n emit: (emitted) => {\n effects.push(createEmitEffect(actorScope, emitted));\n },\n sendBack: (sentEvent) => {\n const parent = actorScope.self._parent;\n if (parent) {\n effects.push(createSendToEffect(actorScope, parent, sentEvent));\n }\n },\n raise: (raisedEvent) => {\n effects.push(\n createSendToEffect(actorScope, actorScope.self, raisedEvent)\n );\n },\n effect: ((keyOrExec, maybeExec) => {\n if (typeof keyOrExec === 'string') {\n enqueueEffect(keyOrExec, maybeExec);\n return;\n }\n const exec = keyOrExec as (\n runtime?: Partial<ActorSystemRuntime>\n ) => void | (() => void);\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, undefined, () =>\n exec(runtime)\n )\n )\n );\n }) as LogicEnqueue<TEvent, TEmitted>['effect']\n };\n\n const patch = config.run(\n {\n context: snapshot.context,\n event,\n input: snapshot.input!,\n system: actorScope.system,\n self: actorScope.self as any,\n emit: actorScope.emit\n } as LogicArgs<TContext, TEvent, TInput>,\n enq\n );\n\n const nextSnapshot = {\n ...snapshot,\n ...(patch || {})\n } as LogicSnapshot<TContext, TOutput, TInput>;\n\n if ('context' in snapshot || patch?.context !== undefined) {\n (nextSnapshot as any).context = patch?.context ?? snapshot.context;\n }\n if (patch?.effects || Object.keys(trackedEffects).length) {\n (nextSnapshot as any).effects = {\n ...snapshot.effects,\n ...patch?.effects,\n ...trackedEffects\n };\n }\n\n return finalizeTransitionResult(actorScope, snapshot, [\n nextSnapshot,\n effects\n ]);\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const transition = ((snapshot, event, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'event',\n logic,\n event,\n eventOrigin: (actorScope.self as any)._lastSourceRef\n ? 'actor'\n : 'external'\n });\n }\n const result = calculateTransition(snapshot, event, actorScope);\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'result',\n logic,\n snapshot: result[0],\n effects: result[1]\n });\n }\n return result;\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const logic: LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> = {\n id: config.id,\n config,\n validator: config.validator,\n transition,\n start: (snapshot, actorScope, options) => {\n if (!options?.restored) {\n return;\n }\n const [nextSnapshot, effects] = transition(\n snapshot,\n createInitEvent(snapshot.input) as unknown as TEvent,\n actorScope\n );\n Object.assign(snapshot, nextSnapshot);\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n },\n initialTransition: (input, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'input',\n logic,\n input\n });\n }\n const context = resolveContext(config.context, input);\n const snapshot = {\n status: 'active' as const,\n output: undefined,\n error: undefined,\n input\n };\n\n if (context !== undefined) {\n (snapshot as any).context = context;\n }\n\n return transition(\n { ...snapshot } as LogicSnapshot<TContext, TOutput, TInput>,\n createInitEvent(input) as unknown as TEvent,\n actorScope\n );\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\ninterface CallbackInstanceState<TEvent extends EventObject> {\n receivers: Set<(e: TEvent) => void> | undefined;\n dispose: (() => void) | void;\n}\n\nconst instanceStates = /* #__PURE__ */ new WeakMap<\n AnyActorRef,\n CallbackInstanceState<any>\n>();\n\nexport type CallbackSnapshot<TInput> = Snapshot<undefined> & {\n input: TInput;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n CallbackSnapshot<TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createCallbackLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createCallbackLogic, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = createCallbackLogic<Event, Input>(\n * ({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef<Event, Input>\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * }\n * );\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link createCallbackLogic}\n */\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorRefFromLogic<CallbackActorLogic<TEvent, TInput>>;\n\ntype Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type CallbackLogicFunction<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n sendBack,\n receive,\n emit\n}: {\n /**\n * Data that was provided to the callback actor\n *\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /** The actor system to which the callback actor belongs */\n system: AnyActorSystem;\n /** The parent actor of the callback actor */\n self: CallbackActorRef<TEvent>;\n /** A function that can send events back to the parent actor */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument; the\n * listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n emit: (emitted: TEmitted) => void;\n}) => (() => void) | void;\n\nexport interface CallbackLogicConfig<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: CallbackLogicFunction<TEvent, TSentEvent, TInput, TEmitted>;\n}\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = createCallbackLogic(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createCallbackLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<\n TEvent,\n AnyEventObject,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): CallbackActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callback: CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callbackOrConfig:\n | CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n | CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted> {\n const callback =\n typeof callbackOrConfig === 'function'\n ? callbackOrConfig\n : callbackOrConfig.run;\n const schemas =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.schemas;\n const validator =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.validator;\n\n return createBaseLogic<undefined, undefined, TEvent, TInput, TEmitted>({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n const emit = (args as any).emit as (emitted: TEmitted) => void;\n const callbackState = instanceStates.get(self as any);\n callbackState?.receivers?.forEach((receiver) => receiver(event));\n\n enq.effect('callback', () => {\n const callbackState: CallbackInstanceState<TEvent> = {\n receivers: undefined,\n dispose: undefined\n };\n\n instanceStates.set(self as any, callbackState);\n\n callbackState.dispose = callback({\n input,\n system,\n self: self as any,\n sendBack: (event) => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n const parent = (self as any)._parent;\n if (parent) {\n system._relay(self as any, parent, event);\n }\n },\n receive: (listener) => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit: emit as (emitted: TEmitted) => void\n });\n\n return () => {\n instanceStates.delete(self as any);\n callbackState.receivers?.clear();\n callbackState.dispose?.();\n };\n });\n }\n }) as unknown as CallbackActorLogic<TEvent, TInput, TEmitted>;\n}\n","import { XSTATE_INIT, XSTATE_STOP } from '../constants';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot,\n Subscribable,\n Subscription\n} from '../types';\nimport { createLogic as createBaseLogic } from './logic.ts';\nimport { finalizeTransitionResult } from '../transitionActions.ts';\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\nexport type ObservableSnapshot<\n TContext,\n TInput extends NonReducibleUnknown\n> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createObservableLogic` or\n * `createEventObservableLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = createObservableLogic<Context, Input>(\n * ({ input, self }) => {\n * self;\n * // ^? ObservableActor<Event, Input>\n *\n * return interval(input.period ?? 1_000);\n * }\n * );\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActor<Event, Input>\n * ```\n *\n * @see {@link createObservableLogic}\n * @see {@link createEventObservableLogic}\n */\nexport type ObservableActorRef<TContext> = ActorRefFromLogic<\n ObservableActorLogic<TContext, any>\n>;\n\ntype ObservableActor<\n TContext,\n TInput extends NonReducibleUnknown = any,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<ObservableActorLogic<TContext, TInput, TEmitted>>;\n\nexport type ObservableLogicFunction<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TContext, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TContext>;\n\nexport interface ObservableLogicConfig<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: ObservableLogicFunction<TContext, TInput, TEmitted>;\n}\n\nexport type EventObservableLogicFunction<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TEvent, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TEvent>;\n\nexport interface EventObservableLogicConfig<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: EventObservableLogicFunction<TEvent, TInput, TEmitted>;\n}\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = createObservableLogic((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nexport function createObservableLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<TContext, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreator: ObservableLogicFunction<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreatorOrConfig:\n | ObservableLogicFunction<TContext, TInput, TEmitted>\n | ObservableLogicConfig<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted> {\n const observableCreator =\n typeof observableCreatorOrConfig === 'function'\n ? observableCreatorOrConfig\n : observableCreatorOrConfig.run;\n const schemas =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.schemas;\n const validator =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.validator;\n\n return createBaseLogic<\n TContext | undefined,\n undefined,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT: {\n return {\n context: event.data as TContext\n };\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n status: 'error',\n error: (event as any).data,\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'error', error: (event as any).data }\n }\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n status: 'done',\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'done' }\n }\n };\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const subscription = observableCreator({\n input,\n system,\n self: self as any,\n emit: ((event: TEmitted) =>\n void runtime.emitEvent!(actorSelf, event)) as (\n emitted: TEmitted\n ) => void\n }).subscribe({\n next: (value) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: (err) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n sendSelf({\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n\n return () => subscription.unsubscribe();\n });\n }\n }) as unknown as ObservableActorLogic<TContext, TInput, TEmitted>;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * createEventObservableLogic,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = createEventObservableLogic(\n * () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<TEvent, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservable: EventObservableLogicFunction<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservableOrConfig:\n | EventObservableLogicFunction<TEvent, TInput, TEmitted>\n | EventObservableLogicConfig<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted> {\n const lazyObservable =\n typeof lazyObservableOrConfig === 'function'\n ? lazyObservableOrConfig\n : lazyObservableOrConfig.run;\n const validator =\n typeof lazyObservableOrConfig === 'function'\n ? undefined\n : lazyObservableOrConfig.validator;\n\n // TODO: event types\n const logic: ObservableActorLogic<TEvent, TInput, TEmitted> = {\n config: lazyObservableOrConfig,\n validator,\n transition: (state, event, actorScope) => {\n if (state.status !== 'active') {\n return [state, []];\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_OBSERVABLE_COMPLETE:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return [\n {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n },\n []\n ];\n default:\n return [state, []];\n }\n },\n initialTransition: (input, _) => {\n if (validator) {\n assertValid(validator, { kind: 'input', logic, input });\n }\n const snapshot = {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>;\n return [snapshot, []];\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n start: (state, { self, system, emit }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self,\n emit: (event) => {\n void emit(event);\n }\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot: any) => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n","import { parseDelayToMilliseconds } from '../delay.ts';\nimport { runStep } from '../runtimeHelpers.ts';\nimport { XSTATE_INIT } from '../constants.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\nexport type AsyncSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nconst XSTATE_ASYNC_RESOLVE = 'xstate.async.resolve';\nconst XSTATE_ASYNC_REJECT = 'xstate.async.reject';\n\nexport type AsyncActorLogic<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n AsyncSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\nexport type AsyncActorRef<TOutput> = ActorRefFromLogic<\n AsyncActorLogic<TOutput, unknown>\n>;\n\ntype AsyncActor<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<AsyncActorLogic<TOutput, TInput, TEmitted>>;\n\nexport interface LogicArgs<TOutput, TInput> {\n /** Data that was provided to the async actor. */\n input: TInput;\n /** The actor system to which the async actor belongs. */\n system: AnyActorSystem;\n /** The async actor. */\n self: AsyncActor<TOutput, TInput>;\n /** Aborted when the async actor is stopped or times out. */\n signal: AbortSignal;\n}\n\nexport interface LogicEnqueue<TEmitted extends EventObject> {\n /** Emits an event that can be observed with `actor.on(...)`. */\n emit: (emitted: TEmitted) => void;\n /**\n * Executes async work as a durable effect keyed by `key`.\n *\n * @experimental The durability semantics (step journaling, replay, and\n * resumption across persistence) are not finalized and may change.\n */\n step: <TStepOutput>(\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>\n ) => Promise<TStepOutput>;\n}\n\nexport type LogicFunction<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = (\n args: LogicArgs<TOutput, TInput>,\n enq: LogicEnqueue<TEmitted>\n) => PromiseLike<TOutput>;\n\ntype AsyncLogicFunctionOutput<\n TLogicFunction extends (...args: any[]) => PromiseLike<any>\n> = Awaited<ReturnType<TLogicFunction>>;\n\nexport interface LogicConfig<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n /**\n * Stable identifier for this async logic. This identifies the logic, not a\n * particular actor instance.\n */\n id?: string;\n validator?: ActorLogicValidator;\n /** Schemas for inferring async logic types. */\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n /** Maximum time this async logic may run before it is aborted and errors. */\n timeout?: number | string;\n /** The async work to execute when the actor starts. */\n run: LogicFunction<TOutput, TInput, TEmitted>;\n}\n\nexport class TimeoutError extends Error {\n constructor(timeout: number | string) {\n super(`Async logic timed out after ${timeout}.`);\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Represents an actor created by `createAsyncLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createAsyncLogic, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = createAsyncLogic<Output, Input>({\n * run: async ({ input, self }, enq) => {\n * self;\n * // ^? AsyncActor<Output, Input>\n * enq.emit({ type: 'request.start' });\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * }\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? AsyncActor<Output, Input>\n * ```\n *\n * @see {@link createAsyncLogic}\n */\n\n/**\n * An actor logic creator which returns async logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from async actor logic can:\n *\n * - Output the resolved value of the async process\n * - Error with the rejected value of the async process\n * - Abort when stopped or timed out\n *\n * Sending events to async actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const asyncLogic = createAsyncLogic({\n * id: 'fetch-user',\n * timeout: '30s',\n * run: async ({ signal }, enq) => {\n * enq.emit({ type: 'request.start' });\n * const result = await fetch('https://example.com/...', {\n * signal\n * }).then((data) => data.json());\n *\n * return result;\n * }\n * });\n *\n * const asyncActor = createActor(asyncLogic);\n * asyncActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * asyncActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param asyncLogic A config object with a `run` function which returns a\n * Promise, and accepts an object with the following properties:\n *\n * - `input` - Data that was provided to the async actor\n * - `self` - The async actor ref\n * - `system` - The actor system to which the async actor belongs\n * - `signal` - An abort signal for cancellation\n *\n * `run` also receives an `enq` object with the following properties:\n *\n * - `emit` - Emits an event that can be observed with `actor.on(...)`\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject,\n TLogicFunction extends LogicFunction<\n any,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n > = LogicFunction<any, StandardSchemaV1.InferOutput<TInputSchema>, TEmitted>\n>(\n asyncLogic: Omit<\n LogicConfig<\n never,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n >,\n 'run' | 'schemas'\n > & {\n schemas: { input: TInputSchema; output?: never };\n run: TLogicFunction;\n }\n): AsyncActorLogic<\n AsyncLogicFunctionOutput<TLogicFunction>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TOutputSchema extends StandardSchemaV1,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: never; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: Omit<LogicConfig<TOutput, TInput, TEmitted>, 'schemas'> & {\n schemas?: undefined;\n }\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<TOutput, TInput, TEmitted>\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string } {\n const config = asyncLogic;\n\n return createBaseLogic<\n undefined,\n TOutput,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n id: config.id,\n validator: config.validator,\n schemas: config.schemas,\n context: undefined,\n run: ({ event, input, self, system }, enq) => {\n switch (event.type) {\n case XSTATE_ASYNC_RESOLVE: {\n const resolvedValue = (event as any).data ?? (event as any).output;\n return {\n status: 'done',\n output: resolvedValue,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'done', output: resolvedValue }\n }\n };\n }\n case XSTATE_ASYNC_REJECT: {\n const error = (event as any).data ?? (event as any).error;\n return {\n status: 'error',\n error,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'error', error }\n }\n };\n }\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const controller = new AbortController();\n const timeout = config.timeout;\n const timeoutMs = parseDelayToMilliseconds(timeout);\n const timeoutId =\n timeoutMs === undefined\n ? undefined\n : system._clock.setTimeout(() => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controller.abort();\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: new TimeoutError(timeout!)\n });\n }, timeoutMs);\n\n const clearTimeout = () => {\n if (timeoutId !== undefined) {\n system._clock.clearTimeout(timeoutId);\n }\n };\n\n const runBody = () =>\n Promise.resolve(\n config.run(\n {\n input,\n system,\n self: self as any,\n signal: controller.signal\n },\n {\n emit: (event) => void runtime.emitEvent!(actorSelf, event),\n // Steps route through the runtime: a durable host that\n // implements `runStep` owns the step journal; otherwise the\n // built-in behavior memoizes into this actor's own snapshot,\n // self-sending through the same runtime as the other effects.\n step: (key, exec) =>\n runtime.runStep\n ? (Promise.resolve(\n runtime.runStep(actorSelf, key, exec)\n ) as Promise<any>)\n : runStep(actorSelf, key, exec, sendSelf)\n }\n )\n );\n // The whole body is one durable unit: a host that implements\n // `runLogic` journals it by the actor's address — or re-runs the\n // registered logic from (src, input) on a remote executor, ignoring\n // the closure. The default runs it here, unjournaled.\n const resolvedPromise = runtime.runLogic\n ? Promise.resolve(runtime.runLogic(actorSelf, runBody))\n : runBody();\n\n resolvedPromise.then(\n (response) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_RESOLVE,\n data: response\n });\n },\n (errorData) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: errorData\n });\n }\n );\n\n return () => {\n controller.abort();\n clearTimeout();\n };\n });\n\n return {\n effects: {\n async: { status: 'active' }\n }\n };\n }\n }) as unknown as AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorFromLogic } from '../types.ts';\nimport { createLogic } from './logic.ts';\nexport {\n createCallbackLogic,\n type CallbackActorLogic,\n type CallbackActorRef,\n type CallbackLogicConfig,\n type CallbackSnapshot,\n type CallbackLogicFunction\n} from './callback.ts';\nexport {\n createObservableLogic,\n createEventObservableLogic,\n type EventObservableLogicConfig,\n type EventObservableLogicFunction,\n type ObservableActorLogic,\n type ObservableActorRef,\n type ObservableLogicConfig,\n type ObservableLogicFunction,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n createLogic,\n type LogicActorLogic,\n type LogicActorRef,\n type LogicArgs,\n type LogicConfig,\n type LogicEffect,\n type LogicEffectState,\n type LogicEnqueue,\n type LogicFunction,\n type LogicPatch,\n type LogicSnapshot\n} from './logic.ts';\nexport {\n createAsyncLogic,\n type AsyncActorLogic,\n type AsyncActorRef,\n type AsyncSnapshot,\n type LogicArgs as AsyncLogicArgs,\n type LogicConfig as AsyncLogicConfig,\n type LogicEnqueue as AsyncLogicEnqueue,\n type LogicFunction as AsyncLogicFunction,\n TimeoutError\n} from './promise.ts';\nexport {\n createListenerLogic,\n listenerLogic,\n type ListenerActorLogic,\n type ListenerActorRef,\n type ListenerSnapshot,\n type ListenerInput\n} from './listener.ts';\nexport {\n createSubscriptionLogic,\n subscriptionLogic,\n type SubscriptionActorLogic,\n type SubscriptionActorRef,\n type SubscriptionSnapshot,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './subscription.ts';\n\nconst emptyLogic = /* #__PURE__ */ createLogic<undefined, undefined>({\n context: undefined,\n run: () => undefined\n});\n\nexport function createEmptyActor(): ActorFromLogic<typeof emptyLogic> {\n return createActor(emptyLogic);\n}\n","const cache = new WeakMap<any, any>();\n\nexport function memo<T>(object: any, key: string, fn: () => T): T {\n let memoizedData = cache.get(object);\n\n if (!memoizedData) {\n memoizedData = { [key]: fn() };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n\n return memoizedData[key];\n}\n","import isDevelopment from '#is-development';\nimport { NULL_EVENT, STATE_DELIMITER } from './constants.ts';\nimport type { SetupStateSchemas } from './schema.types.ts';\nimport { createInvokeTimeoutEventId } from './eventUtils.ts';\nimport { memo } from './memo.ts';\nimport {\n evaluateCandidate,\n formatTransition,\n getCandidates,\n getEventDescriptorKey,\n getDelayedTransitions,\n matchesActorSession,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport type {\n DelayedTransitionDefinition,\n EventObject,\n InitialTransitionDefinition,\n MachineContext,\n Mapper,\n StateNodesConfig,\n TransitionDefinition,\n TransitionDefinitionMap,\n AnyStateMachine,\n AnyStateNodeConfig,\n NonReducibleUnknown,\n EventDescriptor,\n AnyActorScope,\n AnyStateNode,\n AnyEventObject,\n AnyAction,\n AnyTransitionConfig,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyInvokeDefinition\n} from './types.ts';\nimport {\n createInvokeId,\n mapValues,\n toArray,\n toTransitionConfigArray\n} from './utils.ts';\n\nconst EMPTY_OBJECT = {};\nconst CHOICE_CONFIG_KEYS = [\n 'invoke',\n 'after',\n 'on',\n 'entry',\n 'exit',\n 'always',\n 'states',\n 'initial',\n 'onDone',\n 'timeout',\n 'onTimeout',\n 'history',\n 'target',\n 'output'\n] as const;\n\ninterface StateNodeOptions<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n _key: string;\n _parent?: StateNode<TContext, TEvent>;\n _machine: AnyStateMachine;\n}\n\nexport class StateNode<\n TContext extends MachineContext = MachineContext,\n TEvent extends EventObject = EventObject\n> {\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n public key: string;\n /** The unique ID of the state node. */\n public id: string;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'choice'` - pure routing decision state node\n * - `'final'` - final state node\n */\n public type:\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | 'choice';\n /** The string path from the root machine node to this node. */\n public path: string[];\n /** The child state nodes. */\n public states: StateNodesConfig<any, any>;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n public history: false | 'shallow' | 'deep';\n /** The action(s) to be executed upon entering the state node. */\n public entry: AnyAction | undefined;\n /** The action(s) to be executed upon exiting the state node. */\n public exit: AnyAction | undefined;\n /** The parent state node. */\n public parent?: StateNode<any, any>;\n /** The root machine node. */\n public machine: AnyStateMachine;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n public meta?: any;\n /**\n * The output data sent with the `xstate.done.state` event if this is a final\n * state node.\n */\n public output?:\n | Mapper<MachineContext, EventObject, unknown, EventObject>\n | NonReducibleUnknown;\n\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n public order: number = -1;\n\n public description?: string;\n\n public schemas: SetupStateSchemas | undefined;\n\n public tags: string[] = [];\n public transitions!: Map<string, AnyTransitionDefinition[]>;\n public always?: Array<AnyTransitionDefinition>;\n public invoke: Array<AnyInvokeDefinition>;\n public on!: TransitionDefinitionMap<any, any>;\n public after!: Array<DelayedTransitionDefinition<any, any>>;\n public events!: Array<EventDescriptor<any>>;\n public ownEvents!: Array<EventDescriptor<any>>;\n private _candidateCache?: Map<string, AnyTransitionDefinition[]>;\n\n constructor(\n /** The raw config used to create the machine. */\n public config: AnyStateNodeConfig,\n options: StateNodeOptions<TContext, TEvent>\n ) {\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n const firstStateKey = this.config.states\n ? Object.keys(this.config.states)[0]\n : undefined;\n this.id =\n this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type =\n this.config.type ||\n (firstStateKey !== undefined\n ? 'compound'\n : this.config.history\n ? 'history'\n : 'atomic');\n this.description = this.config.description;\n this.schemas = this.config.schemas;\n\n validateStateNodeConfig(this);\n\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n\n this.states = (\n this.config.states\n ? mapValues(\n this.config.states,\n (stateConfig: AnyStateNodeConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }\n )\n : EMPTY_OBJECT\n ) as StateNodesConfig<TContext, TEvent>;\n\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(\n isDevelopment\n ? `No initial state specified for compound state node \"#${\n this.id\n }\". Try adding { initial: \"${firstStateKey}\" } to the state config.`\n : `No initial state specified for compound state node \"#${this.id}\".`\n );\n }\n\n // History config\n this.history =\n this.config.history === true ? 'shallow' : this.config.history || false;\n\n this.entry = this.config.entry as AnyAction | undefined;\n this.exit = this.config.exit as AnyAction | undefined;\n\n if (this.entry) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.entry._special = true;\n }\n\n if (this.exit) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.exit._special = true;\n }\n\n this.meta = this.config.meta;\n this.output =\n this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {\n const { src, registryKey } = invokeConfig;\n const invokeId = createInvokeId(this.id, i);\n const resolvedId = invokeConfig.id ?? invokeId;\n // Referenced (string) actors keep their logical name so persisted\n // snapshots reference `src: 'fetchUser'` rather than a positional id;\n // only inline logic gets the synthetic source name.\n const sourceName =\n typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;\n\n return {\n ...invokeConfig,\n src: sourceName,\n logic: src,\n id: resolvedId,\n registryKey\n } as AnyInvokeDefinition;\n });\n }\n\n /** @internal */\n public _initialize() {\n this.after = getDelayedTransitions(this) as any;\n this.transitions = formatTransitions(this);\n if (this.type === 'choice') {\n this.always = formatChoiceTransitions(this);\n } else if (this.config.always) {\n this.always = mapTransitionConfigs(this.config.always, (transition) =>\n formatTransition(this, NULL_EVENT, transition)\n );\n }\n\n for (const key of Object.keys(this.states)) {\n this.states[key]._initialize();\n }\n\n this._refreshEventMetadata();\n }\n\n /** @internal */\n public _refreshEventMetadata() {\n const on = {} as TransitionDefinitionMap<TContext, TEvent>;\n const ownEvents: EventDescriptor<any>[] = [];\n for (const [descriptor, transitions] of this.transitions) {\n (on as any)[descriptor] = transitions.slice();\n if (\n transitions.some(\n (transition) =>\n transition.target || transition.reenter || transition.to\n )\n ) {\n ownEvents.push(descriptor);\n }\n }\n this.on = on;\n this.ownEvents = ownEvents;\n\n const events = new Set<EventDescriptor<any>>(ownEvents);\n for (const state of Object.values(this.states)) {\n for (const event of state.events) {\n events.add(event);\n }\n }\n this.events = Array.from(events);\n }\n\n public get initial(): InitialTransitionDefinition {\n return memo(this, 'initial', () =>\n formatInitialTransition(this, this.config.initial)\n );\n }\n\n /** @internal */\n public next(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> | undefined {\n const descriptorKey = getEventDescriptorKey(event);\n let candidates = this._candidateCache?.get(descriptorKey);\n if (!candidates) {\n candidates = getCandidates(this, event);\n (this._candidateCache ??= new Map()).set(descriptorKey, candidates);\n }\n\n for (const candidate of candidates) {\n const guardPassed = evaluateCandidate(\n candidate,\n event,\n snapshot,\n this,\n actorScope,\n selectionResults\n );\n\n if (guardPassed) {\n return [candidate];\n }\n }\n\n return undefined;\n }\n}\n\nfunction validateStateNodeConfig(stateNode: AnyStateNode) {\n const config = stateNode.config as any;\n\n if (\n stateNode.type === 'history' &&\n !(\n (typeof config.target === 'string' && config.target.trim().length > 0) ||\n (Array.isArray(config.target) &&\n config.target.length > 0 &&\n config.target.every(\n (target: unknown) =>\n typeof target === 'string' && target.trim().length > 0\n ))\n )\n ) {\n throw new Error(\n isDevelopment\n ? `History state \"${stateNode.id}\" must declare a non-empty \\`target\\`.`\n : `Missing history target on \"${stateNode.id}\"`\n );\n }\n\n if (stateNode.type !== 'choice') {\n if (isDevelopment && config.choice !== undefined) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`choice\\`, but \\`choice\\` can only be used with \\`type: 'choice'\\`.`\n );\n }\n return;\n }\n\n if (typeof config.choice !== 'function') {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must declare a \\`choice\\` function.`\n : `Missing \\`choice\\` function on \"${stateNode.id}\"`\n );\n }\n\n if (isDevelopment) {\n for (const key of CHOICE_CONFIG_KEYS) {\n if (config[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\`.`\n );\n }\n }\n }\n}\n\nfunction formatChoiceTransitions(\n stateNode: AnyStateNode\n): AnyTransitionDefinition[] {\n const choice = (stateNode.config as any).choice;\n const validateChoiceResult = (result: any): AnyTransitionConfig => {\n if (!result || result.target === undefined) {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must resolve to a target.`\n : `Choice \"${stateNode.id}\" has no target`\n );\n }\n if (isDevelopment) {\n for (const key of ['actions', 'to'] as const) {\n if (result[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\` on a choice.`\n );\n }\n }\n }\n return result;\n };\n\n return [\n formatTransition(stateNode, NULL_EVENT, {\n to: (args: any) => validateChoiceResult(choice(args))\n } as AnyTransitionConfig)\n ];\n}\n\nfunction mapTransitionConfigs<T>(\n transitionsConfig: unknown,\n mapper: (transition: AnyTransitionConfig) => T\n): T[] {\n const transitionConfigs = toTransitionConfigArray(transitionsConfig as any);\n const transitions = new Array<T>(transitionConfigs.length);\n\n for (let i = 0; i < transitionConfigs.length; i++) {\n transitions[i] = mapper(transitionConfigs[i]);\n }\n\n return transitions;\n}\n\nfunction formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n const addTransitions = (\n descriptor: string,\n additions: AnyTransitionDefinition[]\n ) => {\n transitions.set(descriptor, [\n ...(transitions.get(descriptor) ?? []),\n ...additions\n ]);\n };\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n isDevelopment\n ? 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n : 'Null event transition key'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n mapTransitionConfigs(transitionsConfig, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = 'xstate.done.state';\n addTransitions(\n descriptor,\n mapTransitionConfigs(stateNode.config.onDone, (transition) =>\n formatTransition(stateNode, descriptor, {\n ...transition,\n matches: { ...transition.matches, stateId: stateNode.id }\n })\n )\n );\n }\n if (stateNode.config.onError) {\n const descriptor = 'xstate.error.*';\n transitions.set(\n descriptor,\n mapTransitionConfigs(stateNode.config.onError, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n const createCancelInvokeTimeoutTransition = (\n descriptor: string,\n timeoutEventId: string,\n actorId: string\n ): AnyTransitionDefinition =>\n formatTransition(stateNode, descriptor, {\n matches: { actorId },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, actorId),\n to: (_args: any, enq: any) => {\n enq.cancel(timeoutEventId);\n return {};\n }\n } as AnyTransitionConfig);\n const formatInvokeCompletionTransition = (\n descriptor: string,\n transitionConfig: AnyTransitionConfig,\n timeoutEventId: string\n ): AnyTransitionDefinition => {\n const { target, to, reenter, ...rest } = transitionConfig;\n\n return formatTransition(stateNode, descriptor, {\n ...rest,\n reenter,\n to: (args: any, enq: any) => {\n if (to) {\n let didEnqueue = false;\n const trackingEnqueue = new Proxy(enq, {\n apply(target, thisArg, argArray) {\n didEnqueue = true;\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n return (...argArray: any[]) => {\n didEnqueue = true;\n return value.apply(target, argArray);\n };\n }\n });\n const result = to(args, trackingEnqueue);\n\n if (result !== undefined || didEnqueue) {\n enq.cancel(timeoutEventId);\n }\n\n return result;\n }\n\n enq.cancel(timeoutEventId);\n return {\n target,\n reenter\n };\n }\n } as AnyTransitionConfig);\n };\n for (const invokeDef of stateNode.invoke) {\n const withInvokeMatch = (transition: AnyTransitionConfig) => ({\n ...transition,\n matches: { ...transition.matches, actorId: invokeDef.id },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id)\n });\n const invokeTimeoutEventId =\n invokeDef.timeout !== undefined\n ? createInvokeTimeoutEventId(invokeDef.id)\n : undefined;\n\n if (invokeDef.onDone) {\n const descriptor = 'xstate.done.actor';\n const invokeDoneTransitions = mapTransitionConfigs(\n invokeDef.onDone,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n );\n\n if (invokeTimeoutEventId) {\n invokeDoneTransitions.push(\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n );\n }\n\n addTransitions(descriptor, invokeDoneTransitions);\n } else if (invokeTimeoutEventId) {\n const descriptor = 'xstate.done.actor';\n addTransitions(descriptor, [\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n ]);\n }\n if (invokeDef.onError) {\n const descriptor = 'xstate.error.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onError, (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n })\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = 'xstate.snapshot.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onSnapshot, (transition) =>\n formatTransition(stateNode, descriptor, withInvokeMatch(transition))\n )\n );\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(\n delayedTransition as TransitionDefinition<TContext, AnyEventObject>\n );\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nfunction formatInitialTransition(\n stateNode: AnyStateNode,\n _target:\n | string\n | { target: string | string[]; input?: any; to?: (...args: any[]) => any }\n | undefined\n): InitialTransitionDefinition {\n const targetString =\n typeof _target === 'object' && _target !== null ? _target.target : _target;\n const input =\n typeof _target === 'object' && _target !== null ? _target.input : undefined;\n const to =\n typeof _target === 'object' && _target !== null ? _target.to : undefined;\n const targetStrings = Array.isArray(targetString)\n ? targetString\n : targetString\n ? [targetString]\n : [];\n const resolvedTargets = targetStrings.map((target) =>\n target.startsWith('#')\n ? stateNode.machine.getStateNodeById(target.slice(1))\n : stateNode.states[target]\n );\n if (resolvedTargets.some((target) => !target)) {\n throw new Error(\n isDevelopment\n ? `Initial state node \"${targetStrings.find((_, index) => !resolvedTargets[index])}\" not found on parent state node #${stateNode.id}`\n : `Initial state not found on \"#${stateNode.id}\"`\n );\n }\n const transition: InitialTransitionDefinition = {\n source: stateNode,\n target: resolvedTargets.length\n ? (resolvedTargets as AnyStateNode[])\n : undefined,\n input,\n to\n };\n\n return transition;\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE, createActor } from './createActor.ts';\nimport {\n createErrorPlatformEvent,\n createInitEvent,\n createInvokeTimeoutEvent\n} from './eventUtils.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { parseGeneratedActorId } from './system.ts';\nimport { createRemoteActorRef } from './remoteActorRef.ts';\n\nimport { createSpawner } from './spawn.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from './getNextSnapshot.ts';\nimport { withActorSelf } from './actorScope.ts';\nimport {\n createMachineSnapshot,\n cloneMachineSnapshot,\n getPersistedSnapshot,\n MachineSnapshot\n} from './State.ts';\nimport { setSnapshotActorRef } from './snapshotActorRef.ts';\nimport { StateNode } from './StateNode.ts';\nimport {\n formatRouteTransitions,\n getAllStateNodes,\n getStateNodeByPath,\n getStateNodes,\n getTransitionResult,\n hasEffect,\n initialMicrostep,\n isInFinalState,\n isStateId,\n macrostep,\n resolveStateValue,\n transitionNode,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport {\n beginSpawnAllocation,\n createSpawnEffect,\n resolveActionsWithContext,\n mergeActorIdCounters,\n takeSpawnAllocationCounters\n} from './transitionActions.ts';\nimport { AnyActorSystem } from './system.ts';\nimport type {\n ActorLogic,\n ActorLogicTransitionResult,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyTransitionDefinition,\n Equals,\n EventDescriptor,\n EmittedFrom,\n EventObject,\n EventFromLogic,\n ExecutableActionObject,\n ExecutableActionObjectFromLogic,\n HistoryValue,\n InputFrom,\n IsAny,\n LogicalTimer,\n MachineContext,\n MetaObject,\n OutputFrom,\n Snapshot,\n SnapshotFrom,\n StateValue,\n StateSchema,\n SnapshotStatus,\n AnyStateNode\n} from './types.ts';\nimport {\n AnyMachineSchemas,\n DelaySourceMap,\n GuardSourceMap,\n Sources,\n Next_MachineConfig,\n MachineOptions\n} from './types.v6.ts';\nimport {\n matchesEventDescriptor,\n resolveReferencedActor,\n toStatePath\n} from './utils.ts';\nimport { assertValid } from './validation.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type { PersistedMachineSnapshot } from './machineVersion.types.ts';\n\nconst STATE_IDENTIFIER = '#';\n\nfunction findEventSchema(\n schemas: Record<string, StandardSchemaV1> | undefined,\n eventType: string\n): StandardSchemaV1 | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (Object.hasOwn(schemas, eventType)) {\n return schemas[eventType];\n }\n\n const descriptor = Object.keys(schemas).find((key) =>\n matchesEventDescriptor(eventType, key)\n );\n return descriptor === undefined ? undefined : schemas[descriptor];\n}\n\nlet emptyCanActor: AnyActor | undefined;\nlet emptyCanActorScope: AnyActorScope | undefined;\n\nfunction getEmptyCanActor(): AnyActor {\n // A minimal inert actor used purely as the `self`/`parent` argument when\n // dry-running transitions for `snapshot.can(...)`. Intentionally not built\n // on `createLogic` so `can()` does not pull that machinery into bundles.\n return (emptyCanActor ??= createActor({\n transition: (snapshot: any) => [snapshot, []],\n initialTransition: () => [\n { status: 'active', output: undefined, error: undefined },\n []\n ],\n getInitialSnapshot: () => ({\n status: 'active',\n output: undefined,\n error: undefined\n }),\n getPersistedSnapshot: (snapshot: any) => snapshot\n } as any) as AnyActor);\n}\n\nfunction getEmptyCanActorScope(): AnyActorScope {\n if (emptyCanActorScope) {\n return emptyCanActorScope;\n }\n\n const actor = getEmptyCanActor();\n emptyCanActorScope = {\n self: actor,\n logger: () => {},\n id: '',\n sessionId: '',\n defer: () => {},\n system: actor.system,\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n return emptyCanActorScope;\n}\n\ntype CompatibleProvidedActorSource<\n TExpected extends AnyActorLogic,\n TActual extends AnyActorLogic\n> =\n IsAny<TActual> extends true\n ? TActual\n : [OutputFrom<TActual>] extends [OutputFrom<TExpected>]\n ? [Omit<SnapshotFrom<TActual>, 'input'>] extends [\n Omit<SnapshotFrom<TExpected>, 'input'>\n ]\n ? [InputFrom<TExpected>] extends [InputFrom<TActual>]\n ? [EventFromLogic<TExpected>] extends [EventFromLogic<TActual>]\n ? [EmittedFrom<TActual>] extends [EmittedFrom<TExpected>]\n ? TActual\n : never\n : never\n : never\n : never\n : never;\n\ntype ProvidedActors<\n TExpectedActorMap extends Sources['actors'],\n TProvidedActorMap extends Partial<\n Record<keyof TExpectedActorMap & string, AnyActorLogic>\n >\n> = {\n [K in keyof TProvidedActorMap]: K extends keyof TExpectedActorMap\n ? TProvidedActorMap[K] extends AnyActorLogic\n ? CompatibleProvidedActorSource<\n TExpectedActorMap[K],\n TProvidedActorMap[K]\n >\n : never\n : never;\n};\n\nexport class StateMachine<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TConfig extends StateSchema,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TInternalEvent extends EventObject = never\n> implements ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n> {\n /**\n * @internal Type-only marker for the actor's internal event protocol. Not\n * `declare` (the build's babel pipeline rejects declare class fields); the\n * one `undefined` property this emits per machine instance is inert.\n */\n readonly _internalEventType!: TInternalEvent;\n\n /** The machine's own version. */\n public version?: string;\n\n public schemas: AnyMachineSchemas | undefined;\n\n /** Standard Schema for snapshots persisted by this machine version. */\n public readonly snapshotSchema: StandardSchemaV1<\n unknown,\n Snapshot<unknown> & PersistedMachineSnapshot & { context: TContext }\n >;\n\n /** Standard Schema for complete events accepted by this machine version. */\n public readonly eventSchema: StandardSchemaV1<unknown, TEvent>;\n\n public sources: Sources;\n\n /** Runtime options for machine execution. */\n public options: MachineOptions;\n\n /** @internal */\n public idMap: Map<string, AnyStateNode> = new Map();\n\n public root: StateNode<TContext, TEvent>;\n\n public id: string;\n\n public states: StateNode<TContext, TEvent>['states'];\n public events: Array<EventDescriptor<TEvent>>;\n public internalEventDescriptors: ReadonlyArray<string>;\n /** @internal Skips eventless-selection scans for machines without `always`. */\n public _hasEventlessTransitions: boolean;\n constructor(\n /** The raw config used to create the machine. */\n public config: Next_MachineConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TEmitted\n > & {\n schemas?: AnyMachineSchemas;\n internalEvents?: readonly string[];\n },\n sources?: Sources,\n public validator?: ActorLogicValidator\n ) {\n this.id = config.id || '(machine)';\n this.sources = {\n actors: config.actors ?? {},\n actions: config.actions ?? {},\n delays: (config.delays ?? {}) as Sources['delays'],\n guards: config.guards ?? {},\n ...sources\n };\n if (isDevelopment) {\n // The `@xstate.` prefix is reserved for built-in serialized action and\n // guard descriptors — user source names must not collide.\n for (const kind of ['actions', 'guards', 'actors', 'delays'] as const) {\n for (const key of Object.keys(this.sources[kind])) {\n if (key.startsWith('@xstate.')) {\n throw new Error(\n `Invalid ${kind} name '${key}': the '@xstate.' prefix is reserved for built-in descriptors.`\n );\n }\n }\n }\n }\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.snapshotSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (value === null || typeof value !== 'object') {\n return { issues: [{ message: 'Expected a persisted snapshot.' }] };\n }\n const snapshot: Record<string, unknown> = {\n historyValue: {},\n timers: {},\n ...(value as Record<string, unknown>)\n };\n const contextSchema = this.schemas?.context;\n let context = snapshot.context;\n if (contextSchema) {\n const result = await contextSchema['~standard'].validate(context);\n if (result.issues) {\n return {\n issues: [\n {\n message: `Invalid context for machine '${this.id}' version '${this.version}': ${result.issues[0]?.message}`\n }\n ]\n };\n }\n context = result.value;\n }\n for (const key of ['value', 'children'] as const) {\n if (!(key in snapshot)) {\n return {\n issues: [{ message: `Persisted snapshot is missing '${key}'.` }]\n };\n }\n }\n if (\n !['active', 'done', 'error', 'stopped'].includes(\n snapshot.status as string\n )\n ) {\n return {\n issues: [{ message: 'Persisted snapshot has invalid status.' }]\n };\n }\n for (const key of ['children', 'historyValue', 'timers'] as const) {\n if (\n snapshot[key] === null ||\n typeof snapshot[key] !== 'object' ||\n Array.isArray(snapshot[key])\n ) {\n return {\n issues: [\n { message: `Persisted snapshot has invalid '${key}'.` }\n ]\n };\n }\n }\n try {\n this.resolveState({\n value: snapshot.value as StateValue,\n context\n } as any);\n } catch (error) {\n return {\n issues: [\n {\n message:\n error instanceof Error\n ? error.message\n : 'Persisted snapshot has invalid state value.'\n }\n ]\n };\n }\n return {\n value: { ...snapshot, context } as Snapshot<unknown> &\n PersistedMachineSnapshot & { context: TContext }\n };\n }\n }\n };\n this.eventSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (\n value === null ||\n typeof value !== 'object' ||\n typeof (value as EventObject).type !== 'string'\n ) {\n return { issues: [{ message: 'Expected an event object.' }] };\n }\n const event = value as EventObject;\n const eventSchemas = this.schemas?.events;\n const internalEventSchemas = this.schemas?.internalEvents;\n const isFrameworkEvent =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n const schema =\n findEventSchema(internalEventSchemas, event.type) ??\n findEventSchema(eventSchemas, event.type);\n if (\n (eventSchemas || internalEventSchemas) &&\n !schema &&\n !isFrameworkEvent\n ) {\n return {\n issues: [\n {\n message: `Unknown event '${event.type}' for machine '${this.id}' version '${this.version}'.`\n }\n ]\n };\n }\n if (!schema) {\n return { value: event as TEvent };\n }\n const { type, ...payload } = event;\n const result = await schema['~standard'].validate(payload);\n if (result.issues) {\n return result;\n }\n if (result.value === null || typeof result.value !== 'object') {\n return { issues: [{ message: 'Expected an event payload.' }] };\n }\n return { value: { ...result.value, type } as TEvent };\n }\n }\n };\n this.internalEventDescriptors = [\n ...Object.keys(this.schemas?.internalEvents ?? {}),\n ...(this.config.internalEvents ?? [])\n ];\n this.options = {\n maxIterations: Infinity,\n ...this.config.options\n };\n\n this.transition = this.transition.bind(this);\n this.initialTransition = this.initialTransition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.restoreSnapshot = this.restoreSnapshot.bind(this);\n this.start = this.start.bind(this);\n\n this.root = new StateNode(config as any, {\n _key: this.id,\n _machine: this as any\n });\n\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.root._refreshEventMetadata();\n this._hasEventlessTransitions = Array.from(this.idMap.values()).some(\n (stateNode) => !!stateNode.always?.length\n );\n\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided sources.\n *\n * @param sources Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided sources.\n */\n public provide<\n const TProvidedActorMap extends Partial<\n Record<keyof TActorMap & string, AnyActorLogic>\n > = {}\n >(sources: {\n actions?: Partial<TActionMap>;\n actors?: TProvidedActorMap & ProvidedActors<TActorMap, TProvidedActorMap>;\n // Mapped over the known names (not an index signature) so unknown source\n // names are still rejected, while entries keep typed args/return values.\n guards?: Partial<TGuardMap> & {\n [K in keyof TGuardMap]?: GuardSourceMap<TContext, TEvent>[string];\n };\n // Delays are widened to `number | fn` per entry (not Partial<TDelayMap>)\n // so a fixed delay can be swapped for a computed one and vice versa.\n delays?: {\n [K in keyof TDelayMap]?: DelaySourceMap<TContext, TEvent>[string];\n };\n }): this {\n const { actions, guards, actors, delays } = this.sources;\n\n const provided = new StateMachine(\n this.config,\n {\n actions: {\n ...actions,\n ...sources.actions\n } as Sources['actions'],\n guards: {\n ...guards,\n ...sources.guards\n } as Sources['guards'],\n actors: {\n ...actors,\n ...sources.actors\n } as Sources['actors'],\n delays: {\n ...delays,\n ...sources.delays\n } as Sources['delays']\n },\n this.validator\n ) as unknown as this;\n // Providing sources does not change the serializable definition.\n provided._json = this._json;\n return provided;\n }\n\n public resolveState(\n config: {\n value: StateValue;\n context?: TContext;\n historyValue?: HistoryValue;\n status?: SnapshotStatus;\n output?: TOutput;\n error?: unknown;\n } & ([TContext] extends [never]\n ? {}\n : Equals<TContext, MachineContext> extends false\n ? { context: unknown }\n : {})\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(\n getStateNodes(this.root, resolvedStateValue)\n );\n const nodes = [...nodeSet];\n\n return createMachineSnapshot(\n {\n _nodes: nodes,\n value: resolvedStateValue,\n context: config.context || ({} as TContext),\n children: {},\n status: isInFinalState(nodeSet, this.root)\n ? 'done'\n : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n },\n this\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n public transition(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope?: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(\n this,\n snapshot as SnapshotFrom<this>\n )) as NonNullable<typeof actorScope>;\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'event',\n logic: this,\n event,\n eventOrigin:\n actorScope && (actorScope.self as any)._lastSourceRef\n ? 'actor'\n : 'external'\n });\n }\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);\n }\n beginSpawnAllocation(resolvedActorScope);\n const fastSnapshot = this._transitionFast(\n snapshot,\n event,\n resolvedActorScope\n );\n if (fastSnapshot) {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);\n }\n const returnedSnapshot =\n usesInertScope && fastSnapshot !== snapshot\n ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot)\n : this._attachPureActorRef(fastSnapshot, resolvedActorScope);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects: []\n });\n }\n return [returnedSnapshot, []];\n }\n\n const { snapshot: nextSnapshot, microsteps } = macrostep(\n snapshot,\n event,\n resolvedActorScope,\n []\n );\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);\n }\n const returnedSnapshot = usesInertScope\n ? nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(resolvedActorScope, nextSnapshot)\n : this._attachPureActorRef(nextSnapshot, resolvedActorScope);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [\n returnedSnapshot as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n effects\n ];\n }\n\n private _collectEffects(\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ExecutableActionObjectFromLogic<this>[] {\n return microsteps.flatMap(\n ([, actions]) => actions\n ) as ExecutableActionObjectFromLogic<this>[];\n }\n\n private _attachPureActorRef<TSnapshot extends AnyMachineSnapshot>(\n snapshot: TSnapshot,\n actorScope: AnyActorScope,\n skipInitializingActor = false\n ): TSnapshot {\n if (isInertActorScope(actorScope)) {\n return snapshot;\n }\n if (\n skipInitializingActor &&\n (\n actorScope.self as AnyActor & {\n _actorScope?: AnyActorScope;\n _snapshot?: unknown;\n }\n )._actorScope === actorScope &&\n (actorScope.self as AnyActor & { _snapshot?: unknown })._snapshot ===\n undefined\n ) {\n return snapshot;\n }\n setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);\n return snapshot;\n }\n\n private _transitionFast(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ):\n | MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | undefined {\n if (\n snapshot.status !== 'active' ||\n typeof snapshot.value !== 'string' ||\n this.root.always?.length\n ) {\n return undefined;\n }\n\n const sourceNode = this.root.states[snapshot.value];\n if (\n !sourceNode ||\n sourceNode.type !== 'atomic' ||\n sourceNode.exit ||\n sourceNode.invoke.length ||\n sourceNode.always?.length ||\n sourceNode.after?.length\n ) {\n return undefined;\n }\n\n const transitions = sourceNode.transitions.get(event.type);\n if (transitions?.length !== 1) {\n return undefined;\n }\n\n const selected = transitions[0];\n if (\n selected.guard ||\n selected.actions ||\n selected.to ||\n selected.reenter ||\n selected.input ||\n typeof selected.context === 'function' ||\n (selected.target && selected.target.length !== 1)\n ) {\n return undefined;\n }\n\n const targetNode = selected.target?.[0] ?? sourceNode;\n const stateChanged = targetNode !== sourceNode;\n if (\n targetNode.parent !== this.root ||\n targetNode.type !== 'atomic' ||\n (stateChanged &&\n (targetNode.entry ||\n targetNode.invoke.length ||\n targetNode.always?.length ||\n targetNode.after?.length))\n ) {\n return undefined;\n }\n\n const context =\n selected.context !== undefined\n ? ({ ...snapshot.context, ...selected.context } as TContext)\n : snapshot.context;\n\n if (\n !isInertActorScope(actorScope) &&\n (actorScope.system._hasInspectionObservers?.() ?? true)\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(selected);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n\n return cloneMachineSnapshot(snapshot, {\n ...(context !== snapshot.context ? { context } : {}),\n ...(stateChanged ? { _nodes: [this.root, targetNode] } : {})\n });\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n public microstep(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope\n ): Array<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n > {\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n const snapshots = new Array(microsteps.length);\n\n for (let i = 0; i < microsteps.length; i++) {\n snapshots[i] = microsteps[i][0];\n }\n\n return snapshots;\n }\n\n public getTransitionData(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> {\n return (\n transitionNode(\n this.root,\n snapshot.value,\n snapshot,\n event,\n actorScope,\n selectionResults\n ) || []\n );\n }\n\n public isInternalEventType(eventType: string): boolean {\n if (eventType === XSTATE_TIMER) {\n return true;\n }\n for (const descriptor of this.internalEventDescriptors) {\n if (matchesEventDescriptor(eventType, descriptor)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines whether sending the `event` to the given snapshot would select a\n * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that\n * non-machine bundles don't pay for the transition-resolution machinery.\n *\n * @internal\n */\n public _canTransition(snapshot: AnyMachineSnapshot, event: TEvent): boolean {\n const emptyActorScope = getEmptyCanActorScope();\n const transitionData = this.getTransitionData(\n snapshot as any,\n event,\n emptyActorScope\n );\n\n if (!transitionData?.length) {\n return false;\n }\n\n // Check that at least one transition is not forbidden\n for (const transition of transitionData) {\n if (transition.target !== undefined) {\n return true;\n }\n\n const res = getTransitionResult(\n transition,\n snapshot,\n event,\n emptyActorScope,\n { resolveActions: false }\n );\n if (\n res.targets?.length ||\n res.context ||\n hasEffect(\n transition,\n snapshot.context,\n event,\n snapshot,\n emptyActorScope\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns the error event that the actor should transition with to recover\n * from an execution error, if any active state node declares `onError`.\n *\n * @internal\n */\n public getExecutionErrorEvent(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n error: unknown\n ): TEvent | undefined {\n if (\n (snapshot as any)?.status !== 'active' ||\n !snapshot.nodes?.some((stateNode) => stateNode.config.onError)\n ) {\n return undefined;\n }\n return createErrorPlatformEvent('execution', error) as unknown as TEvent;\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(\n actorScope: AnyActorScope,\n initEvent: any\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const { context } = this.config;\n\n const preInitial = createMachineSnapshot(\n {\n context:\n typeof context !== 'function' && context ? context : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n );\n\n if (typeof context === 'function') {\n const children = {};\n const spawn = createSpawner(actorScope, this.sources.actors, children);\n const resolvedContext = context(\n withActorSelf(\n {\n spawn,\n input: initEvent.input,\n actors: this.sources.actors\n },\n actorScope\n )\n );\n const [nextState] = resolveActionsWithContext(\n preInitial,\n initEvent,\n actorScope,\n []\n ) as any;\n if (resolvedContext) {\n nextState.context = resolvedContext;\n }\n if (Object.keys(children).length > 0) {\n nextState.children = {\n ...nextState.children,\n ...children\n };\n // Commit the transaction counters so context-factory allocations\n // persist with the snapshot: a freed id is never handed out again\n // after a restore or in a fresh replay process. (The spawner already\n // registered each child for string-id resolution.)\n const counters = takeSpawnAllocationCounters(actorScope);\n if (counters) {\n nextState._nextActorIds = mergeActorIdCounters(\n nextState._nextActorIds,\n counters\n );\n }\n }\n return nextState as SnapshotFrom<this>;\n }\n\n return preInitial as SnapshotFrom<this>;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n public getInitialSnapshot(\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >,\n input?: TInput\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n return this.initialTransition(input, actorScope)[0];\n }\n\n public initialTransition(\n input: TInput | undefined,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'input',\n logic: this,\n input\n });\n }\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n beginSpawnAllocation(resolvedActorScope);\n const initEvent = createInitEvent(input) as unknown as TEvent; // TODO: fix;\n const internalQueue: AnyEventObject[] = [];\n const preInitialState = this._getPreInitialState(\n resolvedActorScope,\n initEvent\n );\n const contextSpawnEffects = Object.values(preInitialState.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n const finalizeInitialResult = (\n macroState: AnyMachineSnapshot,\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ActorLogicTransitionResult<\n SnapshotFrom<this>,\n ExecutableActionObjectFromLogic<this>\n > => {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, macroState, false);\n }\n const returnedSnapshot = usesInertScope\n ? attachSnapshotActorRef(resolvedActorScope, macroState)\n : this._attachPureActorRef(macroState, resolvedActorScope, true);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [returnedSnapshot as SnapshotFrom<this>, effects];\n };\n\n try {\n const [nextState, initialActions] = initialMicrostep(\n this.root,\n preInitialState,\n resolvedActorScope,\n initEvent,\n internalQueue\n );\n\n const { snapshot: macroState, microsteps } = macrostep(\n nextState,\n initEvent as AnyEventObject,\n resolvedActorScope,\n internalQueue,\n [\n [nextState, [...contextSpawnEffects, ...initialActions]] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(macroState, microsteps);\n } catch (err) {\n if (!this.root.config.onError) {\n throw err;\n }\n const errorEvent = createErrorPlatformEvent('execution', err);\n const errorMacrostep = macrostep(\n preInitialState,\n errorEvent,\n resolvedActorScope,\n [],\n [\n [preInitialState, contextSpawnEffects] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(\n errorMacrostep.snapshot,\n errorMacrostep.microsteps\n );\n }\n }\n\n public start(\n snapshot?: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n ): void {\n // Start rehydrated children that were active when persisted. Freshly\n // invoked/spawned children are NOT started here — they start via deferred\n // `@xstate.start` actions so sync start errors route to `onError`.\n if (!snapshot?.children) {\n return;\n }\n const children = snapshot.children as unknown as Record<string, AnyActor>;\n for (const childId in children) {\n if (!Object.hasOwn(children, childId)) {\n continue;\n }\n const child = children[childId];\n if (\n (child as any)._rehydrated &&\n (child as any).getSnapshot?.().status === 'active'\n ) {\n (child as any).start();\n }\n }\n }\n\n public getStateNodeById(stateId: string): StateNode<TContext, TEvent> {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0])\n ? fullPath[0].slice(STATE_IDENTIFIER.length)\n : fullPath[0];\n\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(\n `Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`\n );\n }\n return getStateNodeByPath(stateNode, relativePath) as StateNode<\n TContext,\n TEvent\n >;\n }\n\n public getPersistedSnapshot(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n options?: unknown\n ) {\n return getPersistedSnapshot(snapshot, options);\n }\n\n /**\n * The original JSON definition this machine was created from (set by\n * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless\n * round-trips.\n *\n * @internal\n */\n public _json?: Record<string, unknown>;\n\n public restoreSnapshot(\n snapshot: Snapshot<unknown>,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n const snapshotMachine = (snapshot as any).machine;\n // A live machine snapshot carries its producing machine so helpers such as\n // `matches()` can resolve state nodes. That runtime association is not the\n // persisted `{ id, version }` identity written by getPersistedSnapshot().\n const persistedMachine =\n snapshotMachine &&\n typeof snapshotMachine === 'object' &&\n typeof snapshotMachine.transition === 'function' &&\n 'root' in snapshotMachine\n ? undefined\n : snapshotMachine;\n const legacyPersistedVersion: string | undefined = (snapshot as any)\n .version;\n const persistedVersion: string | undefined =\n typeof persistedMachine?.version === 'string'\n ? persistedMachine.version\n : legacyPersistedVersion;\n if (\n legacyPersistedVersion !== undefined &&\n persistedMachine?.version !== undefined &&\n persistedMachine.version !== legacyPersistedVersion\n ) {\n throw new Error(\n `Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`\n );\n }\n if (\n persistedMachine &&\n typeof persistedMachine.id === 'string' &&\n persistedMachine.id !== this.id\n ) {\n throw new Error(\n isDevelopment\n ? `Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${this.id}' was provided.`\n : `Machine ID mismatch: persisted snapshot machine '${persistedMachine.id}' does not match '${this.id}'.`\n );\n }\n if (persistedVersion !== this.version) {\n const migrate = (this.config as any).migrate;\n if (typeof migrate !== 'function') {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}' for machine '${this.id}'. Provide a \\`migrate(persistedSnapshot, fromVersion)\\` function in the machine config to migrate old snapshots.`\n : `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`\n );\n }\n snapshot = migrate(snapshot, persistedVersion);\n }\n\n const snapshotData = snapshot as any;\n const children: Record<string, AnyActor> = {};\n const snapshotChildren: Record<\n string,\n {\n src: string | AnyActorLogic;\n snapshot?: Snapshot<unknown>;\n address?: string;\n remote?: boolean;\n incarnation?: string;\n syncSnapshot?: boolean;\n registryKey?: string;\n }\n > = snapshotData.children;\n\n for (const actorId of Object.keys(snapshotChildren)) {\n const actorData = snapshotChildren[actorId];\n\n if (actorData.remote === true && actorData.address !== undefined) {\n if (typeof actorData.src !== 'string') {\n // Fail loudly instead of fabricating a source key that hosts would\n // route by.\n throw new Error(\n `Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`\n );\n }\n // The child's state lives with another runtime; restore a\n // location-transparent handle constructed from its identity alone.\n // The handle keeps its persisted address verbatim: the owning\n // runtime's identity for the child wins over the local parent chain.\n const handle = createRemoteActorRef(resolvedActorScope.system, {\n id: actorId,\n address: actorData.address,\n src: actorData.src,\n parent: resolvedActorScope.self,\n registryKey: actorData.registryKey,\n syncSnapshot: actorData.syncSnapshot,\n incarnation: actorData.incarnation\n });\n if (actorData.registryKey) {\n resolvedActorScope.system._set(actorData.registryKey, handle);\n }\n children[actorId] = handle;\n continue;\n }\n\n const childState = actorData.snapshot;\n const src = actorData.src;\n\n const logic =\n typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n\n if (!logic) {\n const sourceId = typeof src === 'string' ? src : '<unknown>';\n throw new Error(\n `Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`\n );\n }\n\n const actor = resolvedActorScope.system.createActorRef(logic, {\n id: actorId,\n parent: resolvedActorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n registryKey: actorData.registryKey\n });\n // Mark so `start()` knows to start this child (freshly invoked/spawned\n // children are started via deferred `@xstate.start` actions instead).\n (actor as any)._rehydrated = true;\n\n children[actorId] = actor;\n }\n\n const timers: Record<string, LogicalTimer> = {};\n const persistedTimers: Record<\n string,\n {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n target: string | { type: 'parent' };\n }\n > = snapshotData.timers ?? {};\n for (const [id, timer] of Object.entries(persistedTimers)) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n const actorId = (event as AnyEventObject).actorId as string;\n const child = children[actorId];\n if (child) {\n event = createInvokeTimeoutEvent(actorId, child.sessionId);\n }\n }\n const target =\n typeof timer.target === 'string'\n ? timer.target === 'self'\n ? 'self'\n : children[timer.target]\n : resolvedActorScope.self._parent;\n if (!target) {\n const targetDescription =\n typeof timer.target === 'string' ? timer.target : timer.target.type;\n throw new Error(\n `Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`\n );\n }\n timers[id] = { ...timer, event, target };\n }\n\n const reviveHistoryValue = (\n historyValue: Record<\n string,\n ({ id: string } | StateNode<TContext, TEvent>)[]\n >\n ): HistoryValue => {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived: HistoryValue = {};\n for (const key of Object.keys(historyValue)) {\n const arr = historyValue[key];\n\n for (const item of arr) {\n let resolved: StateNode<TContext, TEvent> | undefined;\n\n if (item instanceof StateNode) {\n resolved = item;\n } else {\n try {\n resolved = this.root.machine.getStateNodeById(item.id);\n } catch {\n if (isDevelopment) {\n console.warn(`Could not resolve StateNode for id: ${item.id}`);\n }\n }\n }\n\n if (!resolved) {\n continue;\n }\n\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n };\n\n const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);\n\n const validateStateValue = (\n stateValue: StateValue,\n node: AnyStateNode,\n path: string[]\n ): void => {\n const missingStateError = (statePath: string[]) =>\n new Error(\n `Persisted snapshot references state '${statePath.join('.')}' which does not exist on machine '${this.id}'.`\n );\n if (typeof stateValue === 'string') {\n if (!node.states[stateValue]) {\n throw missingStateError(path.concat(stateValue));\n }\n return;\n }\n if (!stateValue || typeof stateValue !== 'object') {\n return;\n }\n for (const key of Object.keys(stateValue)) {\n const childNode = node.states[key];\n if (!childNode) {\n throw missingStateError(path.concat(key));\n }\n validateStateValue(stateValue[key]!, childNode, path.concat(key));\n }\n };\n validateStateValue(snapshotData.value, this.root, []);\n\n const nodes = Array.from(\n getAllStateNodes(getStateNodes(this.root, snapshotData.value))\n );\n\n const {\n version: _persistedSnapshotVersion,\n // The legacy system-wide counter: superseded by per-snapshot\n // `_nextActorIds` plus the child-id fold below; dropped so old and new\n // snapshots round-trip to the same shape.\n _nextActorId: _legacyNextActorId,\n ...persistedRest\n } = snapshot as any;\n // Fold generated-shaped child ids into the counters as a floor: snapshots\n // persisted before per-actor counters (or hand-crafted ones) still must\n // never reuse a live child's id.\n let restoredCounters: Record<string, number> | undefined =\n persistedRest._nextActorIds;\n for (const childId of Object.keys(snapshotChildren)) {\n const generated = parseGeneratedActorId(childId);\n if (\n generated &&\n (restoredCounters?.[generated.prefix] ?? 0) <= generated.index\n ) {\n restoredCounters = {\n ...restoredCounters,\n [generated.prefix]: generated.index + 1\n };\n }\n }\n const restoredSnapshot = createMachineSnapshot(\n {\n ...persistedRest,\n children,\n timers,\n _nextActorIds: restoredCounters,\n _nodes: nodes,\n value: snapshotData.value,\n historyValue: revivedHistoryValue,\n _stateInputs: snapshotData.stateInputs ?? {}\n },\n this,\n resolvedActorScope.self\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n\n const seen = new WeakSet<Record<string, unknown>>();\n\n function reviveContext(contextPart: Record<string, unknown>) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (const key of Object.keys(contextPart)) {\n const value: unknown = contextPart[key];\n\n if (value && typeof value === 'object') {\n if ('xstate$type' in value && value.xstate$type === ACTOR_REF_TYPE) {\n contextPart[key] = children[(value as any).id];\n continue;\n }\n reviveContext(value as typeof contextPart);\n }\n }\n }\n\n reviveContext(restoredSnapshot.context);\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);\n return attachSnapshotActorRef(resolvedActorScope, restoredSnapshot);\n }\n\n return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);\n }\n}\n","import {\n allocateChildId,\n assertChildIdFree,\n reserveChildId\n} from './transitionActions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport {\n ActorFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n ConditionalRequired,\n InputFrom,\n IsNotNever,\n RegistryKeyForLogic,\n SystemRegistry,\n type RequiredLogicInput\n} from './types.ts';\n\nexport type Spawner<TSystemRegistry extends SystemRegistry = SystemRegistry> = <\n TLogic extends AnyActorLogic\n>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: unknown }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n) => ActorFromLogic<TLogic>;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n actors: Record<string, AnyActorLogic>,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner {\n return ((src, options) => {\n const referencedSrc = resolveRegisteredActorSource(actors, src);\n // Generated ids come from the same transaction allocator as `enq.spawn`,\n // so context-factory allocations persist with the snapshot and never\n // collide with later spawns.\n const id =\n options?.id ?? allocateChildId(actorScope, referencedSrc ?? src).id;\n if (options?.id !== undefined) {\n assertChildIdFree(actorScope, options.id);\n reserveChildId(actorScope, options.id);\n }\n const actor = actorScope.system.createActorRef(src, {\n id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src: referencedSrc ?? src,\n registryKey: options?.registryKey\n });\n spawnedChildren[actor.id] = actor;\n return actor;\n }) as Spawner;\n}\n","import { StandardSchemaV1 } from './schema.types.ts';\nimport { StateMachine } from './StateMachine.ts';\nimport {\n AnyActorRef,\n EventObject,\n AnyEventObject,\n Cast,\n MachineContext,\n ProvidedActor,\n StateValueFromStateSchema,\n ToChildren,\n MetaObject,\n StateSchema,\n DoNotInfer,\n RoutableStateId,\n Compute\n} from './types.ts';\nimport {\n Sources,\n DelayMapFromNames,\n InferChildren,\n InferOutput,\n SchemaOrConfigOutput,\n InferEvents,\n InferInternalEvents,\n Next_MachineConfig,\n Next_StateNodeConfig,\n ValidateDelayReferences,\n ValidateHistoryDefaults,\n ValidateStateTargets,\n ValidateTopLevelFinalOutputs,\n WidenLiterals,\n WithDefault\n} from './types.v6.ts';\n\ntype MergeChildren<\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActor extends ProvidedActor\n> = [keyof TChildren] extends [never]\n ? Compute<ToChildren<TActor>>\n : Compute<TChildren>;\n\ntype MachineIdentity<TConfig> = {\n readonly id: TConfig extends { id: infer TId extends string }\n ? TId\n : '(machine)';\n readonly version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n};\n\ntype TestValue =\n | string\n | {\n [k: string]: TestValue | undefined;\n };\n\ntype _GroupTestValues<TTestValue extends string | TestValue> =\n TTestValue extends string\n ? TTestValue extends `${string}.${string}`\n ? [never, never]\n : [TTestValue, never]\n : [never, TTestValue];\n\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n * id: 'light',\n * initial: 'green',\n * states: {\n * green: {\n * on: {\n * TIMER: { target: 'yellow' }\n * }\n * },\n * yellow: {\n * on: {\n * TIMER: { target: 'red' }\n * }\n * },\n * red: {\n * on: {\n * TIMER: { target: 'green' }\n * }\n * }\n * }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n * to provide machine sources instead.\n */\n// Overload 1: With schemas.context — context type inferred from schema\nexport function createMachine<\n TContextSchema extends StandardSchemaV1,\n const TEventSchemaMap extends Record<string, StandardSchemaV1>,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1>,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>,\n TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1>,\n _TEvent extends EventObject,\n TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & {\n schemas: { context: TContextSchema; children?: TChildrenSchemaMap };\n } & ValidateTopLevelFinalOutputs<\n TSS,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n InferOutput<TContextSchema, MachineContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Overload 2: Without schemas.context — context type inferred from config.context\nexport function createMachine<\n TContext extends MachineContext = never,\n const TEventSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1 = StandardSchemaV1,\n TTagSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {},\n _TEvent extends EventObject = EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TActionMap extends Sources['actions'] = Sources['actions'],\n TActorMap extends Sources['actors'] = Sources['actors'],\n TGuardMap extends Sources['guards'] = Sources['guards'],\n TDelayMap extends Sources['delays'] = Sources['delays'],\n TDelays extends string = string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string =\n StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput = unknown,\n const TSS extends StateSchema = StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n StandardSchemaV1,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n false\n > & {\n schemas?: { context?: never };\n // TContext inference site: the `const` state-schema inference above\n // suppresses literal widening, so context is widened explicitly via\n // WidenLiterals before being consumed by handlers and the snapshot.\n context?:\n | TContext\n | ((_: {\n spawn: any;\n actors: TActorMap;\n input: InferOutput<TInputSchema, unknown>;\n self: any;\n }) => TContext);\n } & ValidateTopLevelFinalOutputs<\n TSS,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n WidenLiterals<TContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Implementation\nexport function createMachine(config: any): any {\n return new StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any, // TMeta\n any, // TStateSchema\n any,\n any,\n any,\n any\n >(config) as any;\n}\n\nexport function createStateConfig<\n TContextSchema extends StandardSchemaV1,\n TEventSchema extends StandardSchemaV1,\n TEmittedSchema extends StandardSchemaV1,\n _TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n // TContext extends MachineContext,\n _TEvent extends StandardSchemaV1.InferOutput<TEventSchema> & EventObject, // TODO: consider using a stricter `EventObject` here\n _TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n _TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n _TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n Next_StateNodeConfig<\n InferOutput<TContextSchema, MachineContext>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEventSchema> & EventObject>,\n DoNotInfer<TDelays>,\n DoNotInfer<StandardSchemaV1.InferOutput<TTagSchema> & string>,\n DoNotInfer<StandardSchemaV1.InferOutput<TOutputSchema>>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEmittedSchema> & EventObject>,\n DoNotInfer<InferOutput<TMetaSchema, MetaObject>>,\n DoNotInfer<Record<string, AnyActorRef | undefined>>,\n DoNotInfer<TActionMap>,\n DoNotInfer<TActorMap>,\n DoNotInfer<TGuardMap>,\n DoNotInfer<TDelayMap>\n >\n): typeof config {\n return config;\n}\n","import { XSTATE_INIT, XSTATE_STOP, XSTATE_TIMER } from './constants.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n beginSpawnAllocation,\n finalizeTransitionResult,\n deriveDeferredStarts,\n createSendToEffect,\n createTransitionEnqueue,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport type {\n ActorLogic,\n ActorScope,\n AnyAction,\n AnyActorScope,\n AnyEventObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n LogicalTimer,\n NonReducibleUnknown,\n Snapshot\n} from './types.ts';\n\nexport type FSMSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput = unknown\n> = Snapshot<undefined> & {\n value: TState;\n context: TContext;\n input: TInput | undefined;\n children: {};\n timers: Record<string, LogicalTimer>;\n _nextTimerId: number;\n _nextActorIds?: Record<string, number>;\n _stateInput: Record<string, unknown> | undefined;\n machine: {\n id: string;\n sources: {\n actions: {};\n actors: {};\n guards: {};\n delays: {};\n };\n };\n};\n\ntype FSMArgs<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = {\n context: TContext;\n event: TEvent;\n input: TInput | undefined;\n value: TState;\n self: any;\n system: any;\n parent: any;\n children: {};\n};\n\ntype FSMAction<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (\n args: FSMArgs<TContext, TEvent, TState, TInput> & {\n input: Record<string, unknown> | undefined;\n },\n enq: ReturnType<typeof createTransitionEnqueue>\n) => void | { context?: FSMContextPatch<TContext> };\n\ntype FSMGuard<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (args: FSMArgs<TContext, TEvent, TState, TInput>) => boolean;\n\ntype FSMContextPatch<TContext extends MachineContext> = Partial<TContext> & {\n call?: never;\n apply?: never;\n bind?: never;\n};\n\ntype FSMContextMapper<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (\n args: FSMArgs<TContext, TEvent, TState, TInput>\n) => FSMContextPatch<TContext>;\n\ntype FSMTarget<TContext extends MachineContext> = {\n target?: string;\n context?: FSMContextPatch<TContext>;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: TContext;\n event: EventObject;\n }) => Record<string, unknown>);\n};\n\ntype FSMObjectTarget<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = Omit<FSMTarget<TContext>, 'context'> & {\n context?:\n | FSMContextPatch<TContext>\n | FSMContextMapper<TContext, TEvent, TState, TInput>;\n};\n\ntype FSMTransitionFunction<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (\n args: FSMArgs<TContext, TEvent, TState, TInput>,\n enq: ReturnType<typeof createTransitionEnqueue>\n) => void | false | FSMTarget<TContext>;\n\ntype FSMTransition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> =\n | FSMObjectTarget<TContext, TEvent, TState, TInput>\n | (FSMObjectTarget<TContext, TEvent, TState, TInput> & {\n guard?: FSMGuard<TContext, TEvent, TState, TInput>;\n actions?:\n | FSMAction<TContext, TEvent, TState, TInput>\n | Array<FSMAction<TContext, TEvent, TState, TInput>>;\n })\n | FSMTransitionFunction<TContext, TEvent, TState, TInput>;\n\ntype FSMStateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = {\n entry?:\n | FSMAction<TContext, TEvent, TState, TInput>\n | Array<FSMAction<TContext, TEvent, TState, TInput>>;\n exit?:\n | FSMAction<TContext, TEvent, TState, TInput>\n | Array<FSMAction<TContext, TEvent, TState, TInput>>;\n on?: Record<\n string,\n | FSMTransition<TContext, TEvent, TState, TInput>\n | Array<FSMTransition<TContext, TEvent, TState, TInput>>\n >;\n};\n\nexport type FSMConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput = NonReducibleUnknown\n> = {\n id?: string;\n initial: TState;\n context?: TContext | ((args: { input: TInput }) => TContext);\n states: Record<TState, FSMStateConfig<TContext, TEvent, TState, TInput>>;\n};\n\nexport type FSMActorLogic<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = ActorLogic<\n FSMSnapshot<TContext, TState, TInput>,\n TEvent,\n TInput,\n any,\n EventObject\n> & {\n id?: string;\n};\n\nconst emptySources = {\n actions: {},\n actors: {},\n guards: {},\n delays: {}\n};\n\nconst emptyExecutableActions: ExecutableActionObject[] = [];\nconst emptyRawActions: AnyAction[] = [];\nconst builtInActionSet = new Set<(...args: any[]) => void>(\n Object.values(builtInActions)\n);\n\nfunction toArray<T>(value: T | T[] | undefined): T[] {\n return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\nfunction resolveContext<TContext extends MachineContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext) | undefined,\n input: TInput\n): TContext {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : (context ?? ({} as TContext));\n}\n\nfunction resolveTransitionContext<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n>(\n context:\n | FSMContextPatch<TContext>\n | FSMContextMapper<TContext, TEvent, TState, TInput>\n | undefined,\n args: FSMArgs<TContext, TEvent, TState, TInput>\n): FSMContextPatch<TContext> | undefined {\n return typeof context === 'function' ? context(args) : context;\n}\n\nfunction resolveInput(\n input: FSMTarget<any>['input'],\n context: MachineContext,\n event: EventObject\n) {\n return typeof input === 'function' ? input({ context, event }) : input;\n}\n\nfunction mergeContextPatch<TContext extends MachineContext>(\n context: TContext,\n patch: FSMContextPatch<TContext>\n): TContext {\n for (const key of Object.keys(patch) as Array<keyof TContext>) {\n if (\n !Object.prototype.hasOwnProperty.call(context, key) ||\n !Object.is(context[key], patch[key])\n ) {\n return { ...context, ...patch };\n }\n }\n\n return context;\n}\n\nfunction createSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput\n>(\n value: TState,\n context: TContext,\n input: TInput | undefined,\n machine: FSMSnapshot<TContext, TState, TInput>['machine'],\n stateInput?: Record<string, unknown>\n): FSMSnapshot<TContext, TState, TInput> {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n value,\n context,\n input,\n children: {},\n timers: {},\n _nextTimerId: 0,\n _stateInput: stateInput,\n machine\n };\n}\n\nfunction cloneSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput\n>(\n snapshot: FSMSnapshot<TContext, TState, TInput>,\n value: TState,\n context: TContext,\n stateInput: Record<string, unknown> | undefined\n): FSMSnapshot<TContext, TState, TInput> {\n return {\n status: snapshot.status,\n output: snapshot.output,\n error: snapshot.error,\n value,\n context,\n input: snapshot.input,\n children: snapshot.children,\n timers: snapshot.timers,\n _nextTimerId: snapshot._nextTimerId,\n // Carried across state changes: dropping these would let a later spawn\n // reuse the id of a still-running child.\n _nextActorIds: snapshot._nextActorIds,\n _stateInput: stateInput,\n machine: snapshot.machine\n } as FSMSnapshot<TContext, TState, TInput>;\n}\n\nfunction stopSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput\n>(\n snapshot: FSMSnapshot<TContext, TState, TInput>\n): FSMSnapshot<TContext, TState, TInput> {\n return {\n status: 'stopped',\n output: undefined,\n error: undefined,\n value: snapshot.value,\n context: snapshot.context,\n input: undefined,\n children: snapshot.children,\n timers: snapshot.timers,\n _nextTimerId: snapshot._nextTimerId,\n _nextActorIds: snapshot._nextActorIds,\n _stateInput: snapshot._stateInput,\n machine: snapshot.machine\n } as FSMSnapshot<TContext, TState, TInput>;\n}\n\nfunction assertNoStringTransitions(\n config: FSMConfig<any, any, string, any>\n): void {\n for (const [stateKey, stateConfig] of Object.entries(config.states)) {\n for (const [eventType, transitionConfig] of Object.entries(\n stateConfig.on ?? {}\n )) {\n for (const transition of toArray(transitionConfig)) {\n if (typeof transition === 'string') {\n const target = transition as string;\n throw new Error(\n `Invalid transition for \"${stateKey}.${eventType}\": use { target: \"${target}\" } instead of a string target.`\n );\n }\n }\n }\n }\n}\n\nfunction resolveSimpleEnqueuedActions(\n rawActions: AnyAction[]\n): ExecutableActionObject[] | undefined {\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of rawActions) {\n if (\n !action ||\n typeof action !== 'object' ||\n !('action' in action) ||\n typeof action.action !== 'function' ||\n builtInActionSet.has(action.action) ||\n '_special' in action.action\n ) {\n return undefined;\n }\n\n executableActions.push({\n kind: 'action',\n type: action.action.name || '(anonymous)',\n params: undefined,\n args: action.args,\n action: action.action,\n exec() {\n return this.action?.(...this.args);\n }\n });\n }\n\n return executableActions;\n}\n\nexport function createFSM<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n>(\n config: FSMConfig<TContext, TEvent, string, TInput>\n): FSMActorLogic<TContext, TEvent, string, TInput> {\n const machine = {\n id: config.id ?? '(fsm)',\n sources: emptySources\n };\n assertNoStringTransitions(config);\n\n const runActions = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: EventObject,\n actorScope: AnyActorScope,\n rawActions: AnyAction[] | undefined\n ): [FSMSnapshot<TContext, string, TInput>, ExecutableActionObject[]] => {\n if (!rawActions?.length) {\n return [snapshot, emptyExecutableActions];\n }\n const simpleExecutableActions = resolveSimpleEnqueuedActions(rawActions);\n if (simpleExecutableActions) {\n return [snapshot, simpleExecutableActions];\n }\n return resolveActionsWithContext(\n snapshot as any,\n event as AnyEventObject,\n actorScope,\n rawActions\n ) as any;\n };\n\n const runStateActions = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: EventObject,\n actorScope: AnyActorScope,\n actionsConfig: FSMStateConfig<TContext, TEvent, string, TInput>['entry'],\n stateInput: Record<string, unknown> | undefined,\n internalQueue: EventObject[]\n ): [FSMSnapshot<TContext, string, TInput>, ExecutableActionObject[]] => {\n if (!actionsConfig) {\n return [snapshot, emptyExecutableActions];\n }\n\n const actions: AnyAction[] = [];\n const enq = createTransitionEnqueue(\n actorScope,\n actions,\n internalQueue,\n true\n );\n let context: TContext | undefined;\n const actionCount = Array.isArray(actionsConfig) ? actionsConfig.length : 1;\n\n for (let i = 0; i < actionCount; i++) {\n const action = Array.isArray(actionsConfig)\n ? actionsConfig[i]\n : actionsConfig;\n const result = action(\n withActorScope(\n {\n context: context ?? snapshot.context,\n event: event as TEvent,\n input: stateInput as any,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n ),\n enq\n );\n if (result?.context !== undefined) {\n const currentContext = context ?? snapshot.context;\n const nextContext = mergeContextPatch(currentContext, result.context);\n if (nextContext !== currentContext) {\n context = nextContext;\n }\n }\n }\n\n const nextSnapshot =\n context !== undefined\n ? cloneSnapshot(snapshot, snapshot.value, context, snapshot._stateInput)\n : snapshot;\n return runActions(nextSnapshot, event, actorScope, actions);\n };\n\n const selectTransition = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: TEvent,\n actorScope: AnyActorScope,\n internalQueue: EventObject[]\n ) => {\n const state = config.states[snapshot.value];\n const transitionsConfig:\n | FSMTransition<TContext, TEvent, string, TInput>\n | Array<FSMTransition<TContext, TEvent, string, TInput>>\n | undefined = state?.on?.[event.type];\n\n if (!transitionsConfig) {\n return undefined;\n }\n\n const transitionCount = Array.isArray(transitionsConfig)\n ? transitionsConfig.length\n : 1;\n\n for (let i = 0; i < transitionCount; i++) {\n const transition = Array.isArray(transitionsConfig)\n ? transitionsConfig[i]\n : transitionsConfig;\n const args = withActorScope(\n {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n );\n\n if (typeof transition === 'function') {\n const actions: AnyAction[] = [];\n const enq = createTransitionEnqueue(\n actorScope,\n actions,\n internalQueue,\n true\n );\n const result = transition(args, enq);\n if (!result) {\n if (actions.length) {\n return { actions };\n }\n continue;\n }\n return {\n target: result.target,\n context: result.context,\n input: result.input,\n actions\n };\n }\n\n if (\n 'guard' in transition &&\n transition.guard &&\n !transition.guard(args)\n ) {\n continue;\n }\n\n return {\n target: transition.target,\n context: resolveTransitionContext(transition.context, args),\n input: transition.input,\n actions:\n 'actions' in transition && transition.actions\n ? toArray(transition.actions as any)\n : emptyRawActions\n };\n }\n\n return undefined;\n };\n\n const transitionCore = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n FSMSnapshot<TContext, string, TInput>,\n TEvent,\n any,\n EventObject\n >\n ): [FSMSnapshot<TContext, string, TInput>, ExecutableActionObject[]] => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n if (event.type === XSTATE_STOP) {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const id of Object.keys(snapshot.timers)) {\n enqueue.cancel(id);\n }\n const [withoutTimers, cancelEffects] = resolveActionsWithContext(\n snapshot as any,\n event,\n actorScope,\n actions\n );\n return [stopSnapshot(withoutTimers as any), cancelEffects] as any;\n }\n if (event.type === XSTATE_TIMER) {\n const timer = snapshot.timers[(event as any).id];\n if (!timer) {\n return [snapshot, emptyExecutableActions];\n }\n const timers = { ...snapshot.timers };\n delete timers[timer.id];\n const nextSnapshot = { ...snapshot, timers };\n if (timer.type === '@xstate.raise') {\n return transitionCore(nextSnapshot, timer.event as TEvent, actorScope);\n }\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n return [\n nextSnapshot,\n [createSendToEffect(actorScope, target, timer.event)]\n ];\n }\n\n const stateConfig = config.states[snapshot.value];\n const directTransition = stateConfig?.on?.[event.type];\n if (!directTransition) {\n return [snapshot, emptyExecutableActions];\n }\n\n if (\n !Array.isArray(directTransition) &&\n typeof directTransition !== 'function' &&\n !('guard' in directTransition) &&\n !('actions' in directTransition && directTransition.actions) &&\n typeof directTransition.input !== 'function'\n ) {\n const target = directTransition.target ?? snapshot.value;\n const stateChanged = target !== snapshot.value;\n if (stateChanged && (stateConfig.exit || config.states[target]?.entry)) {\n // Exit/entry actions need the general path.\n } else {\n const hasContext = directTransition.context !== undefined;\n const hasInput = directTransition.input !== undefined;\n const resolvedContext = !isLazyActorScope(actorScope)\n ? resolveTransitionContext(directTransition.context, {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: snapshot.children\n })\n : typeof directTransition.context === 'function'\n ? directTransition.context(\n withActorScope(\n {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n )\n )\n : directTransition.context;\n const context =\n hasContext && resolvedContext\n ? mergeContextPatch(snapshot.context, resolvedContext)\n : snapshot.context;\n if (\n !stateChanged &&\n context === snapshot.context &&\n !hasInput &&\n snapshot._stateInput === undefined\n ) {\n return [snapshot, emptyExecutableActions];\n }\n return [\n cloneSnapshot(\n snapshot,\n target,\n context,\n hasInput\n ? resolveInput(directTransition.input, context, event)\n : undefined\n ),\n emptyExecutableActions\n ];\n }\n }\n if (\n typeof directTransition === 'function' &&\n directTransition.length < 2 &&\n !stateConfig?.exit\n ) {\n const result = directTransition(\n withActorScope(\n {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n ),\n undefined as any\n );\n if (result) {\n const target = result.target ?? snapshot.value;\n if (!config.states[target]?.entry) {\n const hasContext = result.context !== undefined;\n const hasInput = result.input !== undefined;\n const context =\n hasContext && result.context\n ? mergeContextPatch(snapshot.context, result.context)\n : snapshot.context;\n if (\n target === snapshot.value &&\n context === snapshot.context &&\n !hasInput &&\n snapshot._stateInput === undefined\n ) {\n return [snapshot, emptyExecutableActions];\n }\n return [\n cloneSnapshot(\n snapshot,\n target,\n context,\n hasInput ? resolveInput(result.input, context, event) : undefined\n ),\n emptyExecutableActions\n ];\n }\n }\n }\n\n let nextSnapshot: FSMSnapshot<TContext, string, TInput> = snapshot;\n const executableActions: ExecutableActionObject[] = [];\n const internalQueue: EventObject[] = [event];\n let iterations = 0;\n\n while (internalQueue.length) {\n if (++iterations > 1000) {\n throw new Error('FSM microstep count exceeded 1000');\n }\n const nextEvent = internalQueue.shift() as TEvent;\n const selected = selectTransition(\n nextSnapshot,\n nextEvent,\n actorScope,\n internalQueue\n );\n if (!selected) {\n continue;\n }\n\n const nextValue = selected.target ?? nextSnapshot.value;\n const stateChanged = nextValue !== nextSnapshot.value;\n\n if (stateChanged) {\n const [exited, exitActions] = runStateActions(\n nextSnapshot,\n nextEvent,\n actorScope,\n config.states[nextSnapshot.value]?.exit,\n nextSnapshot._stateInput,\n internalQueue\n );\n nextSnapshot = exited;\n executableActions.push(...exitActions);\n }\n\n let context = nextSnapshot.context;\n if (selected.context !== undefined) {\n context = mergeContextPatch(context, selected.context);\n }\n const hasInput = selected.input !== undefined;\n const stateInput = hasInput\n ? resolveInput(selected.input, context, nextEvent)\n : undefined;\n if (\n stateChanged ||\n context !== nextSnapshot.context ||\n hasInput ||\n nextSnapshot._stateInput !== undefined\n ) {\n nextSnapshot = cloneSnapshot(\n nextSnapshot,\n nextValue,\n context,\n stateInput\n );\n }\n\n const [afterTransition, transitionActions] = runActions(\n nextSnapshot,\n nextEvent,\n actorScope,\n selected.actions\n );\n nextSnapshot = afterTransition;\n executableActions.push(...transitionActions);\n\n if (stateChanged) {\n const [entered, entryActions] = runStateActions(\n nextSnapshot,\n nextEvent,\n actorScope,\n config.states[nextValue]?.entry,\n stateInput,\n internalQueue\n );\n nextSnapshot = entered;\n executableActions.push(...entryActions);\n }\n }\n\n return [nextSnapshot, executableActions];\n };\n\n const transition = ((...args: Parameters<typeof transitionCore>) => {\n beginSpawnAllocation(args[2]);\n const [nextSnapshot, effects] = transitionCore(...args);\n return finalizeTransitionResult(args[2], args[0], [\n nextSnapshot,\n [...effects, ...deriveDeferredStarts(effects)]\n ]);\n }) as FSMActorLogic<TContext, TEvent, string, TInput>['transition'];\n\n const logic: FSMActorLogic<TContext, TEvent, string, TInput> = {\n id: config.id,\n config,\n transition,\n initialTransition: (input, actorScope) => {\n beginSpawnAllocation(actorScope);\n const context = resolveContext(config.context, input);\n const snapshot = createSnapshot(\n config.initial,\n context,\n input,\n machine as any\n );\n const internalQueue: EventObject[] = [];\n let [nextSnapshot, actions] = runStateActions(\n snapshot,\n { type: XSTATE_INIT },\n actorScope,\n config.states[config.initial]?.entry,\n undefined,\n internalQueue\n );\n if (!actions.length) {\n actions = [];\n }\n while (internalQueue.length) {\n const [raisedSnapshot, raisedActions] = transitionCore(\n nextSnapshot,\n internalQueue.shift()! as TEvent,\n actorScope\n );\n nextSnapshot = raisedSnapshot;\n actions.push(...raisedActions);\n }\n return finalizeTransitionResult(actorScope, undefined, [\n nextSnapshot,\n [...actions, ...deriveDeferredStarts(actions)]\n ]);\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: ({ machine: _, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot) => ({\n ...(snapshot as FSMSnapshot<TContext, string, TInput>),\n machine: machine as any\n })\n };\n\n return logic;\n}\n","import {\n Action,\n AnyActorLogic,\n AnyEventObject,\n AnyStateMachine,\n EventObject,\n MachineContext,\n MetaObject\n} from './types';\nimport { createMachine } from './createMachine';\nimport { parseDelayToMilliseconds } from './delay';\n\nfunction delayToMs(delay: string | number): number {\n const parsedDelay = parseDelayToMilliseconds(delay);\n if (parsedDelay !== undefined) return parsedDelay;\n return typeof delay === 'string' ? parseFloat(delay) || 0 : delay;\n}\n\ninterface RaiseJSON {\n type: '@xstate.raise';\n event: EventObject;\n id?: string;\n delay?: number;\n}\n\ninterface CancelJSON {\n type: '@xstate.cancel';\n id: string;\n}\n\ninterface LogJSON {\n type: '@xstate.log';\n args: any[];\n}\n\ninterface EmitJSON {\n type: '@xstate.emit';\n event: AnyEventObject;\n}\n\ninterface AssignJSON {\n type: '@xstate.assign';\n context: MachineContext;\n}\n\ntype BuiltInActionJSON =\n | RaiseJSON\n | CancelJSON\n | LogJSON\n | EmitJSON\n | AssignJSON;\n\ninterface CustomActionJSON {\n type: string;\n params?: unknown;\n}\n\nexport type ActionJSON =\n | CustomActionJSON\n | BuiltInActionJSON\n | ExpressionJSON\n | CodeJSON;\n\nexport interface GuardJSON {\n type: string;\n params?: unknown;\n}\n\ninterface ExpressionJSON {\n '@expr': string;\n '@lang'?: string;\n}\n\ninterface CodeJSON {\n '@code': string;\n '@lang'?: string;\n}\n\ntype ResolvableJSON = ExpressionJSON | CodeJSON;\ntype ConditionJSON = GuardJSON | ResolvableJSON;\n\ninterface ChoiceBranchJSON {\n when?: ConditionJSON;\n target: string | string[];\n context?: MachineContext;\n input?: unknown;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n}\n\nexport interface InvokeJSON {\n id?: string;\n registryKey?: string;\n src: string;\n input?: unknown;\n onDone?: TransitionConfigJSON | TransitionConfigJSON[];\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n onSnapshot?: TransitionConfigJSON | TransitionConfigJSON[];\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n}\n\nexport interface TransitionJSON {\n target?: string | string[];\n matches?: Record<string, unknown>;\n context?: MachineContext;\n actions?: ActionJSON[];\n guard?: ConditionJSON;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n input?: unknown;\n}\n\ntype TransitionConfigJSON = TransitionJSON | ResolvableJSON;\n\nexport interface StateNodeJSON {\n id?: string;\n key?: string;\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history' | 'choice';\n initial?: string;\n states?: Record<string, StateNodeJSON>;\n on?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n after?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n always?: TransitionConfigJSON | TransitionConfigJSON[];\n choice?: ChoiceBranchJSON[] | ResolvableJSON;\n route?:\n | {\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n guard?: string;\n input?: Record<string, unknown>;\n }\n | ResolvableJSON;\n invoke?: InvokeJSON | InvokeJSON[];\n entry?: ActionJSON | ActionJSON[];\n exit?: ActionJSON | ActionJSON[];\n meta?: MetaObject;\n description?: string;\n tags?: string[];\n input?: unknown;\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n history?: 'shallow' | 'deep';\n target?: string | [string, ...string[]];\n output?: unknown;\n context?: Record<string, unknown>;\n}\n\nexport interface MachineJSON extends StateNodeJSON {\n '@exprLang'?: string;\n version?: string;\n actions?: Record<string, ActionJSON | ActionJSON[]>;\n guards?: Record<string, { when: ConditionJSON }>;\n actors?: Record<string, unknown>;\n delays?: Record<\n string,\n number | string | { duration: number | string | ResolvableJSON }\n >;\n schemas?: Record<string, unknown>;\n}\n\ntype EvaluatorSlot =\n | 'context'\n | 'guard'\n | 'choice'\n | 'action'\n | 'actionParams'\n | 'transition'\n | 'input'\n | 'output'\n | 'delay'\n | 'transitionContext'\n | 'unknown';\n\ntype EvaluatorKind = 'expr' | 'code';\n\ninterface EvaluatorArgs {\n source: string;\n kind: EvaluatorKind;\n slot: EvaluatorSlot;\n scope: Record<string, unknown>;\n path: string;\n}\n\ninterface MachineSources {\n actions?: Record<string, (...args: any[]) => unknown>;\n guards?: Record<string, (...args: any[]) => boolean>;\n actors?: Record<string, AnyActorLogic>;\n delays?: Record<string, number | ((...args: any[]) => number)>;\n evaluators?: Record<string, (args: EvaluatorArgs) => unknown>;\n}\n\ntype ProvidedSources = Required<MachineSources>;\n\nfunction isExpression(value: unknown): value is ExpressionJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@expr'] === 'string'\n );\n}\n\nfunction isCode(value: unknown): value is CodeJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@code'] === 'string'\n );\n}\n\nfunction isResolvable(value: unknown): value is ResolvableJSON {\n return isExpression(value) || isCode(value);\n}\n\nfunction isBuiltInActionType(type: string): boolean {\n return type.startsWith('@xstate.');\n}\n\nfunction toPath(parent: string, key: string | number): string {\n return typeof key === 'number' ? `${parent}[${key}]` : `${parent}.${key}`;\n}\n\nfunction extractSerializableDelays(\n delays: MachineJSON['delays'] | undefined\n): Record<string, number> {\n const result: Record<string, number> = {};\n if (!delays) {\n return result;\n }\n for (const key of Object.keys(delays)) {\n const value = delays[key];\n if (typeof value === 'number') {\n result[key] = value;\n } else if (\n value &&\n typeof value === 'object' &&\n typeof value.duration === 'number'\n ) {\n result[key] = value.duration;\n }\n }\n return result;\n}\n\nfunction mergeSources(\n json: MachineJSON,\n sources: MachineSources\n): ProvidedSources {\n return {\n actions: sources.actions ?? {},\n guards: sources.guards ?? {},\n actors: sources.actors ?? {},\n delays: {\n ...extractSerializableDelays(json.delays),\n ...(sources.delays ?? {})\n },\n evaluators: sources.evaluators ?? {}\n };\n}\n\ninterface ExpressionResolver {\n evaluateResolvable: (\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n resolveValue: (\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n makeScope: (\n x: any,\n extra?: Record<string, unknown>\n ) => Record<string, unknown>;\n getDurationConfig: (value: unknown, path: string) => unknown;\n assertResolvable: (value: unknown, path: string) => void;\n}\n\nfunction createExpressionResolver(\n expressionLanguage: string | undefined,\n sources: ProvidedSources\n): ExpressionResolver {\n function getEvaluator(value: ResolvableJSON, path: string) {\n const lang = value['@lang'] ?? expressionLanguage;\n if (!lang) {\n throw new Error(`Missing @exprLang for expression at ${path}`);\n }\n const evaluator = sources.evaluators[lang];\n if (!evaluator) {\n throw new Error(`Missing evaluator for @lang '${lang}' at ${path}`);\n }\n return evaluator;\n }\n\n function evaluateResolvable(\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) {\n const kind = isExpression(value) ? 'expr' : 'code';\n const source = isExpression(value) ? value['@expr'] : value['@code'];\n return getEvaluator(\n value,\n path\n )({\n source,\n kind,\n slot,\n scope,\n path\n });\n }\n\n function resolveValue(\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ): unknown {\n if (isResolvable(value)) {\n return evaluateResolvable(value, slot, scope, path);\n }\n if (Array.isArray(value)) {\n return value.map((item, index) =>\n resolveValue(item, slot, scope, toPath(path, index))\n );\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = resolveValue(\n (value as Record<string, unknown>)[key],\n slot,\n scope,\n toPath(path, key)\n );\n }\n return result;\n }\n\n function makeScope(x: any, extra?: Record<string, unknown>) {\n return {\n context: x.context,\n event: x.event,\n input: x.input,\n self: x.self,\n children: x.children,\n params: x.params,\n ...extra\n };\n }\n\n function getDurationConfig(value: unknown, path: string) {\n if (!isResolvable(value)) {\n return value;\n }\n return (args: any) =>\n delayToMs(\n resolveValue(value, 'delay', makeScope(args), path) as string | number\n );\n }\n\n function assertResolvable(value: unknown, path: string) {\n if (isResolvable(value)) {\n getEvaluator(value, path);\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertResolvable(item, toPath(path, index))\n );\n return;\n }\n if (!value || typeof value !== 'object') {\n return;\n }\n for (const key of Object.keys(value)) {\n assertResolvable(\n (value as Record<string, unknown>)[key],\n toPath(path, key)\n );\n }\n }\n\n return {\n evaluateResolvable,\n resolveValue,\n makeScope,\n getDurationConfig,\n assertResolvable\n };\n}\n\nfunction toActionArray(\n actions: ActionJSON | ActionJSON[] | undefined\n): ActionJSON[] {\n return actions === undefined\n ? []\n : Array.isArray(actions)\n ? actions\n : [actions];\n}\n\nfunction validateChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!Array.isArray(choice)) {\n return;\n }\n choice.forEach((branch, index) => {\n if (branch.when === undefined && index !== choice.length - 1) {\n throw new Error(\n `Choice fallback branch at ${path}[${index}] must be last.`\n );\n }\n });\n}\n\nfunction assertMachineJSON(\n json: MachineJSON,\n resolvedSources: ProvidedSources,\n expressionResolver: ExpressionResolver\n) {\n const { assertResolvable } = expressionResolver;\n\n function assertCondition(condition: ConditionJSON | undefined, path: string) {\n if (!condition) {\n return;\n }\n if (isResolvable(condition)) {\n assertResolvable(condition, path);\n return;\n }\n assertResolvable(condition.params, `${path}.params`);\n if (json.guards?.[condition.type]) {\n assertCondition(\n json.guards[condition.type].when,\n `$.guards.${condition.type}.when`\n );\n return;\n }\n if (\n !resolvedSources.guards[condition.type] &&\n !['xstate.stateIn', 'xstate.not'].includes(condition.type)\n ) {\n throw new Error(`Missing guard source \"${condition.type}\"`);\n }\n }\n\n function assertAction(\n action: ActionJSON,\n path: string,\n stack: string[] = []\n ) {\n if (isResolvable(action)) {\n assertResolvable(action, path);\n return;\n }\n if (!action || typeof action.type !== 'string') {\n throw new Error(`Invalid action at ${path}`);\n }\n assertResolvable((action as CustomActionJSON).params, `${path}.params`);\n if (isBuiltInActionType(action.type)) {\n assertResolvable(action, path);\n return;\n }\n const definition = json.actions?.[action.type];\n if (definition) {\n if (stack.includes(action.type)) {\n throw new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n );\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n definitions.forEach((item, index) =>\n assertAction(\n item,\n `${path}.actions.${action.type}${definitions.length > 1 ? `[${index}]` : ''}`,\n stack.concat(action.type)\n )\n );\n return;\n }\n if (!resolvedSources.actions[action.type]) {\n throw new Error(`Missing action source \"${action.type}\"`);\n }\n }\n\n function assertActions(\n actions: ActionJSON | ActionJSON[] | undefined,\n path: string\n ) {\n toActionArray(actions).forEach((action, index) =>\n assertAction(action, `${path}[${index}]`)\n );\n }\n\n function assertTransition(\n transition: TransitionConfigJSON | TransitionConfigJSON[] | undefined,\n path: string\n ) {\n const transitions = Array.isArray(transition)\n ? transition\n : transition\n ? [transition]\n : [];\n transitions.forEach((t, index) => {\n const transitionPath = Array.isArray(transition)\n ? `${path}[${index}]`\n : path;\n if (isResolvable(t)) {\n assertResolvable(t, transitionPath);\n return;\n }\n assertCondition(t.guard, `${transitionPath}.guard`);\n assertActions(t.actions, `${transitionPath}.actions`);\n assertResolvable(t.context, `${transitionPath}.context`);\n assertResolvable(t.input, `${transitionPath}.input`);\n });\n }\n\n function assertStateNode(node: StateNodeJSON, path: string) {\n if (\n (node.type === 'history' || node.history !== undefined) &&\n !(\n (typeof node.target === 'string' && node.target.trim().length > 0) ||\n (Array.isArray(node.target) &&\n node.target.length > 0 &&\n node.target.every((target) => target.trim().length > 0))\n )\n ) {\n throw new Error(\n `History state at ${path} must declare a non-empty target.`\n );\n }\n assertResolvable(node.context, `${path}.context`);\n assertResolvable(node.input, `${path}.input`);\n assertResolvable(node.output, `${path}.output`);\n assertResolvable(node.timeout, `${path}.timeout`);\n assertActions(node.entry, `${path}.entry`);\n assertActions(node.exit, `${path}.exit`);\n if (node.type === 'choice') {\n if (!node.choice) {\n throw new Error(`Choice state at ${path} must declare choice.`);\n }\n if (Array.isArray(node.choice)) {\n validateChoiceConfig(node.choice, `${path}.choice`);\n node.choice.forEach((branch, index) => {\n assertCondition(branch.when, `${path}.choice[${index}].when`);\n assertResolvable(branch.context, `${path}.choice[${index}].context`);\n assertResolvable(branch.input, `${path}.choice[${index}].input`);\n });\n } else {\n assertResolvable(node.choice, `${path}.choice`);\n }\n }\n if (isResolvable(node.route)) {\n assertResolvable(node.route, `${path}.route`);\n }\n if (node.invoke) {\n const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];\n invokes.forEach((invoke, index) => {\n const invokePath = `${path}.invoke${Array.isArray(node.invoke) ? `[${index}]` : ''}`;\n if (!resolvedSources.actors[invoke.src]) {\n throw new Error(`Missing actor source \"${invoke.src}\"`);\n }\n assertResolvable(invoke.input, `${invokePath}.input`);\n assertResolvable(invoke.timeout, `${invokePath}.timeout`);\n assertTransition(invoke.onDone, `${invokePath}.onDone`);\n assertTransition(invoke.onError, `${invokePath}.onError`);\n assertTransition(invoke.onSnapshot, `${invokePath}.onSnapshot`);\n assertTransition(invoke.onTimeout, `${invokePath}.onTimeout`);\n });\n }\n if (node.on) {\n for (const descriptor of Object.keys(node.on)) {\n assertTransition(node.on[descriptor], `${path}.on.${descriptor}`);\n }\n }\n if (node.after) {\n for (const delay of Object.keys(node.after)) {\n if (\n Number.isNaN(Number(delay)) &&\n parseDelayToMilliseconds(delay) === undefined &&\n !json.delays?.[delay] &&\n !resolvedSources.delays[delay]\n ) {\n throw new Error(`Missing delay source \"${delay}\"`);\n }\n assertTransition(node.after[delay], `${path}.after.${delay}`);\n }\n }\n assertTransition(node.always, `${path}.always`);\n assertTransition(node.onError, `${path}.onError`);\n assertTransition(node.onTimeout, `${path}.onTimeout`);\n if (node.states) {\n for (const key of Object.keys(node.states)) {\n assertStateNode(node.states[key], `${path}.states.${key}`);\n }\n }\n }\n\n if (json.actions) {\n for (const key of Object.keys(json.actions)) {\n const actions = Array.isArray(json.actions[key])\n ? json.actions[key]\n : [json.actions[key]];\n actions.forEach((action, index) =>\n assertAction(\n action,\n `$.actions.${key}${actions.length > 1 ? `[${index}]` : ''}`,\n [key]\n )\n );\n }\n }\n if (json.guards) {\n for (const key of Object.keys(json.guards)) {\n assertCondition(json.guards[key].when, `$.guards.${key}.when`);\n }\n }\n if (json.delays) {\n for (const key of Object.keys(json.delays)) {\n const delay = json.delays[key];\n assertResolvable(\n delay && typeof delay === 'object' && 'duration' in delay\n ? delay.duration\n : delay,\n `$.delays.${key}`\n );\n }\n }\n assertStateNode(json, '$');\n}\n\nexport function createMachineFromConfig(\n json: MachineJSON,\n sources: MachineSources = {}\n): AnyStateMachine {\n const resolvedSources = mergeSources(json, sources);\n const expressionResolver = createExpressionResolver(\n json['@exprLang'],\n resolvedSources\n );\n const { evaluateResolvable, resolveValue, makeScope, getDurationConfig } =\n expressionResolver;\n\n type ResolvedCondition = ((args: any) => boolean) | undefined;\n\n function resolveCondition(\n condition: ConditionJSON | undefined,\n slot: 'guard' | 'choice',\n path: string\n ): ResolvedCondition {\n if (!condition) return undefined;\n if (isResolvable(condition)) {\n return (args: any) =>\n !!evaluateResolvable(condition, slot, makeScope(args), path);\n }\n return (args: any) => {\n const params = resolveValue(\n condition.params,\n slot,\n makeScope(args),\n `${path}.params`\n );\n const declarativeGuard = json.guards?.[condition.type];\n if (declarativeGuard) {\n const guard = resolveCondition(\n declarativeGuard.when,\n 'guard',\n `$.guards.${condition.type}.when`\n );\n return !!guard?.({ ...args, params });\n }\n const guardImpl = args.guards?.[condition.type];\n if (!guardImpl) {\n throw new Error(\n getMissingGuardMessage(condition.type, args.guards ?? {})\n );\n }\n return guardImpl(args, params);\n };\n }\n\n function getMissingGuardMessage(type: string, guards: Record<string, any>) {\n return `Guard '${type}' is not implemented in machine '${json.id ?? '(machine)'}'. Available guards: ${\n Object.keys(guards)\n .map((key) => `'${key}'`)\n .join(', ') || '(none)'\n }.`;\n }\n\n function makeChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!choice) return undefined;\n if (isResolvable(choice)) {\n return (args: any) =>\n evaluateResolvable(choice, 'choice', makeScope(args), path);\n }\n validateChoiceConfig(choice, path);\n return (args: any) => {\n for (let index = 0; index < choice.length; index++) {\n const branch = choice[index];\n const guard = resolveCondition(\n branch.when,\n 'choice',\n `${path}[${index}].when`\n );\n if (!guard || guard(args)) {\n return {\n target: branch.target,\n context: branch.context\n ? resolveValue(\n branch.context,\n 'transitionContext',\n makeScope(args),\n `${path}[${index}].context`\n )\n : undefined,\n input:\n branch.input !== undefined\n ? resolveValue(\n branch.input,\n 'input',\n makeScope(args),\n `${path}[${index}].input`\n )\n : undefined,\n description: branch.description,\n reenter: branch.reenter,\n meta: branch.meta\n };\n }\n }\n throw new Error(`Choice state at ${path} did not match any branch.`);\n };\n }\n\n function resolveRouteConfig(route: StateNodeJSON['route'], path: string) {\n if (!route || typeof route === 'function') return route;\n if (isResolvable(route)) {\n return (args: any) =>\n evaluateResolvable(route, 'transition', makeScope(args), path);\n }\n const { guard, ...routeConfig } = route;\n if (!guard) return routeConfig;\n const resolvedGuard = resolveCondition({ type: guard }, 'guard', path);\n return (args: any) => (resolvedGuard!(args) ? routeConfig : undefined);\n }\n\n function executeActions(\n actions: ActionJSON[],\n x: any,\n enq: any,\n stack: string[] = []\n ) {\n let context: MachineContext | undefined;\n for (const action of actions) {\n if (isResolvable(action)) {\n const result = evaluateResolvable(\n action,\n 'action',\n makeScope(x, { params: x.params, enq }),\n '$.actions'\n );\n if (\n result &&\n typeof result === 'object' &&\n 'context' in result &&\n (result as any).context\n ) {\n context ??= {};\n Object.assign(context, (result as any).context);\n }\n continue;\n }\n if (isBuiltInActionJSON(action)) {\n switch (action.type) {\n case '@xstate.raise':\n enq.raise(\n resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n ),\n { id: action.id, delay: action.delay }\n );\n break;\n case '@xstate.cancel':\n enq.cancel(action.id);\n break;\n case '@xstate.log':\n enq.log(...action.args);\n break;\n case '@xstate.emit':\n enq.emit(\n resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n )\n );\n break;\n case '@xstate.assign':\n context ??= {};\n Object.assign(\n context,\n resolveValue(\n action.context,\n 'transitionContext',\n makeScope(x, { params: x.params }),\n '$.actions.context'\n )\n );\n break;\n }\n continue;\n }\n const params = resolveValue(\n action.params,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.params'\n );\n const definition = json.actions?.[action.type];\n if (!definition) {\n enq(x.actions[action.type], params);\n continue;\n }\n if (stack.includes(action.type)) {\n throw new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n );\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n const result = executeActions(\n definitions,\n { ...x, context: { ...x.context, ...context }, params },\n enq,\n stack.concat(action.type)\n );\n if (result.context) context = result.context;\n }\n return { context: context ? { ...x.context, ...context } : undefined };\n }\n\n function iterActions(actions: ActionJSON | ActionJSON[]) {\n const actionArray = toActionArray(actions);\n return ((x: any, enq: any) =>\n executeActions(actionArray, x, enq)) as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n }\n\n function getTransitionConfig(\n transition: TransitionConfigJSON | TransitionConfigJSON[]\n ): any {\n const transitions = Array.isArray(transition) ? transition : [transition];\n return transitions.map((item, index) => {\n if (isResolvable(item)) {\n return (x: any, enq: any) =>\n evaluateResolvable(\n item,\n 'transition',\n makeScope(x, { enq }),\n `$.transition${transitions.length > 1 ? `[${index}]` : ''}`\n );\n }\n const context = item.context\n ? (x: any) =>\n resolveValue(\n item.context,\n 'transitionContext',\n makeScope(x),\n '$.transition.context'\n ) as MachineContext\n : undefined;\n const input =\n item.input !== undefined\n ? (x: any) =>\n resolveValue(\n item.input,\n 'input',\n makeScope(x),\n '$.transition.input'\n )\n : undefined;\n const dynamic = !!context || !!item.actions?.length;\n return {\n matches: item.matches,\n target: dynamic ? undefined : item.target,\n to: dynamic\n ? (x: any, enq: any) => {\n const resolvedContext = context?.(x);\n const result = item.actions?.length\n ? executeActions(\n item.actions,\n resolvedContext\n ? { ...x, context: { ...x.context, ...resolvedContext } }\n : x,\n enq\n )\n : undefined;\n return {\n target: item.target,\n context: result?.context ?? resolvedContext,\n reenter: item.reenter\n };\n }\n : undefined,\n guard: resolveCondition(item.guard, 'guard', '$.transition.guard'),\n description: item.description,\n reenter: item.reenter,\n meta: item.meta,\n input\n };\n });\n }\n\n function iterInvokeConfigs(invokes: InvokeJSON | InvokeJSON[]): any {\n return (Array.isArray(invokes) ? invokes : [invokes]).map((inv) => ({\n src: resolvedSources.actors[inv.src] ?? inv.src,\n id: inv.id,\n registryKey: inv.registryKey,\n input:\n inv.input !== undefined\n ? (args: any) =>\n resolveValue(\n inv.input,\n 'input',\n makeScope(args),\n '$.invoke.input'\n )\n : undefined,\n onDone: inv.onDone ? getTransitionConfig(inv.onDone) : undefined,\n onError: inv.onError ? getTransitionConfig(inv.onError) : undefined,\n onSnapshot: inv.onSnapshot\n ? getTransitionConfig(inv.onSnapshot)\n : undefined,\n timeout: getDurationConfig(inv.timeout, '$.invoke.timeout'),\n onTimeout: inv.onTimeout ? getTransitionConfig(inv.onTimeout) : undefined\n }));\n }\n\n function iterNode(node: StateNodeJSON, nodeKey?: string): any {\n return {\n id: node.id,\n initial: node.initial,\n type: node.type,\n history: node.history,\n target: node.target,\n description: node.description,\n tags: node.tags,\n input: node.input,\n timeout: getDurationConfig(node.timeout, `$.states.${nodeKey}.timeout`),\n states: node.states\n ? Object.fromEntries(\n Object.entries(node.states).map(([key, value]) => [\n key,\n iterNode(value, key)\n ])\n )\n : undefined,\n on: node.on\n ? Object.fromEntries(\n Object.entries(node.on).map(([key, value]) => [\n key,\n getTransitionConfig(value)\n ])\n )\n : undefined,\n always: node.always ? getTransitionConfig(node.always) : undefined,\n onError: node.onError ? getTransitionConfig(node.onError) : undefined,\n choice: makeChoiceConfig(node.choice, `$.states.${nodeKey}.choice`),\n route: resolveRouteConfig(node.route, `$.states.${nodeKey}.route`),\n after: node.after\n ? Object.fromEntries(\n Object.entries(node.after).map(([key, value]) => [\n key,\n getTransitionConfig(value)\n ])\n )\n : undefined,\n onTimeout: node.onTimeout\n ? getTransitionConfig(node.onTimeout)\n : undefined,\n entry: node.entry ? iterActions(node.entry) : undefined,\n exit: node.exit ? iterActions(node.exit) : undefined,\n invoke: node.invoke ? iterInvokeConfigs(node.invoke) : undefined,\n meta: node.meta,\n output: isResolvable(node.output)\n ? ({ context, event, self }: any) =>\n evaluateResolvable(\n node.output as ResolvableJSON,\n 'output',\n { context, event, self },\n `$.states.${nodeKey}.output`\n )\n : node.output\n };\n }\n\n if (json.delays) {\n for (const [key, delay] of Object.entries(json.delays)) {\n if (typeof delay === 'number') resolvedSources.delays[key] = delay;\n else if (typeof delay === 'string')\n resolvedSources.delays[key] = delayToMs(delay);\n else if (delay && typeof delay === 'object') {\n resolvedSources.delays[key] = (args: any) =>\n delayToMs(\n resolveValue(\n delay.duration,\n 'delay',\n makeScope(args),\n `$.delays.${key}.duration`\n ) as string | number\n );\n }\n }\n }\n\n assertMachineJSON(json, resolvedSources, expressionResolver);\n const contextConfig = json.context\n ? {\n context: (args: any) =>\n resolveValue(\n json.context,\n 'context',\n args,\n '$.context'\n ) as MachineContext\n }\n : {};\n const machine = createMachine({\n ...iterNode(json),\n ...contextConfig,\n version: json.version\n }) as unknown as AnyStateMachine;\n const provided = machine.provide({\n actions: resolvedSources.actions,\n actors: resolvedSources.actors,\n guards: {\n 'xstate.stateIn': (args: any, params: any) => {\n const stateId = params?.stateId as string;\n const snapshot = args._snapshot;\n return (\n !!stateId &&\n !!snapshot?.nodes?.some(\n (node: any) => node.id === stateId.replace(/^#/, '')\n )\n );\n },\n 'xstate.not': (args: any, params: any) => {\n const inner = params?.guard;\n const impl = inner && args.guards?.[inner.type];\n if (!impl)\n throw new Error(\n `Guard '${inner?.type}' referenced by 'xstate.not' is not implemented.`\n );\n return !impl(args, inner.params);\n },\n ...resolvedSources.guards\n },\n delays: resolvedSources.delays\n });\n (provided as any)._json = json;\n return provided;\n}\n\nfunction isBuiltInActionJSON(action: ActionJSON): action is BuiltInActionJSON {\n return !isResolvable(action) && action.type.startsWith('@xstate.');\n}\n","/**\n * Machine-definition serialization.\n *\n * `machineConfigToJSON` converts a machine config into a JSON-safe structure\n * (the `MachineJSON` shape accepted by `createMachineFromConfig`). The boundary\n * between serializable structure and runtime sources is explicit: functions are\n * represented as `@code` source objects, while actor logic, runtime schemas,\n * and other non-data runtime values are omitted.\n */\n\nimport type { AnyStateMachine } from './types.ts';\n\nexport interface CodeExpression {\n '@code': string;\n '@lang': 'ts';\n}\n\n/**\n * Returns the JSON-serializable definition of a machine.\n *\n * Inline functions are represented as `{ \"@code\": string, \"@lang\": \"ts\" }`. A\n * machine created via `createMachineFromConfig` returns its original JSON\n * config (lossless round-trip):\n *\n * ```ts\n * import { serializeMachine, createMachineFromConfig } from 'xstate';\n *\n * const json = serializeMachine(machine);\n * const revived = createMachineFromConfig(\n * JSON.parse(JSON.stringify(json))\n * );\n * ```\n */\nexport function serializeMachine(\n machine: AnyStateMachine\n): Record<string, unknown> {\n return (machine as any)._json ?? machineConfigToJSON(machine.config);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction codeExpression(fn: Function): CodeExpression {\n return {\n '@code': fn.toString(),\n '@lang': 'ts'\n };\n}\n\nfunction isActorLogic(value: unknown): value is { id?: string } {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any).transition === 'function' &&\n typeof (value as any).getInitialSnapshot === 'function'\n );\n}\n\nfunction isRuntimeSchema(value: unknown): boolean {\n return !!value && typeof value === 'object' && '~standard' in value;\n}\n\n/** JSON-safe deep copy of a plain value; functions become code expressions. */\nfunction valueToJSON(value: unknown): unknown {\n if (typeof value === 'function') {\n return codeExpression(value);\n }\n if (value === null || typeof value !== 'object') {\n return typeof value === 'bigint' || typeof value === 'symbol'\n ? undefined\n : value;\n }\n if (isActorLogic(value)) {\n return undefined;\n }\n if (isRuntimeSchema(value)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map(valueToJSON).filter((item) => item !== undefined);\n }\n if (value.constructor !== Object && value.constructor !== undefined) {\n // Class instances (actor logic, schemas, dates, ...) are not portable.\n return undefined;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const v = (value as Record<string, unknown>)[key];\n if (v !== undefined) {\n const jsonValue = valueToJSON(v);\n if (jsonValue !== undefined) {\n result[key] = jsonValue;\n }\n }\n }\n return result;\n}\n\nfunction invokeToJSON(invoke: unknown): unknown {\n if (Array.isArray(invoke)) {\n const values = invoke\n .map(invokeToJSON)\n .filter((value) => value !== undefined);\n return values.length ? values : undefined;\n }\n const def = invoke as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(def)) {\n const value = def[key];\n if (value === undefined) {\n continue;\n }\n result[key] =\n key === 'src' && typeof value !== 'string'\n ? (value as { id?: string }).id\n : valueToJSON(value);\n if (result[key] === undefined) {\n delete result[key];\n }\n }\n return result.src === undefined ? undefined : result;\n}\n\nfunction sourcesToJSON(\n map: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (!map) {\n return undefined;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(map)) {\n const value = map[key];\n if (typeof value === 'function') {\n result[key] = undefined;\n } else {\n result[key] = valueToJSON(value);\n }\n if (result[key] === undefined) {\n delete result[key];\n }\n }\n return result;\n}\n\nfunction stateNodeConfigToJSON(\n config: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const key of Object.keys(config)) {\n if (key === 'states' || key === 'invoke') {\n continue;\n }\n const value = config[key];\n if (value !== undefined) {\n result[key] = valueToJSON(value);\n }\n }\n if (config.invoke !== undefined) {\n const invoke = invokeToJSON(config.invoke);\n if (invoke !== undefined) {\n result.invoke = invoke;\n }\n }\n if (config.states) {\n const states: Record<string, unknown> = {};\n for (const key of Object.keys(config.states as object)) {\n states[key] = stateNodeConfigToJSON(\n (config.states as Record<string, Record<string, unknown>>)[key]\n );\n }\n result.states = states;\n }\n\n return result;\n}\n\n/**\n * Converts a machine config (as passed to `createMachine`) to its JSON-safe\n * definition.\n */\nexport function machineConfigToJSON(\n config: Record<string, unknown>\n): Record<string, unknown> {\n const result = stateNodeConfigToJSON(config);\n\n if (config.internalEvents !== undefined) {\n result.internalEvents = valueToJSON(config.internalEvents);\n }\n if (config.schemas) {\n const schemas: Record<string, unknown> = {};\n for (const key of Object.keys(config.schemas as object)) {\n const value = (config.schemas as Record<string, unknown>)[key];\n if (value && typeof value === 'object' && !('~standard' in value)) {\n // Map-form schemas (events/emitted): preserve event-type keys.\n schemas[key] = sourcesToJSON(value as Record<string, unknown>);\n } else {\n schemas[key] = valueToJSON(value);\n }\n if (schemas[key] === undefined) {\n delete schemas[key];\n }\n }\n result.schemas = schemas;\n }\n for (const key of ['actions', 'guards', 'actors', 'delays'] as const) {\n if (config[key]) {\n const value = sourcesToJSON(config[key] as Record<string, unknown>);\n if (value && Object.keys(value).length) {\n result[key] = value;\n } else {\n delete result[key];\n }\n }\n }\n\n return result;\n}\n","import type { StandardSchemaV1 } from './schema.types.ts';\nimport type {\n MachineEventSchema,\n MachineSnapshotSchema,\n MachineVersionDescriptor\n} from './machineVersion.types.ts';\nexport type {\n MachineEventSchema,\n MachineSnapshotSchema,\n MachineVersionDescriptor,\n PersistedMachineSnapshot\n} from './machineVersion.types.ts';\nimport type {\n AnyStateMachine,\n ContextFrom,\n EventFrom,\n EventObject,\n PersistedSnapshotFor,\n Snapshot\n} from './types.ts';\n\nexport type PersistedMachineIdentity<\n TMachine extends AnyStateMachine = AnyStateMachine\n> = {\n id: TMachine['id'];\n version: NonNullable<TMachine['version']>;\n};\n\ntype VersionedStateMachine = AnyStateMachine & {\n version: string;\n snapshotSchema: MachineSnapshotSchema;\n eventSchema: MachineEventSchema;\n};\n\ntype VersionEntry = MachineVersionDescriptor;\n\nexport type PersistedSnapshotFrom<TMachine extends AnyStateMachine> =\n Snapshot<unknown> &\n PersistedSnapshotFor<TMachine> & {\n context: ContextFrom<TMachine>;\n machine: PersistedMachineIdentity<TMachine>;\n [key: string]: unknown;\n };\n\nexport type PersistedSnapshotDataFrom<TMachine extends AnyStateMachine> =\n Snapshot<unknown> & {\n context: ContextFrom<TMachine>;\n [key: string]: unknown;\n };\n\nexport type ParsedPersistedSnapshot<TEntries extends readonly VersionEntry[]> =\n {\n [K in keyof TEntries]: TEntries[K] extends VersionEntry\n ? TEntries[K] extends VersionedStateMachine\n ? {\n source: TEntries[K];\n machine: TEntries[K];\n snapshot: PersistedSnapshotFromEntry<TEntries[K]>;\n }\n : {\n source: TEntries[K];\n snapshot: PersistedSnapshotFromEntry<TEntries[K]>;\n }\n : never;\n }[number];\n\nexport type MachineVersionsOptions<TEntries extends readonly VersionEntry[]> = {\n unversioned?: SnapshotSourceVersion<TEntries>;\n};\n\ntype MaybePromise<T> = T | PromiseLike<T>;\n\ntype MachineVersion<TEntries extends readonly VersionEntry[]> = Extract<\n TEntries[number],\n VersionedStateMachine\n>['version'];\n\ntype SnapshotSourceVersion<TEntries extends readonly VersionEntry[]> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { snapshotSchema: MachineSnapshotSchema }\n ? TEntries[K]['version']\n : never;\n}[number];\n\ntype EventSourceVersion<TEntries extends readonly VersionEntry[]> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { eventSchema: MachineEventSchema }\n ? TEntries[K]['version']\n : never;\n}[number];\n\ntype MachineForVersion<\n TEntries extends readonly VersionEntry[],\n TVersion extends string\n> = {\n [K in keyof TEntries]: TEntries[K] extends VersionedStateMachine\n ? TEntries[K]['version'] extends TVersion\n ? TEntries[K]\n : never\n : never;\n}[number];\n\ntype SnapshotEntryForVersion<\n TEntries extends readonly VersionEntry[],\n TVersion extends string\n> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { snapshotSchema: MachineSnapshotSchema }\n ? TEntries[K]['version'] extends TVersion\n ? TEntries[K]\n : never\n : never;\n}[number];\n\ntype EventEntryForVersion<\n TEntries extends readonly VersionEntry[],\n TVersion extends string\n> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { eventSchema: MachineEventSchema }\n ? TEntries[K]['version'] extends TVersion\n ? TEntries[K]\n : never\n : never;\n}[number];\n\ntype PersistedSnapshotFromEntry<TEntry extends VersionEntry> = TEntry extends {\n snapshotSchema: infer TSchema extends MachineSnapshotSchema;\n}\n ? StandardSchemaV1.InferOutput<TSchema>\n : TEntry extends VersionedStateMachine\n ? PersistedSnapshotFrom<TEntry>\n : never;\n\ntype EventFromEntry<TEntry extends VersionEntry> = TEntry extends {\n eventSchema: infer TSchema extends MachineEventSchema;\n}\n ? StandardSchemaV1.InferOutput<TSchema>\n : TEntry extends VersionedStateMachine\n ? EventFrom<TEntry>\n : never;\n\nexport type PersistedSnapshotSource = {\n id?: string;\n version?: string;\n};\n\nexport type SnapshotMigrationHandlers<\n TEntries extends readonly VersionEntry[],\n TTarget extends VersionedStateMachine\n> = {\n [TVersion in Exclude<SnapshotSourceVersion<TEntries>, TTarget['version']>]?: (\n snapshot: PersistedSnapshotFromEntry<\n SnapshotEntryForVersion<TEntries, TVersion>\n >\n ) => MaybePromise<PersistedSnapshotDataFrom<TTarget>>;\n} & {\n '*'?: (\n snapshot: unknown,\n source: PersistedSnapshotSource\n ) => MaybePromise<PersistedSnapshotDataFrom<TTarget>>;\n};\n\nexport type MigrateSnapshotOptions<\n TEntries extends readonly VersionEntry[],\n TTargetVersion extends MachineVersion<TEntries>\n> = {\n to: TTargetVersion;\n migrations: SnapshotMigrationHandlers<\n TEntries,\n MachineForVersion<TEntries, TTargetVersion>\n >;\n};\n\nexport type EventHistorySource = {\n id?: string;\n version?: string;\n};\n\nexport type EventAdapterHandlers<\n TEntries extends readonly VersionEntry[],\n TTarget extends VersionedStateMachine\n> = {\n [TVersion in Exclude<EventSourceVersion<TEntries>, TTarget['version']>]?: (\n events: readonly EventFromEntry<EventEntryForVersion<TEntries, TVersion>>[]\n ) => MaybePromise<readonly EventFrom<TTarget>[]>;\n} & {\n '*'?: (\n events: readonly unknown[],\n source: EventHistorySource\n ) => MaybePromise<readonly EventFrom<TTarget>[]>;\n};\n\nexport type AdaptEventsOptions<\n TEntries extends readonly VersionEntry[],\n TTargetVersion extends MachineVersion<TEntries>\n> = {\n from: EventHistorySource;\n to: TTargetVersion;\n adapters: EventAdapterHandlers<\n TEntries,\n MachineForVersion<TEntries, TTargetVersion>\n >;\n};\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nfunction isVersionedStateMachine(\n entry: VersionEntry\n): entry is VersionedStateMachine {\n return (\n 'transition' in entry &&\n typeof (entry as VersionedStateMachine).transition === 'function'\n );\n}\n\nfunction hasSnapshotSchema(\n entry: VersionEntry\n): entry is MachineVersionDescriptor & {\n snapshotSchema: MachineSnapshotSchema;\n} {\n return 'snapshotSchema' in entry && entry.snapshotSchema !== undefined;\n}\n\nfunction hasEventSchema(\n entry: VersionEntry\n): entry is MachineVersionDescriptor & { eventSchema: MachineEventSchema } {\n return 'eventSchema' in entry && entry.eventSchema !== undefined;\n}\n\nfunction getSnapshotSource(\n raw: unknown,\n defaultId: string\n): PersistedSnapshotSource {\n if (!isObject(raw)) {\n return {};\n }\n if (isObject(raw.machine)) {\n return {\n id: typeof raw.machine.id === 'string' ? raw.machine.id : undefined,\n version:\n typeof raw.machine.version === 'string'\n ? raw.machine.version\n : undefined\n };\n }\n return {\n id: typeof raw.version === 'string' ? defaultId : undefined,\n version: typeof raw.version === 'string' ? raw.version : undefined\n };\n}\n\nasync function validate(\n schema: StandardSchemaV1 | undefined,\n value: unknown,\n description: string\n): Promise<unknown> {\n if (!schema) {\n return value;\n }\n const result = await schema['~standard'].validate(value);\n if (result.issues) {\n throw new Error(`Invalid ${description}: ${result.issues[0]?.message}`);\n }\n return result.value;\n}\n\nasync function finalizeSnapshot<TTarget extends VersionedStateMachine>(\n snapshot: PersistedSnapshotDataFrom<TTarget>,\n target: TTarget\n): Promise<PersistedSnapshotFrom<TTarget>> {\n return (await validate(\n target.snapshotSchema,\n {\n ...snapshot,\n machine: { id: target.id, version: target.version },\n version: target.version\n },\n `snapshot for machine '${target.id}' version '${target.version}'`\n )) as PersistedSnapshotFrom<TTarget>;\n}\n\nasync function validateEvents<\n TSource extends MachineVersionDescriptor & {\n eventSchema: MachineEventSchema;\n }\n>(\n events: readonly unknown[],\n source: TSource\n): Promise<EventFromEntry<TSource>[]> {\n return Promise.all(\n events.map(async (event, index) => {\n const result = await source.eventSchema['~standard'].validate(event);\n if (result.issues) {\n const message = result.issues[0]?.message;\n if (message?.startsWith('Unknown event ')) {\n throw new Error(message);\n }\n const type = isObject(event) ? event.type : undefined;\n throw new Error(\n typeof type === 'string'\n ? `Invalid event '${type}' at index ${index}${message ? `: ${message}` : '.'}`\n : `Invalid event at index ${index}${message ? `: ${message}` : '.'}`\n );\n }\n const validated = result.value;\n if (!isObject(validated) || typeof validated.type !== 'string') {\n throw new Error(`Invalid event at index ${index}.`);\n }\n return validated as EventFromEntry<TSource>;\n })\n );\n}\n\n/** Creates migration and adaptation utilities for versions of one machine. */\nexport function machineVersions<\n const TEntries extends readonly [VersionEntry, ...VersionEntry[]]\n>(entries: TEntries, options?: MachineVersionsOptions<TEntries>) {\n const byIdentity = new Map<string, VersionEntry>();\n const machinesByIdentity = new Map<string, VersionedStateMachine>();\n const machineId = entries[0].id;\n\n for (const entry of entries) {\n if (entry.version === undefined) {\n throw new Error(`Machine '${entry.id}' must define a version.`);\n }\n if (entry.version === '*') {\n throw new Error(\n \"Machine version '*' is reserved for wildcard migrations.\"\n );\n }\n if (entry.id !== machineId) {\n throw new Error(\n `Machine '${entry.id}' does not match machine ID '${machineId}'.`\n );\n }\n const key = `${entry.id}\\0${entry.version}`;\n if (byIdentity.has(key)) {\n throw new Error(\n `Duplicate machine identity '${entry.id}' version '${entry.version}'.`\n );\n }\n byIdentity.set(key, entry);\n if (isVersionedStateMachine(entry)) {\n machinesByIdentity.set(key, entry);\n }\n }\n\n if (\n options?.unversioned !== undefined &&\n !byIdentity.has(`${machineId}\\0${options.unversioned}`)\n ) {\n throw new Error(\n `Unversioned snapshot version '${options.unversioned}' is not retained for machine '${machineId}'.`\n );\n }\n\n const parseSnapshot = async (\n raw: unknown\n ): Promise<ParsedPersistedSnapshot<TEntries>> => {\n if (!isObject(raw)) {\n throw new Error('Persisted snapshot is missing machine identity.');\n }\n\n let id: string;\n let version: string;\n if (isObject(raw.machine)) {\n ({ id, version } = raw.machine as { id: string; version: string });\n if (typeof id !== 'string' || typeof version !== 'string') {\n throw new Error('Persisted snapshot has an invalid machine identity.');\n }\n } else if (typeof raw.version === 'string') {\n id = machineId;\n version = raw.version;\n } else if (\n raw.version === undefined &&\n options?.unversioned !== undefined\n ) {\n id = machineId;\n version = options.unversioned;\n } else {\n throw new Error('Persisted snapshot is missing machine identity.');\n }\n if (raw.version !== undefined && typeof raw.version !== 'string') {\n throw new Error('Persisted snapshot has an invalid version.');\n }\n if (raw.version !== undefined && raw.version !== version) {\n throw new Error(\n `Persisted snapshot version '${raw.version}' conflicts with machine version '${version}'.`\n );\n }\n\n const source = byIdentity.get(`${id}\\0${version}`);\n if (!source) {\n throw new Error(`Unknown machine identity '${id}' version '${version}'.`);\n }\n\n if (!hasSnapshotSchema(source)) {\n throw new Error(\n `Machine version '${version}' does not define a snapshot schema.`\n );\n }\n const snapshot = await validate(\n source.snapshotSchema,\n raw,\n `snapshot for machine '${id}' version '${version}'`\n );\n\n return {\n source,\n ...(isVersionedStateMachine(source) && { machine: source }),\n snapshot: {\n ...(snapshot as Record<string, unknown>),\n machine: { id, version }\n }\n } as ParsedPersistedSnapshot<TEntries>;\n };\n\n return {\n parseSnapshot,\n async adaptEvents<TTargetVersion extends MachineVersion<TEntries>>(\n events: readonly unknown[],\n adaptationOptions: AdaptEventsOptions<TEntries, TTargetVersion>\n ): Promise<EventFrom<MachineForVersion<TEntries, TTargetVersion>>[]> {\n type TargetMachine = MachineForVersion<TEntries, TTargetVersion>;\n const target = machinesByIdentity.get(\n `${machineId}\\0${adaptationOptions.to}`\n ) as TargetMachine | undefined;\n if (!target) {\n throw new Error(\n `Target version '${adaptationOptions.to}' is not backed by a machine for '${machineId}'.`\n );\n }\n\n const sourceId = adaptationOptions.from.id ?? machineId;\n const source = byIdentity.get(\n `${sourceId}\\0${adaptationOptions.from.version}`\n );\n let sourceError: unknown;\n let sourceValidationFailed = false;\n const hasTypedSource = source && hasEventSchema(source);\n if (hasTypedSource) {\n let sourceEvents: EventObject[] | undefined;\n try {\n sourceEvents = await validateEvents(events, source);\n } catch (error) {\n sourceError = error;\n sourceValidationFailed = true;\n }\n if (sourceEvents) {\n if (source === target) {\n return sourceEvents as EventFrom<TargetMachine>[];\n }\n const adapter = (\n adaptationOptions.adapters as Record<\n string,\n | ((\n events: readonly EventObject[]\n ) =>\n | readonly EventFrom<TargetMachine>[]\n | PromiseLike<readonly EventFrom<TargetMachine>[]>)\n | undefined\n >\n )[source.version];\n if (adapter) {\n return validateEvents(\n await adapter(sourceEvents),\n target\n ) as Promise<EventFrom<TargetMachine>[]>;\n }\n }\n }\n\n const wildcardAdapter = adaptationOptions.adapters['*'];\n if (wildcardAdapter) {\n return validateEvents(\n await wildcardAdapter(events, adaptationOptions.from),\n target\n ) as Promise<EventFrom<TargetMachine>[]>;\n }\n if (hasTypedSource) {\n if (sourceValidationFailed) {\n throw sourceError instanceof Error\n ? sourceError\n : new Error(\n `Unable to validate event history for machine '${source.id}' version '${source.version}'.`,\n { cause: sourceError }\n );\n }\n throw new Error(\n `No event adapter from version '${source.version}' to '${target.version}' for machine '${target.id}'.`\n );\n }\n if (source) {\n throw new Error(\n `Machine version '${source.version}' does not define an event schema; only the '*' adapter can handle its event history.`\n );\n }\n throw new Error(\n `Unknown event history source '${sourceId}' version '${adaptationOptions.from.version}'.`\n );\n },\n async migrateSnapshot<TTargetVersion extends MachineVersion<TEntries>>(\n raw: unknown,\n migrationOptions: MigrateSnapshotOptions<TEntries, TTargetVersion>\n ): Promise<\n PersistedSnapshotFrom<MachineForVersion<TEntries, TTargetVersion>>\n > {\n type TargetMachine = MachineForVersion<TEntries, TTargetVersion>;\n const target = machinesByIdentity.get(\n `${machineId}\\0${migrationOptions.to}`\n ) as TargetMachine | undefined;\n if (!target) {\n throw new Error(\n `Target version '${migrationOptions.to}' is not backed by a machine for '${machineId}'.`\n );\n }\n\n let source: ParsedPersistedSnapshot<TEntries> | undefined;\n let parseError: unknown;\n try {\n source = await parseSnapshot(raw);\n } catch (error) {\n parseError = error;\n }\n\n if (source) {\n if (source.source.version === target.version) {\n return finalizeSnapshot(\n source.snapshot as PersistedSnapshotDataFrom<TargetMachine>,\n target\n );\n }\n const exactMigration = (\n migrationOptions.migrations as unknown as Record<\n string,\n | ((\n snapshot: unknown\n ) => MaybePromise<PersistedSnapshotDataFrom<TargetMachine>>)\n | undefined\n >\n )[source.source.version];\n if (exactMigration) {\n return finalizeSnapshot(\n await exactMigration(source.snapshot),\n target\n );\n }\n }\n\n const wildcardMigration = migrationOptions.migrations['*'];\n if (!wildcardMigration) {\n if (source) {\n throw new Error(\n `No snapshot migration from version '${source.source.version}' to '${target.version}' for machine '${target.id}'.`\n );\n }\n throw parseError;\n }\n\n const snapshot = await wildcardMigration(\n raw,\n getSnapshotSource(raw, machineId)\n );\n return finalizeSnapshot(snapshot, target);\n }\n };\n}\n","import { SetupStateSchemas, StandardSchemaV1 } from './schema.types.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\nimport { StateMachine } from './StateMachine.ts';\nimport {\n createActor as createActorFromLogic,\n type Actor,\n type RequiredActorOptionsKeys\n} from './createActor.ts';\nimport {\n AnyActorRef,\n AnyActorLogic,\n ActorRefFromLogic,\n AnyStateNode,\n EventObject,\n AnyEventObject,\n EventDescriptor,\n ExtractEvent,\n MachineContext,\n ProvidedActor,\n RoutableStateId,\n StateSchema,\n StateValue,\n StateValueFromStateSchema,\n ToChildren,\n MetaObject,\n Cast,\n Compute,\n EnqueueObject,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n SystemRegistry,\n RegistryKeyForLogic,\n ActorOptions,\n Observer,\n Subscription,\n OutputArg,\n SnapshotEvent,\n SingleOrArray,\n AfterEvent,\n TimeoutEvent,\n ErrorEvent\n} from './types.ts';\nimport { AnyActorSystem } from './system.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport {\n ActionSchemas,\n DelayMapFromNames,\n DelaySourceMap,\n GuardSourceMap,\n GuardSchemas,\n InferChildren,\n InferActions,\n InferGuards,\n Sources,\n InferOutput,\n InferEvents,\n InferInternalEvents,\n Next_MachineConfig,\n Next_InvokeConfig,\n Next_StateNodeConfig,\n Next_TransitionConfigOrTarget,\n OutputFromConfig,\n ValidateHistoryDefaults,\n ValidateStateTargets,\n WithDefault\n} from './types.v6.ts';\n\nexport type SetupConfig<\n TSchemas extends SetupSchemas,\n TStates extends Record<string, SetupStateSchema>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TValidator extends ActorLogicValidator | undefined =\n | ActorLogicValidator\n | undefined\n> = {\n validator?: TValidator;\n schemas?: TSchemas;\n states?: TStates;\n actions?: TActionMap;\n actors?: TActorMap;\n guards?: TGuardMap & SetupGuardSources<NoInfer<TSchemas>>;\n delays?: TDelayMap & SetupDelaySources<NoInfer<TSchemas>>;\n};\n\n/**\n * Contextual types for guard/delay source maps passed to `setup()`, derived\n * from the same call's `schemas` (context/events). These intersect the\n * inferred source-map type parameters so inline functions get typed args\n * without hand-annotating.\n */\ntype SetupGuardSources<TSchemas> = GuardSourceMap<\n SetupContext<TSchemas, StandardSchemaV1>,\n SetupEvents<TSchemas, Record<string, StandardSchemaV1>>\n>;\n\ntype SetupDelaySources<TSchemas> = DelaySourceMap<\n SetupContext<TSchemas, StandardSchemaV1>,\n SetupEvents<TSchemas, Record<string, StandardSchemaV1>>\n>;\n\n/**\n * Contextual companion for the whole-config `setup()` overload: gives inline\n * `guards`/`delays` functions typed args from the config's own `schemas`.\n */\ntype SetupSourceCompanions<TSchemas> = {\n guards?: SetupGuardSources<TSchemas>;\n delays?: SetupDelaySources<TSchemas>;\n};\n\ntype MergeRecord<TBase, TExtend> = Omit<TBase, keyof TExtend> & TExtend;\n\n/**\n * Mirrors the runtime `mergeSchemas`: scalar schema keys (`context`, `input`,\n * ...) are overridden whole, while map-valued keys (`events`, `emitted`,\n * `children`, `actions`, `guards`) are merged entry-by-entry with extension\n * entries winning, so base-declared entries stay visible to extension sources.\n */\ntype MergedSetupSchemas<TBaseSchemas, TExtendSchemas> = {\n [K in keyof TBaseSchemas | keyof TExtendSchemas]: K extends\n | 'events'\n | 'emitted'\n | 'children'\n | 'actions'\n | 'guards'\n ? MergeRecord<\n K extends keyof TBaseSchemas ? NonNullable<TBaseSchemas[K]> : {},\n K extends keyof TExtendSchemas ? NonNullable<TExtendSchemas[K]> : {}\n >\n : K extends keyof TExtendSchemas\n ? TExtendSchemas[K]\n : K extends keyof TBaseSchemas\n ? TBaseSchemas[K]\n : never;\n};\n\nexport type AnySetupConfig = SetupConfig<\n SetupSchemas,\n Record<string, SetupStateSchema>,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays'],\n ActorLogicValidator | undefined\n>;\n\ninterface RuntimeValidationDoesNotSupportTransformingSchemas {\n readonly __xstate_error: 'Runtime validation does not support schemas with different input and output types';\n}\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n\ntype AssertNonTransformingSchema<TSchema extends StandardSchemaV1> =\n IsAny<StandardSchemaV1.InferInput<TSchema>> extends true\n ? TSchema\n : IsAny<StandardSchemaV1.InferOutput<TSchema>> extends true\n ? TSchema\n : [\n StandardSchemaV1.InferInput<TSchema>,\n StandardSchemaV1.InferOutput<TSchema>\n ] extends [\n StandardSchemaV1.InferOutput<TSchema>,\n StandardSchemaV1.InferInput<TSchema>\n ]\n ? TSchema\n : RuntimeValidationDoesNotSupportTransformingSchemas;\n\ntype ValidateSchemaMap<TMap> =\n TMap extends Record<string, StandardSchemaV1>\n ? {\n [K in keyof TMap]: TMap[K] extends StandardSchemaV1\n ? AssertNonTransformingSchema<TMap[K]>\n : TMap[K];\n }\n : TMap;\n\ntype ValidateSetupSchemas<TSchemas> = TSchemas extends SetupSchemas\n ? {\n [K in keyof TSchemas]: K extends\n | 'events'\n | 'internalEvents'\n | 'emitted'\n | 'children'\n ? ValidateSchemaMap<TSchemas[K]>\n : K extends 'context' | 'input' | 'output'\n ? TSchemas[K] extends StandardSchemaV1\n ? AssertNonTransformingSchema<TSchemas[K]>\n : TSchemas[K]\n : TSchemas[K];\n }\n : TSchemas;\n\ntype ValidateSetupStates<TStates> =\n TStates extends Record<string, SetupStateSchema>\n ? {\n [K in keyof TStates]: TStates[K] extends SetupStateSchema\n ? Omit<TStates[K], 'schemas' | 'states'> & {\n schemas?: TStates[K]['schemas'] extends SetupStateSchemas\n ? {\n [P in keyof TStates[K]['schemas']]: TStates[K]['schemas'][P] extends StandardSchemaV1\n ? AssertNonTransformingSchema<TStates[K]['schemas'][P]>\n : TStates[K]['schemas'][P];\n }\n : TStates[K]['schemas'];\n states?: TStates[K]['states'] extends Record<\n string,\n SetupStateSchema\n >\n ? ValidateSetupStates<TStates[K]['states']>\n : TStates[K]['states'];\n }\n : TStates[K];\n }\n : TStates;\n\ntype RuntimeValidationConstraint<TSchemas, TStates, TValidator> = [\n TValidator\n] extends [ActorLogicValidator]\n ? {\n schemas?: ValidateSetupSchemas<TSchemas>;\n states?: ValidateSetupStates<TStates>;\n }\n : unknown;\n\ntype RuntimeValidationCompatibility<TSchemas, TStates, TValidator> = [\n TValidator\n] extends [ActorLogicValidator]\n ? [TSchemas] extends [ValidateSetupSchemas<TSchemas>]\n ? [TStates] extends [ValidateSetupStates<TStates>]\n ? unknown\n : RuntimeValidationDoesNotSupportTransformingSchemas\n : RuntimeValidationDoesNotSupportTransformingSchemas\n : unknown;\n\ndeclare const inheritedValidator: unique symbol;\ntype InheritedValidator = typeof inheritedValidator;\n\ntype ResolveExtendedValidator<TBase, TExtension> = [TExtension] extends [\n InheritedValidator\n]\n ? TBase\n : Exclude<TExtension, InheritedValidator>;\n\ntype ExtendValidatorConfig<TExtension> = [TExtension] extends [\n InheritedValidator\n]\n ? { validator?: never }\n : { validator: TExtension };\n\ntype SetupExtensionConfig<\n TBaseSchemas,\n TBaseStates,\n TBaseValidator,\n TExtendSchemas extends SetupSchemas,\n TExtendStates extends Record<string, SetupStateSchema>,\n TExtendActionMap extends Sources['actions'],\n TExtendActorMap extends Sources['actors'],\n TExtendGuardMap extends Sources['guards'],\n TExtendDelayMap extends Sources['delays'],\n TExtendValidator extends ActorLogicValidator | undefined | InheritedValidator\n> = Omit<\n SetupConfig<\n TExtendSchemas,\n TExtendStates,\n TExtendActionMap,\n TExtendActorMap,\n TExtendGuardMap,\n TExtendDelayMap\n >,\n 'validator' | 'guards' | 'delays'\n> & {\n guards?: TExtendGuardMap &\n SetupGuardSources<\n NoInfer<MergedSetupSchemas<TBaseSchemas, TExtendSchemas>>\n >;\n delays?: TExtendDelayMap &\n SetupDelaySources<\n NoInfer<MergedSetupSchemas<TBaseSchemas, TExtendSchemas>>\n >;\n} & ExtendValidatorConfig<TExtendValidator> &\n RuntimeValidationCompatibility<\n NoInfer<TBaseSchemas>,\n NoInfer<TBaseStates>,\n ResolveExtendedValidator<TBaseValidator, TExtendValidator>\n > &\n RuntimeValidationConstraint<\n NoInfer<TExtendSchemas>,\n NoInfer<TExtendStates>,\n ResolveExtendedValidator<TBaseValidator, TExtendValidator>\n >;\n\ntype InlineMachineSchemas<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TActionSchemaMap,\n TGuardSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap\n> = {\n context?: TContextSchema;\n events?: TEventSchemaMap;\n internalEvents?: TInternalEventSchemaMap;\n emitted?: TEmittedSchemaMap;\n actions?: TActionSchemaMap;\n guards?: TGuardSchemaMap;\n input?: TInputSchema;\n output?: TOutputSchema;\n meta?: TMetaSchema;\n tags?: TTagSchema;\n children?: TChildrenSchemaMap;\n};\n\ntype MachineConfigStates<TConfig> = TConfig extends {\n states?: infer TStates;\n}\n ? TStates\n : {};\n\ntype MachineConfigSchemas<TConfig> = TConfig extends {\n schemas?: infer TSchemas;\n}\n ? TSchemas\n : {};\n\nexport type SystemConfig<TSystemRegistry extends SystemRegistry> = {\n registry?: TSystemRegistry;\n};\n\nexport type SystemActorMap<TSystemRegistry extends SystemRegistry> = {\n [K in keyof TSystemRegistry & string]: ActorRefFromLogic<TSystemRegistry[K]>;\n};\n\ntype MachineIdentity<TConfig> = {\n readonly id: TConfig extends { id: infer TId extends string }\n ? TId\n : '(machine)';\n readonly version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n};\n\nexport type SystemRuntime<TSystemRegistry extends SystemRegistry> = Omit<\n AnyActorSystem,\n 'get' | 'getAll'\n> & {\n get<K extends keyof SystemActorMap<TSystemRegistry> & string>(\n key: K\n ): SystemActorMap<TSystemRegistry>[K] | undefined;\n getAll(): Partial<SystemActorMap<TSystemRegistry>>;\n};\n\ntype LogicMatchesRegistryKey<TLogic, TSystemLogic> =\n TLogic extends AnyActorLogic\n ? TSystemLogic extends AnyActorLogic\n ? [TLogic] extends [TSystemLogic]\n ? true\n : [TSystemLogic] extends [TLogic]\n ? true\n : ActorRefFromLogic<TLogic> extends ActorRefFromLogic<TSystemLogic>\n ? true\n : false\n : false\n : false;\n\ntype RegistryKeyMatchesSrc<\n TKey extends string,\n TSrc,\n TSystemRegistry extends SystemRegistry,\n TActorMap extends Sources['actors']\n> = TKey extends keyof TSystemRegistry & string\n ? TSrc extends keyof TActorMap & string\n ? LogicMatchesRegistryKey<TActorMap[TSrc], TSystemRegistry[TKey]>\n : TSrc extends AnyActorLogic\n ? LogicMatchesRegistryKey<TSrc, TSystemRegistry[TKey]>\n : true\n : false;\n\ntype ValidateSystemInvoke<\n TInvoke,\n TSystemRegistry extends SystemRegistry,\n TActorMap extends Sources['actors']\n> = TInvoke extends readonly unknown[]\n ? {\n [K in keyof TInvoke]: TInvoke[K] &\n ValidateSystemInvoke<TInvoke[K], TSystemRegistry, TActorMap>;\n }\n : TInvoke extends { registryKey: infer TKey }\n ? TKey extends string\n ? TInvoke extends { src: infer TSrc }\n ? RegistryKeyMatchesSrc<\n TKey,\n TSrc,\n TSystemRegistry,\n TActorMap\n > extends true\n ? unknown\n : { registryKey: never }\n : TKey extends keyof TSystemRegistry & string\n ? unknown\n : { registryKey: never }\n : { registryKey: never }\n : unknown;\n\ntype ValidateRegistryKeys<\n TConfig,\n TSystemRegistry extends SystemRegistry,\n TActorMap extends Sources['actors']\n> = string extends keyof TSystemRegistry\n ? unknown\n : (TConfig extends { invoke: infer TInvoke }\n ? {\n invoke: TInvoke &\n ValidateSystemInvoke<TInvoke, TSystemRegistry, TActorMap>;\n }\n : unknown) &\n (TConfig extends { states: infer TStates }\n ? {\n states: {\n [K in keyof TStates]: TStates[K] &\n ValidateRegistryKeys<TStates[K], TSystemRegistry, TActorMap>;\n };\n }\n : unknown);\n\nexport type { SetupStateSchemas };\n\nexport type SetupSchemas = {\n context?: StandardSchemaV1;\n events?: Record<string, StandardSchemaV1>;\n internalEvents?: Record<string, StandardSchemaV1>;\n actions?: ActionSchemas;\n guards?: GuardSchemas;\n emitted?: Record<string, StandardSchemaV1>;\n input?: StandardSchemaV1;\n output?: StandardSchemaV1;\n meta?: StandardSchemaV1;\n tags?: StandardSchemaV1;\n children?: Record<string, StandardSchemaV1>;\n};\n\n/** State schema with optional input/output schemas and nested states */\nexport interface SetupStateSchema {\n schemas?: SetupStateSchemas;\n states?: Record<string, SetupStateSchema>;\n}\n\ntype SetupSchema<\n TSchemas,\n TKey extends keyof SetupSchemas\n> = TKey extends keyof TSchemas\n ? TSchemas[TKey] extends StandardSchemaV1\n ? TSchemas[TKey]\n : never\n : never;\n\ntype SetupSchemaMap<\n TSchemas,\n TKey extends 'events' | 'internalEvents' | 'emitted' | 'children'\n> = TKey extends keyof TSchemas\n ? TSchemas[TKey] extends Record<string, StandardSchemaV1>\n ? TSchemas[TKey]\n : never\n : never;\n\ntype SetupActionSchemaMap<TSchemas> = 'actions' extends keyof TSchemas\n ? TSchemas['actions'] extends ActionSchemas\n ? TSchemas['actions']\n : never\n : never;\n\ntype SetupGuardSchemaMap<TSchemas> = 'guards' extends keyof TSchemas\n ? TSchemas['guards'] extends GuardSchemas\n ? TSchemas['guards']\n : never\n : never;\n\ntype SetupOrConfigSchema<\n TSchemas,\n TKey extends Exclude<\n keyof SetupSchemas,\n 'events' | 'actions' | 'guards' | 'emitted' | 'children'\n >,\n TConfigSchema extends StandardSchemaV1\n> = [SetupSchema<TSchemas, TKey>] extends [never]\n ? TConfigSchema\n : SetupSchema<TSchemas, TKey>;\n\ntype SetupOrConfigSchemaMap<\n TSchemas,\n TKey extends 'events' | 'internalEvents' | 'emitted' | 'children',\n TConfigSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, TKey>] extends [never]\n ? TConfigSchemaMap\n : SetupSchemaMap<TSchemas, TKey>;\n\ntype SetupStateKeys<TStateSchemas extends Record<string, SetupStateSchema>> =\n keyof TStateSchemas & string;\n\ntype SetupStateKey<TStateSchemas extends Record<string, SetupStateSchema>> =\n string extends SetupStateKeys<TStateSchemas>\n ? string\n : [SetupStateKeys<TStateSchemas>] extends [never]\n ? string\n : SetupStateKeys<TStateSchemas>;\n\ntype SetupStateTarget<TStateSchemas extends Record<string, SetupStateSchema>> =\n string extends SetupStateKeys<TStateSchemas>\n ? string\n : [SetupStateKeys<TStateSchemas>] extends [never]\n ? string\n : SetupStateKeys<TStateSchemas> | `.${string}` | `#${string}`;\n\ntype StateSchemasWithKeys<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TStateKeys extends string\n> = TStateSchemas & {\n [K in Exclude<TStateKeys, keyof TStateSchemas>]: {};\n};\n\n/**\n * The sibling state schemas of a dotted path: the children of the path's\n * parent. A bare transition target resolves relative to the parent, so the\n * valid targets for a path's config are its siblings. For a dotless (top-level)\n * path the siblings are the root states.\n */\ntype ResolveStateSiblings<\n TStates extends Record<string, SetupStateSchema>,\n TPath extends string\n> = TPath extends `${infer Head}.${infer Rest}`\n ? Head extends keyof TStates\n ? TStates[Head]['states'] extends Record<string, SetupStateSchema>\n ? ResolveStateSiblings<TStates[Head]['states'], Rest>\n : never\n : never\n : TStates; // dotless path: siblings are the current level's states\n\n/**\n * Resolves a dotted state path (e.g. `'parent.child'`) into the leaf\n * `SetupStateSchema` it addresses, or `never` if any segment is missing.\n */\ntype ResolveStatePath<\n TStates extends Record<string, SetupStateSchema>,\n TPath extends string\n> = TPath extends `${infer Head}.${infer Rest}`\n ? Head extends keyof TStates\n ? TStates[Head]['states'] extends Record<string, SetupStateSchema>\n ? ResolveStatePath<TStates[Head]['states'], Rest>\n : never\n : never\n : TPath extends keyof TStates\n ? TStates[TPath]\n : never;\n\n/** Union of every addressable dotted path into a setup states tree */\ntype StatePathsInner<TStates extends Record<string, SetupStateSchema>> = {\n [K in SetupStateKeys<TStates>]:\n | K\n | (TStates[K]['states'] extends Record<string, SetupStateSchema>\n ? `${K}.${StatePathsInner<TStates[K]['states']>}`\n : never);\n}[SetupStateKeys<TStates>];\n\ntype StatePaths<TStates extends Record<string, SetupStateSchema>> =\n string extends SetupStateKeys<TStates>\n ? string\n : [SetupStateKeys<TStates>] extends [never]\n ? string\n : StatePathsInner<TStates>;\n\n/**\n * Shared body of both `createStateConfig` overloads: the\n * `StateNodeConfigWithNestedInput` instantiation whose only varying parts are\n * the leading sibling-schemas and state-schema arguments.\n */\ntype SetupStateNodeConfig<\n TStates extends Record<string, SetupStateSchema>,\n TStateSchema extends SetupStateSchema,\n TSchemas extends SetupSchemas,\n TSetupActionMap extends Sources['actions'],\n TSetupActorMap extends Sources['actors'],\n TSetupGuardMap extends Sources['guards'],\n TSetupDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = StateNodeConfigWithNestedInput<\n TStates,\n TStateSchema,\n SetupContext<TSchemas, StandardSchemaV1>,\n SetupContextShape<\n TSchemas,\n StandardSchemaV1,\n SetupContext<TSchemas, StandardSchemaV1>\n >,\n SetupEvents<TSchemas, Record<string, StandardSchemaV1>>,\n Cast<\n SetupChildren<TSchemas, Record<string, StandardSchemaV1>>,\n Record<string, AnyActorRef | undefined>\n >,\n string,\n SetupTags<TSchemas, StandardSchemaV1>,\n SetupOutput<TSchemas, StandardSchemaV1>,\n SetupEmitted<TSchemas, Record<string, StandardSchemaV1>>,\n SetupMeta<TSchemas, StandardSchemaV1>,\n SetupActions<TSchemas, TSetupActionMap>,\n TSetupActorMap,\n SetupGuards<TSchemas, TSetupGuardMap>,\n TSetupDelayMap,\n TSystemRegistry\n>;\n\ntype SetupContext<TSchemas, TContextSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'context'>\n] extends [never]\n ? unknown extends StandardSchemaV1.InferOutput<TContextSchema>\n ? MachineContext\n : StandardSchemaV1.InferOutput<TContextSchema> & MachineContext\n : StandardSchemaV1.InferOutput<SetupSchema<TSchemas, 'context'>> &\n MachineContext;\n\ntype SetupContextShape<\n TSchemas,\n TContextSchema extends StandardSchemaV1,\n TFallbackContext\n> = [SetupSchema<TSchemas, 'context'>] extends [never]\n ? unknown extends StandardSchemaV1.InferOutput<TContextSchema>\n ? TFallbackContext\n : StandardSchemaV1.InferOutput<TContextSchema>\n : StandardSchemaV1.InferOutput<SetupSchema<TSchemas, 'context'>>;\n\ntype SetupContextRequired<TSchemas, TContextSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'context'>\n] extends [never]\n ? unknown extends StandardSchemaV1.InferOutput<TContextSchema>\n ? false\n : true\n : true;\n\ntype SetupPublicEvents<\n TSchemas,\n TEventSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'events'>] extends [never]\n ? InferEvents<TEventSchemaMap>\n : InferEvents<SetupSchemaMap<TSchemas, 'events'>>;\n\ntype SetupInternalEvents<\n TSchemas,\n TInternalEventSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'internalEvents'>] extends [never]\n ? InferInternalEvents<TInternalEventSchemaMap>\n : InferInternalEvents<SetupSchemaMap<TSchemas, 'internalEvents'>>;\n\ntype SetupEvents<\n TSchemas,\n TEventSchemaMap extends Record<string, StandardSchemaV1>,\n TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {}\n> =\n | SetupPublicEvents<TSchemas, TEventSchemaMap>\n | SetupInternalEvents<TSchemas, TInternalEventSchemaMap>;\n\ntype SetupTags<TSchemas, TTagSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'tags'>\n] extends [never]\n ? StandardSchemaV1.InferOutput<TTagSchema> & string\n : StandardSchemaV1.InferOutput<SetupSchema<TSchemas, 'tags'>> & string;\n\ntype SetupInput<TSchemas, TInputSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'input'>\n] extends [never]\n ? InferOutput<TInputSchema, unknown>\n : InferOutput<SetupSchema<TSchemas, 'input'>, unknown>;\n\ntype SetupOutput<TSchemas, TOutputSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'output'>\n] extends [never]\n ? InferOutput<TOutputSchema, unknown>\n : InferOutput<SetupSchema<TSchemas, 'output'>, unknown>;\n\n/**\n * Whether an output schema was declared, either in `setup({ schemas })` or in\n * the machine config's own `schemas.output`. A declared schema is always\n * authoritative for the machine's output type.\n */\ntype HasOutputSchema<TSchemas, TOutputSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'output'>\n] extends [never]\n ? StandardSchemaV1 extends TOutputSchema\n ? false\n : true\n : true;\n\n/**\n * The machine's output type. A declared output schema wins; otherwise the type\n * is inferred from the config's `output` property (a mapper's return type, or\n * the static value's type).\n */\ntype SetupOrConfigOutput<\n TSchemas,\n TOutputSchema extends StandardSchemaV1,\n TConfig\n> =\n HasOutputSchema<TSchemas, TOutputSchema> extends true\n ? SetupOutput<TSchemas, TOutputSchema>\n : OutputFromConfig<TConfig, SetupOutput<TSchemas, TOutputSchema>>;\n\ntype SetupEmitted<\n TSchemas,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'emitted'>] extends [never]\n ? WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>\n : WithDefault<\n InferEvents<SetupSchemaMap<TSchemas, 'emitted'>>,\n AnyEventObject\n >;\n\ntype SetupMeta<TSchemas, TMetaSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'meta'>\n] extends [never]\n ? InferOutput<TMetaSchema, MetaObject>\n : InferOutput<SetupSchema<TSchemas, 'meta'>, MetaObject>;\n\ntype SetupChildren<\n TSchemas,\n TChildrenSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'children'>] extends [never]\n ? InferChildren<TChildrenSchemaMap>\n : InferChildren<SetupSchemaMap<TSchemas, 'children'>>;\n\ntype SetupActions<TSchemas, TActionMap extends Sources['actions']> = [\n SetupActionSchemaMap<TSchemas>\n] extends [never]\n ? TActionMap\n : MergeSourceMaps<InferActions<SetupActionSchemaMap<TSchemas>>, TActionMap>;\n\ntype SetupGuards<TSchemas, TGuardMap extends Sources['guards']> = [\n SetupGuardSchemaMap<TSchemas>\n] extends [never]\n ? TGuardMap\n : MergeSourceMaps<InferGuards<SetupGuardSchemaMap<TSchemas>>, TGuardMap>;\n\ntype MergeChildren<\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActor extends ProvidedActor\n> = [keyof TChildren] extends [never]\n ? Compute<ToChildren<TActor>>\n : Compute<TChildren>;\n\ntype MergeSourceMaps<\n TBase extends Record<string, unknown>,\n TExtension extends Record<string, unknown>\n> = Compute<TBase & TExtension>;\n\ntype DelayNamesFromConfigOrString<TConfig> = TConfig extends {\n delays: infer TDelays;\n}\n ? Extract<keyof TDelays, string>\n : string;\n\ntype DelayNamesFromConfig<TConfig> = TConfig extends { delays: infer TDelays }\n ? Extract<keyof TDelays, string>\n : never;\n\ntype InvalidDelayReferences<TConfig, TDelays extends string> =\n | (TConfig extends { after: infer TAfter }\n ? Exclude<Extract<keyof TAfter, string>, TDelays>\n : never)\n | (TConfig extends { timeout: infer TTimeout }\n ? TTimeout extends string\n ? TTimeout extends TDelays\n ? never\n : TTimeout\n : never\n : never)\n | (TConfig extends { states: infer TStates }\n ? TStates extends Record<string, unknown>\n ? {\n [K in keyof TStates]: InvalidDelayReferences<TStates[K], TDelays>;\n }[keyof TStates]\n : never\n : never);\n\ntype ValidateSetupDelayReferences<\n TConfig,\n TSetupDelays extends string\n> = string extends (\n [TSetupDelays] extends [never]\n ? DelayNamesFromConfigOrString<TConfig>\n : TSetupDelays | DelayNamesFromConfig<TConfig>\n)\n ? unknown\n : InvalidDelayReferences<\n TConfig,\n [TSetupDelays] extends [never]\n ? DelayNamesFromConfigOrString<TConfig>\n : TSetupDelays | DelayNamesFromConfig<TConfig>\n > extends never\n ? unknown\n : never;\n\n/** Extracts input type from a state schema */\ntype StateInput<TStateSchema extends SetupStateSchema> =\n TStateSchema['schemas'] extends { input: infer TInputSchema }\n ? TInputSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : undefined\n : undefined;\n\n/** Extracts the completion output type from a state schema. */\ntype StateOutput<\n TStateSchema extends SetupStateSchema,\n TFallback\n> = TStateSchema['schemas'] extends { output: infer TOutputSchema }\n ? TOutputSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TOutputSchema>\n : TFallback\n : TFallback;\n\ntype StateCompletionOutput<TStateSchema extends SetupStateSchema> = StateOutput<\n TStateSchema,\n unknown\n>;\n\ntype StateContext<\n TStateSchema extends SetupStateSchema,\n TFallbackContext extends MachineContext\n> = TStateSchema['schemas'] extends { context: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TContextSchema> &\n MachineContext &\n RootContextMarker<TFallbackContext>\n : RootContext<TFallbackContext>\n : RootContext<TFallbackContext>;\n\ndeclare const rootContext: unique symbol;\n\ntype RootContextMarker<TContext> = {\n readonly [rootContext]?: RootContext<TContext>;\n};\n\ntype RootContext<TContext> = typeof rootContext extends keyof TContext\n ? TContext[typeof rootContext]\n : TContext;\n\ntype StateContextShape<\n TStateSchema extends SetupStateSchema,\n TFallbackContext\n> = TStateSchema['schemas'] extends { context: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TContextSchema> &\n RootContextMarker<TFallbackContext>\n : RootContext<TFallbackContext>\n : RootContext<TFallbackContext>;\n\ntype WithNestedStates<TConfig, TNestedStates> = TConfig extends {\n type: 'choice';\n}\n ? TConfig\n : Omit<TConfig, 'states'> & { states?: TNestedStates };\n\ntype DistributiveOmit<T, K extends keyof any> = T extends any\n ? Omit<T, K>\n : never;\n\n/**\n * Converts SetupStateSchema to StateSchema with input types included. This\n * allows getInputs() to be strongly typed.\n */\ntype SetupStateSchemaToStateSchema<TSetupSchema extends SetupStateSchema> = {\n input: StateInput<TSetupSchema>;\n contextSchema: TSetupSchema['schemas'] extends {\n context: infer TContextSchema;\n }\n ? TContextSchema extends StandardSchemaV1\n ? TContextSchema\n : undefined\n : undefined;\n outputSchema: TSetupSchema['schemas'] extends {\n output: infer TOutputSchema;\n }\n ? TOutputSchema extends StandardSchemaV1\n ? TOutputSchema\n : undefined\n : undefined;\n states: TSetupSchema['states'] extends Record<string, SetupStateSchema>\n ? {\n [K in keyof TSetupSchema['states'] &\n string]: SetupStateSchemaToStateSchema<TSetupSchema['states'][K]>;\n }\n : undefined;\n};\n\n/** Converts the root setup states config to a StateSchema. */\ntype SetupStatesToStateSchema<\n TStates extends Record<string, SetupStateSchema>\n> = {\n states: {\n [K in keyof TStates & string]: SetupStateSchemaToStateSchema<TStates[K]>;\n };\n};\n\ntype EmptyStateSchema = {\n input: undefined;\n states: undefined;\n};\n\ntype StateSchemaInput<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = TSetup extends { input: infer TInput }\n ? TInput\n : TConfig extends { input: infer TInput }\n ? TInput\n : undefined;\n\ntype StateSchemaContextSchema<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = TSetup extends { contextSchema: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? TContextSchema\n : undefined\n : TConfig extends { contextSchema: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? TContextSchema\n : undefined\n : undefined;\n\ntype StateSchemaOutputSchema<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = TSetup extends { outputSchema: infer TOutputSchema }\n ? TOutputSchema extends StandardSchemaV1\n ? TOutputSchema\n : undefined\n : TConfig extends { outputSchema: infer TOutputSchema }\n ? TOutputSchema extends StandardSchemaV1\n ? TOutputSchema\n : undefined\n : undefined;\n\ntype StateSchemaChild<\n TSetup extends StateSchema,\n K extends string\n> = TSetup extends { states: infer TStates }\n ? K extends keyof TStates\n ? Cast<TStates[K], StateSchema>\n : EmptyStateSchema\n : EmptyStateSchema;\n\ntype MergeStateSchema<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = Omit<TConfig, 'contextSchema' | 'input' | 'states'> & {\n contextSchema: StateSchemaContextSchema<TConfig, TSetup>;\n outputSchema: StateSchemaOutputSchema<TConfig, TSetup>;\n input: StateSchemaInput<TConfig, TSetup>;\n states: TConfig extends { states: infer TStates }\n ? TStates extends Record<string, StateSchema>\n ? {\n [K in keyof TStates & string]: MergeStateSchema<\n TStates[K],\n StateSchemaChild<TSetup, K>\n >;\n }\n : undefined\n : undefined;\n};\n\n/** Machine config with typed state input */\ntype SetupMachineConfig<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TStateKeys extends string,\n TSchemas extends SetupSchemas,\n TContextSchema extends StandardSchemaV1,\n TEventSchemaMap extends Record<string, StandardSchemaV1>,\n TInternalEventSchemaMap extends Record<string, StandardSchemaV1>,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>,\n TInputSchema extends StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n TChildrenSchemaMap extends Record<string, StandardSchemaV1>,\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TDelays extends string,\n TTag extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TContextRequired extends boolean,\n TRootDelays extends string = TDelays,\n TRootActionMap extends Sources['actions'] = TActionMap,\n TRootActorMap extends Sources['actors'] = TActorMap,\n TRootGuardMap extends Sources['guards'] = TGuardMap\n> = Omit<\n Next_MachineConfig<\n SetupOrConfigSchema<TSchemas, 'context', TContextSchema>,\n SetupOrConfigSchemaMap<TSchemas, 'events', TEventSchemaMap>,\n SetupOrConfigSchemaMap<TSchemas, 'internalEvents', TInternalEventSchemaMap>,\n SetupOrConfigSchemaMap<TSchemas, 'emitted', TEmittedSchemaMap>,\n SetupOrConfigSchema<TSchemas, 'input', TInputSchema>,\n SetupOrConfigSchema<TSchemas, 'output', TOutputSchema>,\n SetupOrConfigSchema<TSchemas, 'meta', TMetaSchema>,\n SetupOrConfigSchema<TSchemas, 'tags', TTagSchema>,\n SetupOrConfigSchemaMap<TSchemas, 'children', TChildrenSchemaMap>,\n TContext,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TContextRequired,\n TSystemRegistry\n >,\n | 'states'\n | 'initial'\n | 'on'\n | 'always'\n | 'invoke'\n | 'actions'\n | 'actors'\n | 'guards'\n | 'delays'\n> & {\n actions?: TRootActionMap;\n actors?: TRootActorMap;\n guards?: TRootGuardMap & GuardSourceMap<TContext, TEvent>;\n delays?: {\n [K in TRootDelays | number]?:\n | number\n | (({\n context,\n event,\n stateNode\n }: {\n context: TContext;\n event: TEvent;\n stateNode: AnyStateNode;\n }) => number);\n };\n initial?:\n | TStateKeys\n | InitialTransitionWithInput<TStateSchemas, TContext, TEvent>\n | undefined;\n on?: StateTransitions<\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n always?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n invoke?: SingleOrArray<\n SetupInvokeConfig<\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n >;\n states?: StatesWithInput<\n TStateSchemas,\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n SetupOutput<TSchemas, TOutputSchema>,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TStateKeys\n >;\n};\n\n/** States config type that provides typed input for known states */\ntype StatesWithInput<\n TRootStateSchemas extends Record<string, SetupStateSchema>,\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TDelays extends string,\n TTag extends string,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TStateKeys extends string = SetupStateKey<TStateSchemas>\n> = {\n [K in TStateKeys]?: StateNodeConfigWithNestedInput<\n StateSchemasWithKeys<TRootStateSchemas, TStateKeys>,\n K extends keyof TStateSchemas ? TStateSchemas[K] : {},\n TContext,\n TContextShape,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n TOutput,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n};\n\n/** State node config that recursively applies typed input for nested states */\ntype StateNodeConfigWithNestedInput<\n TSiblingStateSchemas extends Record<string, SetupStateSchema>,\n TStateSchema extends SetupStateSchema,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TDelays extends string,\n TTag extends string,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = WithNestedStates<\n Omit<\n Next_StateNodeConfig<\n StateContext<TStateSchema, TContext>,\n TEvent,\n TDelays,\n TTag,\n StateOutput<TStateSchema, TOutput>,\n TEmitted,\n TMeta,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n StateInput<TStateSchema>,\n Record<string, unknown>,\n TSystemRegistry,\n StateCompletionOutput<TStateSchema>\n >,\n | 'on'\n | 'always'\n | 'initial'\n | 'invoke'\n | 'onDone'\n | 'onError'\n | 'onTimeout'\n | 'after'\n > & {\n initial?: TStateSchema['states'] extends Record<string, SetupStateSchema>\n ?\n | SetupStateKey<TStateSchema['states']>\n | (string & {})\n | InitialTransitionWithInput<\n TStateSchema['states'],\n StateContext<TStateSchema, TContext>,\n TEvent\n >\n :\n | string\n | {\n target: string;\n input?: Record<string, unknown>;\n }\n | undefined;\n on?: StateTransitions<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n always?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n invoke?: SingleOrArray<\n SetupInvokeConfig<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n >;\n onDone?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n DoneStateEvent<StateCompletionOutput<TStateSchema>>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n onError?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n ErrorEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n onTimeout?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TimeoutEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n after?: {\n [K in NoInfer<TDelays> | number]?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n AfterEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n };\n },\n TStateSchema['states'] extends Record<string, SetupStateSchema>\n ? StatesWithInput<\n TStateSchema['states'],\n TStateSchema['states'],\n TContext,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n TOutput,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n : {\n [K in string]?: Next_StateNodeConfig<\n TContext,\n TEvent,\n TDelays,\n TTag,\n TOutput,\n TEmitted,\n TMeta,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n undefined,\n Record<string, unknown>,\n TSystemRegistry\n >;\n }\n>;\n\ntype StateTransitions<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TInput = undefined\n> = {\n [K in EventDescriptor<TEvent>]?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n ExtractEvent<TEvent, K>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TInput\n >;\n};\n\ntype InvokeDoneEvent<TInvoke> = TInvoke extends {\n onDone?: Next_TransitionConfigOrTarget<\n infer _TContext,\n infer TDoneEvent,\n infer _TEvent,\n infer _TEmitted,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer _TMeta\n >;\n}\n ? Cast<TDoneEvent, EventObject>\n : DoneActorEvent;\n\ntype SetupInvokeConfig<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> =\n Next_InvokeConfig<\n TContext,\n TEvent,\n TEmitted,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta,\n TSystemRegistry\n > extends infer TInvoke\n ? TInvoke extends any\n ? DistributiveOmit<\n TInvoke,\n 'onDone' | 'onError' | 'onSnapshot' | 'onTimeout'\n > & {\n // Inline (unregistered-logic) invoke branches have no function-form\n // `onDone` when actors are registered (see InlineInvokeOnDone), and\n // that must be preserved when rebuilding `onDone` here: when a\n // registered logic value is passed as `src`, TypeScript narrows the\n // invoke union to the matching registered branch plus the inline\n // branch, and contextual typing of `onDone` callbacks (and their\n // per-actor `event.output`) only works if the registered branch\n // provides the union's only call signature.\n onDone?: TInvoke extends {\n onDone?: infer TOnDone;\n }\n ? [\n Extract<NonNullable<TOnDone>, (...args: any[]) => unknown>\n ] extends [never]\n ?\n | undefined\n | StateTransitionObjectConfig<\n TStateSchemas,\n TContext,\n TContextShape,\n DoneActorEvent,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n false\n >\n : StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n InvokeDoneEvent<TInvoke>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n : never;\n onError?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n onSnapshot?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n SnapshotEvent<any>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n onTimeout?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n TEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n }\n : never\n : never;\n\ntype StateTransitionConfigOrTarget<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TInput = undefined\n> =\n | undefined\n | StateTransitionObjectConfig<\n TStateSchemas,\n TContext,\n TContextShape,\n TExpressionEvent,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n | StateTransitionFunction<\n TStateSchemas,\n TContext,\n TContextShape,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TInput\n >;\n\ntype StateTransitionObjectConfig<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TAllowContextMapper extends boolean = true\n> =\n | (StateTransitionResult<\n TStateSchemas,\n TContext,\n TContextShape,\n TMeta,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TAllowContextMapper\n > & {\n description?: string;\n })\n | {\n target: SetupStateTarget<TStateSchemas>[];\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n TContextShape,\n TContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n description?: string;\n reenter?: boolean;\n meta?: TMeta;\n input?:\n | Record<string, unknown>\n | ((\n args: {\n context: TContext;\n event: TExpressionEvent;\n } & OutputArg<TExpressionEvent>\n ) => Record<string, unknown>);\n };\n\ntype StateTransitionContextMapper<\n TContext extends MachineContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = (\n args: {\n context: TContext;\n event: TExpressionEvent;\n self: AnyActorRef;\n parent: AnyActorRef | undefined;\n value: StateValue;\n children: TChildren;\n system: SystemRuntime<TSystemRegistry>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n } & OutputArg<TExpressionEvent>\n) => ContextPatch<TContextShape, TTargetContextShape, TResolvedTargetContext>;\n\ntype StateTransitionContextOrMapper<\n TContext extends MachineContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> =\n | ContextPatch<TContextShape, TTargetContextShape, TResolvedTargetContext>\n | StateTransitionContextMapper<\n TContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n\ntype StateTransitionContext<\n TAllowMapper extends boolean,\n TContext extends MachineContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = TAllowMapper extends true\n ? StateTransitionContextOrMapper<\n TContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n : ContextPatch<TContextShape, TTargetContextShape, TResolvedTargetContext>;\n\ntype StateTransitionFunction<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TInput = undefined\n> = (\n args: {\n context: TContext;\n event: TExpressionEvent;\n self: AnyActorRef;\n parent: AnyActorRef | undefined;\n value: StateValue;\n children: TChildren;\n system: SystemRuntime<TSystemRegistry>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n input: TInput;\n } & OutputArg<TExpressionEvent>,\n enq: EnqueueObject<TEvent, TEmitted, TSystemRegistry, TActorMap>\n) => StateTransitionResult<\n TStateSchemas,\n TContext,\n TContextShape,\n TMeta,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n false\n> | void;\n\ntype StateTransitionResult<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TMeta extends MetaObject,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TAllowContextMapper extends boolean\n> =\n | {\n target?: never;\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n TContextShape,\n TContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n reenter?: boolean;\n meta?: TMeta;\n }\n | {\n [K in keyof TStateSchemas & string]: {\n target: K;\n reenter?: boolean;\n meta?: TMeta;\n input?:\n | StateInput<TStateSchemas[K]>\n | ((\n args: {\n context: TContext;\n event: EventObject;\n } & OutputArg<EventObject>\n ) => StateInput<TStateSchemas[K]>);\n } & ([TContextShape] extends [\n StateContextShape<TStateSchemas[K], TContextShape>\n ]\n ? {\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n StateContextShape<TStateSchemas[K], TContextShape>,\n StateContext<TStateSchemas[K], TContext>,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n }\n : {\n context: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n StateContextShape<TStateSchemas[K], TContextShape>,\n StateContext<TStateSchemas[K], TContext>,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n });\n }[keyof TStateSchemas & string]\n | {\n target: Exclude<\n SetupStateTarget<TStateSchemas>,\n keyof TStateSchemas & string\n >;\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n TContextShape,\n TContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n reenter?: boolean;\n meta?: TMeta;\n };\n\ntype ContextPatch<\n TCurrentContext,\n TTargetContext,\n TResolvedTargetContext extends MachineContext\n> = Compute<\n Partial<TResolvedTargetContext> &\n Pick<\n TResolvedTargetContext,\n Extract<RequiredContextKeys<TCurrentContext, TTargetContext>, string>\n > & {\n call?: never;\n apply?: never;\n bind?: never;\n }\n>;\n\ntype RequiredContextKeys<TCurrentContext, TTargetContext> = {\n [K in keyof TTargetContext]-?: K extends keyof TCurrentContext\n ? [TCurrentContext[K]] extends [TTargetContext[K]]\n ? never\n : K\n : K;\n}[keyof TTargetContext];\n\n/** Initial transition with typed input based on target state */\ntype InitialTransitionWithInput<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in keyof TStateSchemas & string]: {\n target: K;\n input?:\n | StateInput<TStateSchemas[K]>\n | ((args: {\n context: TContext;\n event: TEvent;\n }) => StateInput<TStateSchemas[K]>);\n };\n}[keyof TStateSchemas & string];\n\n/** Return type of setup() */\nexport interface SetupReturn<\n TStates extends Record<string, SetupStateSchema> = Record<\n string,\n SetupStateSchema\n >,\n TSchemas extends SetupSchemas = {},\n TSetupActionMap extends Sources['actions'] = {},\n TSetupActorMap extends Sources['actors'] = {},\n TSetupGuardMap extends Sources['guards'] = {},\n TSetupDelayMap extends Sources['delays'] = {},\n TSetupDelays extends string = Extract<keyof TSetupDelayMap, string>,\n TSystemRegistry extends SystemRegistry = SystemRegistry,\n TValidator extends ActorLogicValidator | undefined = undefined\n> {\n /** Extends the setup configuration */\n extend<\n const TExtendSchemas extends SetupSchemas = {},\n const TExtendStates extends Record<string, SetupStateSchema> = {},\n TExtendActionMap extends Sources['actions'] = {},\n TExtendActorMap extends Sources['actors'] = {},\n TExtendGuardMap extends Sources['guards'] = {},\n TExtendDelayMap extends Sources['delays'] = {},\n const TExtendValidator extends\n | ActorLogicValidator\n | undefined\n | InheritedValidator = InheritedValidator\n >(\n config: SetupExtensionConfig<\n TSchemas,\n TStates,\n TValidator,\n TExtendSchemas,\n TExtendStates,\n TExtendActionMap,\n TExtendActorMap,\n TExtendGuardMap,\n TExtendDelayMap,\n TExtendValidator\n >\n ): SetupReturn<\n MergeSourceMaps<TStates, TExtendStates>,\n MergeSourceMaps<TSchemas, TExtendSchemas>,\n MergeSourceMaps<TSetupActionMap, TExtendActionMap>,\n MergeSourceMaps<TSetupActorMap, TExtendActorMap>,\n MergeSourceMaps<TSetupGuardMap, TExtendGuardMap>,\n MergeSourceMaps<TSetupDelayMap, TExtendDelayMap>,\n TSetupDelays | Extract<keyof TExtendDelayMap, string>,\n TSystemRegistry,\n ResolveExtendedValidator<TValidator, TExtendValidator>\n >;\n\n /** Creates a state machine with the setup configuration */\n createMachine<\n TContextSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TEventSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {},\n TEmittedSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1 = StandardSchemaV1,\n TTagSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TActionSchemaMap extends ActionSchemas = {},\n const TGuardSchemaMap extends GuardSchemas = {},\n _TEvent extends EventObject = EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TActionMap extends Sources['actions'] = {},\n TActorMap extends Sources['actors'] = {},\n TGuardMap extends Sources['guards'] = {},\n TDelayMap extends Sources['delays'] = {},\n TDelays extends string = Extract<keyof TDelayMap, string>,\n TTag extends SetupTags<TSchemas, TTagSchema> = SetupTags<\n TSchemas,\n TTagSchema\n >,\n TInput = unknown,\n const TStateKeys extends string = SetupStateKey<TStates>,\n TConfig extends SetupMachineConfig<\n TStates,\n TStateKeys,\n TSchemas,\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n SetupContext<TSchemas, TContextSchema>,\n SetupEvents<TSchemas, TEventSchemaMap, TInternalEventSchemaMap>,\n Cast<\n MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TSetupDelays | TDelays,\n TTag,\n SetupEmitted<TSchemas, TEmittedSchemaMap>,\n SetupMeta<TSchemas, TMetaSchema>,\n MergeSourceMaps<\n SetupActions<TSchemas, TSetupActionMap>,\n MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>\n >,\n MergeSourceMaps<TSetupActorMap, TActorMap>,\n MergeSourceMaps<\n SetupGuards<TSchemas, TSetupGuardMap>,\n MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>\n >,\n MergeSourceMaps<TSetupDelayMap, TDelayMap>,\n TSystemRegistry,\n SetupContextRequired<TSchemas, TContextSchema>,\n TDelays,\n TActionMap,\n TActorMap,\n TGuardMap\n > = SetupMachineConfig<\n TStates,\n TStateKeys,\n TSchemas,\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n SetupContext<TSchemas, TContextSchema>,\n SetupEvents<TSchemas, TEventSchemaMap, TInternalEventSchemaMap>,\n Cast<\n MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TSetupDelays | TDelays,\n TTag,\n SetupEmitted<TSchemas, TEmittedSchemaMap>,\n SetupMeta<TSchemas, TMetaSchema>,\n MergeSourceMaps<\n SetupActions<TSchemas, TSetupActionMap>,\n MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>\n >,\n MergeSourceMaps<TSetupActorMap, TActorMap>,\n MergeSourceMaps<\n SetupGuards<TSchemas, TSetupGuardMap>,\n MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>\n >,\n MergeSourceMaps<TSetupDelayMap, TDelayMap>,\n TSystemRegistry,\n SetupContextRequired<TSchemas, TContextSchema>,\n TDelays,\n TActionMap,\n TActorMap,\n TGuardMap\n >\n >(\n config: {\n schemas?: {\n events?: TEventSchemaMap;\n internalEvents?: TInternalEventSchemaMap;\n context?: TContextSchema;\n emitted?: TEmittedSchemaMap;\n actions?: TActionSchemaMap;\n guards?: TGuardSchemaMap;\n input?: TInputSchema;\n output?: TOutputSchema;\n meta?: TMetaSchema;\n tags?: TTagSchema;\n children?: TChildrenSchemaMap;\n } & ([TValidator] extends [ActorLogicValidator]\n ? ValidateSetupSchemas<\n InlineMachineSchemas<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TActionSchemaMap,\n TGuardSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap\n >\n >\n : unknown);\n actions?: TActionMap;\n actors?: TActorMap;\n guards?: TGuardMap;\n delays?: TDelayMap;\n states?: Record<TStateKeys, unknown>;\n } & TConfig &\n RuntimeValidationConstraint<\n NoInfer<MachineConfigSchemas<TConfig>>,\n NoInfer<MachineConfigStates<TConfig>>,\n TValidator\n > &\n ValidateSetupDelayReferences<TConfig, TSetupDelays> &\n ValidateHistoryDefaults<TConfig> &\n ValidateStateTargets<TConfig> &\n ValidateRegistryKeys<\n TConfig,\n TSystemRegistry,\n MergeSourceMaps<TSetupActorMap, TActorMap>\n >\n ): StateMachine<\n SetupContext<TSchemas, TContextSchema>,\n | SetupEvents<TSchemas, TEventSchemaMap, TInternalEventSchemaMap>\n | ([RoutableStateId<Cast<TConfig, StateSchema>>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<Cast<TConfig, StateSchema>>;\n }),\n Cast<\n MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<\n MergeStateSchema<\n Cast<TConfig, StateSchema>,\n SetupStatesToStateSchema<TStates>\n >\n >,\n TTag & string,\n [SetupSchema<TSchemas, 'input'>] extends [never]\n ? TInput\n : SetupInput<TSchemas, TInputSchema>,\n SetupOrConfigOutput<TSchemas, TOutputSchema, TConfig>,\n SetupEmitted<TSchemas, TEmittedSchemaMap>,\n SetupMeta<TSchemas, TMetaSchema>,\n MergeStateSchema<\n Cast<TConfig, StateSchema>,\n SetupStatesToStateSchema<TStates>\n >,\n MergeSourceMaps<\n SetupActions<TSchemas, TSetupActionMap>,\n MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>\n >,\n MergeSourceMaps<TSetupActorMap, TActorMap>,\n MergeSourceMaps<\n SetupGuards<TSchemas, TSetupGuardMap>,\n MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>\n >,\n DelayMapFromNames<\n TSetupDelays | TDelays,\n MergeSourceMaps<TSetupDelayMap, TDelayMap>\n >,\n SetupInternalEvents<TSchemas, TInternalEventSchemaMap>\n > &\n MachineIdentity<TConfig>;\n\n /**\n * Creates a state node config bound to a specific setup-declared state,\n * addressed by a dotted path (e.g. `'loading'` or `'parent.child'`). The\n * addressed state's own `input` schema is typed inside `entry`/`exit` args.\n */\n createStateConfig<\n const TPath extends StatePaths<TStates>,\n const TConfig extends SetupStateNodeConfig<\n ResolveStateSiblings<TStates, TPath>,\n ResolveStatePath<TStates, TPath>,\n TSchemas,\n TSetupActionMap,\n TSetupActorMap,\n TSetupGuardMap,\n TSetupDelayMap,\n TSystemRegistry\n >\n >(\n path: TPath,\n config: TConfig\n ): TConfig;\n\n /** Creates a state node config with the setup configuration */\n createStateConfig<\n const TConfig extends SetupStateNodeConfig<\n TStates,\n SetupStateSchema,\n TSchemas,\n TSetupActionMap,\n TSetupActorMap,\n TSetupGuardMap,\n TSetupDelayMap,\n TSystemRegistry\n >\n >(\n config: TConfig\n ): TConfig;\n\n /** State input schemas from setup config */\n states: TStates;\n\n /** Schemas from setup config */\n schemas: TSchemas;\n}\n\ntype SetupConfigSchemas<TConfig> = TConfig extends { schemas?: infer TSchemas }\n ? TSchemas extends SetupSchemas\n ? TSchemas\n : {}\n : {};\n\ntype SetupConfigStates<TConfig> = TConfig extends { states?: infer TStates }\n ? TStates extends Record<string, SetupStateSchema>\n ? TStates\n : Record<string, SetupStateSchema>\n : Record<string, SetupStateSchema>;\n\ntype SetupConfigActions<TConfig> = TConfig extends { actions?: infer TActions }\n ? TActions extends Sources['actions']\n ? MergeSourceMaps<SetupActions<SetupConfigSchemas<TConfig>, {}>, TActions>\n : SetupActions<SetupConfigSchemas<TConfig>, {}>\n : SetupActions<SetupConfigSchemas<TConfig>, {}>;\n\ntype SetupConfigActors<TConfig> = TConfig extends {\n actors?: infer TActors;\n}\n ? TActors extends Sources['actors']\n ? TActors\n : {}\n : {};\n\ntype SetupConfigGuards<TConfig> = TConfig extends { guards?: infer TGuards }\n ? TGuards extends Sources['guards']\n ? MergeSourceMaps<SetupGuards<SetupConfigSchemas<TConfig>, {}>, TGuards>\n : SetupGuards<SetupConfigSchemas<TConfig>, {}>\n : SetupGuards<SetupConfigSchemas<TConfig>, {}>;\n\ntype SetupConfigDelays<TConfig> = TConfig extends { delays?: infer TDelays }\n ? TDelays extends Sources['delays']\n ? TDelays\n : {}\n : {};\n\nexport type SetupReturnFromConfig<\n TConfig extends AnySetupConfig,\n TSystemRegistry extends SystemRegistry = SystemRegistry\n> = SetupReturn<\n SetupConfigStates<TConfig>,\n SetupConfigSchemas<TConfig>,\n SetupConfigActions<TConfig>,\n SetupConfigActors<TConfig>,\n SetupConfigGuards<TConfig>,\n SetupConfigDelays<TConfig>,\n Extract<keyof SetupConfigDelays<TConfig>, string>,\n TSystemRegistry,\n TConfig extends { validator: infer TValidator extends ActorLogicValidator }\n ? TValidator\n : undefined\n>;\n\ntype SetupFunction<TSystemRegistry extends SystemRegistry = SystemRegistry> = {\n (): SetupReturn<\n Record<string, SetupStateSchema>,\n {},\n {},\n {},\n {},\n {},\n never,\n TSystemRegistry\n >;\n <\n const TSchemas extends SetupSchemas = {},\n const TStates extends Record<string, SetupStateSchema> = Record<\n string,\n SetupStateSchema\n >,\n TActionMap extends Sources['actions'] = {},\n TActorMap extends Sources['actors'] = {},\n TGuardMap extends Sources['guards'] = {},\n TDelayMap extends Sources['delays'] = {},\n const TValidator extends ActorLogicValidator | undefined = undefined\n >(\n config: SetupConfig<\n TSchemas,\n TStates,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TValidator\n > &\n RuntimeValidationConstraint<\n NoInfer<TSchemas>,\n NoInfer<TStates>,\n TValidator\n >\n ): SetupReturn<\n TStates,\n TSchemas,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n Extract<keyof TDelayMap, string>,\n TSystemRegistry,\n TValidator\n >;\n <const TConfig extends AnySetupConfig>(\n config: TConfig &\n SetupSourceCompanions<SetupConfigSchemas<TConfig>> &\n RuntimeValidationConstraint<\n NoInfer<SetupConfigSchemas<TConfig>>,\n NoInfer<SetupConfigStates<TConfig>>,\n TConfig extends { validator: infer TValidator } ? TValidator : undefined\n >\n ): SetupReturnFromConfig<TConfig, TSystemRegistry>;\n};\n\n/**\n * Sets up a state machine with state input schemas and other configuration.\n *\n * @example\n *\n * ```ts\n * import { setup } from 'xstate';\n * import z from 'zod';\n *\n * const s = setup({\n * states: {\n * loading: {\n * schemas: {\n * input: z.object({\n * userId: z.string()\n * })\n * }\n * }\n * }\n * });\n *\n * const machine = s.createMachine({\n * initial: {\n * target: 'loading',\n * input: { userId: '123' }\n * },\n * states: {\n * loading: {\n * entry: ({ input }) => {\n * console.log(input.userId);\n * }\n * }\n * }\n * });\n * ```\n */\nexport const setup = function setupImplementation<\n const TSchemas extends SetupSchemas = {},\n const TStates extends Record<string, SetupStateSchema> = Record<\n string,\n SetupStateSchema\n >,\n TActionMap extends Sources['actions'] = {},\n TActorMap extends Sources['actors'] = {},\n TGuardMap extends Sources['guards'] = {},\n TDelayMap extends Sources['delays'] = {},\n TValidator extends ActorLogicValidator | undefined =\n | ActorLogicValidator\n | undefined\n>(\n config: SetupConfig<\n TSchemas,\n TStates,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TValidator\n > = {}\n): SetupReturn<\n TStates,\n TSchemas,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n Extract<keyof TDelayMap, string>,\n SystemRegistry,\n TValidator\n> {\n const {\n validator,\n states = {} as TStates,\n schemas,\n actions,\n actors,\n guards,\n delays\n } = config;\n\n return {\n extend<\n const TExtendSchemas extends SetupSchemas = {},\n const TExtendStates extends Record<string, SetupStateSchema> = {},\n TExtendActionMap extends Sources['actions'] = {},\n TExtendActorMap extends Sources['actors'] = {},\n TExtendGuardMap extends Sources['guards'] = {},\n TExtendDelayMap extends Sources['delays'] = {},\n const TExtendValidator extends\n | ActorLogicValidator\n | undefined\n | InheritedValidator = InheritedValidator\n >(\n extension: SetupExtensionConfig<\n TSchemas,\n TStates,\n TValidator,\n TExtendSchemas,\n TExtendStates,\n TExtendActionMap,\n TExtendActorMap,\n TExtendGuardMap,\n TExtendDelayMap,\n TExtendValidator\n >\n ) {\n return setup(\n mergeSetupConfigs(config, extension as AnySetupConfig) as any\n ) as unknown as SetupReturn<\n MergeSourceMaps<TStates, TExtendStates>,\n MergeSourceMaps<TSchemas, TExtendSchemas>,\n MergeSourceMaps<TActionMap, TExtendActionMap>,\n MergeSourceMaps<TActorMap, TExtendActorMap>,\n MergeSourceMaps<TGuardMap, TExtendGuardMap>,\n MergeSourceMaps<TDelayMap, TExtendDelayMap>,\n | Extract<keyof TDelayMap, string>\n | Extract<keyof TExtendDelayMap, string>,\n SystemRegistry,\n ResolveExtendedValidator<TValidator, TExtendValidator>\n >;\n },\n createMachine(machineConfig) {\n const configSchemas = machineConfig.schemas;\n const mergedSchemas = mergeSchemas(configSchemas, schemas);\n const mergedStates = mergeStateSchemas(machineConfig.states, states);\n const mergedActions = mergeMaps(actions, machineConfig.actions);\n const mergedActors = mergeMaps(actors, machineConfig.actors);\n const mergedGuards = mergeMaps(guards, machineConfig.guards);\n const mergedDelays = mergeMaps(delays, machineConfig.delays);\n\n return new StateMachine(\n {\n ...machineConfig,\n ...(mergedSchemas ? { schemas: mergedSchemas } : undefined),\n ...(mergedStates ? { states: mergedStates } : undefined),\n ...(mergedActions ? { actions: mergedActions } : undefined),\n ...(mergedActors ? { actors: mergedActors } : undefined),\n ...(mergedGuards ? { guards: mergedGuards } : undefined),\n ...(mergedDelays ? { delays: mergedDelays } : undefined)\n } as any,\n undefined,\n validator\n ) as any;\n },\n createStateConfig(...args: unknown[]) {\n return args.length > 1 ? args[1] : args[0];\n },\n states,\n schemas: schemas ?? ({} as TSchemas)\n };\n} as SetupFunction;\n\ntype SystemBuilder<TSystemRegistry extends SystemRegistry> = {\n createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: Omit<ActorOptions<TLogic>, 'registryKey'> & {\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n } & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n ): Actor<TLogic>;\n get: SystemRuntime<TSystemRegistry>['get'];\n getAll: SystemRuntime<TSystemRegistry>['getAll'];\n inspect(\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription;\n setup: SetupFunction<TSystemRegistry>;\n};\n\nexport function createSystem<const TSystemRegistry extends SystemRegistry = {}>(\n _config: SystemConfig<TSystemRegistry> = {}\n): SystemBuilder<TSystemRegistry> {\n const runtimeRef: { current?: AnyActorSystem } = {};\n const pendingObservers: Array<{\n observer: Parameters<AnyActorSystem['inspect']>[0];\n subscription?: Subscription;\n active: boolean;\n }> = [];\n\n const flushObservers = () => {\n const runtime = runtimeRef.current;\n if (!runtime) {\n return;\n }\n\n for (const entry of pendingObservers) {\n if (entry.active && !entry.subscription) {\n entry.subscription = runtime.inspect(entry.observer);\n }\n }\n };\n\n return {\n createActor(logic, options) {\n const actor = createActorFromLogic(logic, {\n ...options,\n _systemRef: runtimeRef\n } as any);\n flushObservers();\n return actor as any;\n },\n get(key) {\n return runtimeRef.current?.get(key as any);\n },\n getAll() {\n return (runtimeRef.current?.getAll() ?? {}) as Partial<\n SystemActorMap<TSystemRegistry>\n >;\n },\n inspect(observer) {\n const runtime = runtimeRef.current;\n\n if (runtime) {\n return runtime.inspect(observer as any);\n }\n\n const entry: (typeof pendingObservers)[number] = {\n observer: observer as Parameters<AnyActorSystem['inspect']>[0],\n active: true\n };\n pendingObservers.push(entry);\n\n return {\n unsubscribe() {\n entry.active = false;\n entry.subscription?.unsubscribe();\n }\n };\n },\n setup: setup as SetupFunction<TSystemRegistry>\n };\n}\n\nfunction mergeMaps<TLeft, TRight>(\n left: TLeft | undefined,\n right: TRight | undefined\n): (TLeft & TRight) | undefined {\n return left || right ? ({ ...left, ...right } as TLeft & TRight) : undefined;\n}\n\nfunction mergeSchemas(\n left: SetupSchemas | undefined,\n right: SetupSchemas | undefined\n): SetupSchemas | undefined {\n if (!left && !right) {\n return undefined;\n }\n\n return {\n ...left,\n ...right,\n events: mergeMaps(left?.events, right?.events),\n internalEvents: mergeMaps(left?.internalEvents, right?.internalEvents),\n actions: mergeMaps(left?.actions, right?.actions),\n guards: mergeMaps(left?.guards, right?.guards),\n emitted: mergeMaps(left?.emitted, right?.emitted),\n children: mergeMaps(left?.children, right?.children)\n };\n}\n\n/**\n * Setup schemas win over inline config schemas (same precedence as root\n * `mergeSchemas`); setup states with no matching config state are skipped.\n */\nfunction mergeStateSchemas(\n configStates: Record<string, SetupStateSchema> | undefined,\n setupStates: Record<string, SetupStateSchema> | undefined\n): Record<string, SetupStateSchema> | undefined {\n if (!configStates || !setupStates) {\n return configStates;\n }\n\n return Object.fromEntries(\n Object.entries(configStates).map(([key, configState]) => {\n const setupState = setupStates[key];\n\n if (!setupState) {\n return [key, configState];\n }\n\n const schemas = mergeMaps(configState.schemas, setupState.schemas);\n const states = mergeStateSchemas(configState.states, setupState.states);\n\n return [\n key,\n {\n ...configState,\n ...(schemas ? { schemas } : undefined),\n ...(states ? { states } : undefined)\n }\n ];\n })\n );\n}\n\nfunction mergeSetupConfigs<\n TBase extends SetupConfig<any, any, any, any, any, any>,\n TExtension extends SetupConfig<any, any, any, any, any, any>\n>(base: TBase, extension: TExtension): TBase & TExtension {\n return {\n ...base,\n ...extension,\n schemas: mergeSchemas(base.schemas, extension.schemas),\n states: mergeMaps(base.states, extension.states),\n actions: mergeMaps(base.actions, extension.actions),\n actors: mergeMaps(base.actors, extension.actors),\n guards: mergeMaps(base.guards, extension.guards),\n delays: mergeMaps(base.delays, extension.delays)\n } as TBase & TExtension;\n}\n","import type { MachineSnapshot } from './State.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { AsyncActorLogic } from './actors/promise.ts';\nimport type { Actor, ProcessingStatus } from './createActor.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport { Spawner } from './spawn.ts';\nimport type { ActorSystemRuntime, AnyActorSystem, Clock } from './system.ts';\n\n// this is needed to make JSDoc `@link` work properly\n// oxlint-disable-next-line no-unused-vars\nimport type { SimulatedClock } from './SimulatedClock.ts';\nimport { Sources, Next_StateNodeConfig } from './types.v6.ts';\nimport { StandardSchemaV1 } from './schema.types.ts';\nimport { builtInActions } from './actions.ts';\n\nexport type Identity<T> = { [K in keyof T]: T[K] };\n\nexport type HomomorphicPick<T, K extends keyof any> = {\n [P in keyof T as P & K]: T[P];\n};\nexport type HomomorphicOmit<T, K extends keyof any> = {\n [P in keyof T as Exclude<P, K>]: T[P];\n};\n\nexport type Invert<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n\nexport type GetParameterizedParams<T extends ParameterizedObject | undefined> =\n T extends any ? ('params' extends keyof T ? T['params'] : undefined) : never;\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\nexport type NonReducibleUnknown = {} | null | undefined;\nexport type AnyFunction = (...args: any[]) => any;\n\ntype ReturnTypeOrValue<T> = T extends AnyFunction ? ReturnType<T> : T;\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNotNever<T> = [T] extends [never] ? false : true;\n\nexport type Compute<A> = { [K in keyof A]: A[K] } & unknown;\nexport type Prop<T, K> = K extends keyof T ? T[K] : never;\nexport type Values<T> = T[keyof T];\nexport type Elements<T> = T[keyof T & `${number}`];\nexport type Merge<M, N> = Omit<M, keyof N> & N;\nexport type IndexByProp<T extends Record<P, string>, P extends keyof T> = {\n [E in T as E[P]]: E;\n};\n\nexport type IndexByType<T extends { type: string }> = IndexByProp<T, 'type'>;\n\nexport type IsEmptyObject<T> = keyof T extends never ? true : false;\n\nexport type Equals<A1, A2> =\n (<A>() => A extends A2 ? true : false) extends <A>() => A extends A1\n ? true\n : false\n ? true\n : false;\nexport type IsAny<T> = Equals<T, any>;\nexport type Cast<A, B> = A extends B ? A : B;\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\nexport type DoNotInfer<T> = [T][T extends any ? 0 : any];\n/** @deprecated Use the built-in `NoInfer` type instead */\nexport type NoInfer<T> = DoNotInfer<T>;\nexport type LowInfer<T> = T & NonNullable<unknown>;\n\nexport type MetaObject = Record<string, any>;\n\nexport type Lazy<T> = () => T;\nexport type MaybeLazy<T> = T | Lazy<T>;\n\n/** The full definition of an event, with a string `type`. */\nexport type EventObject = {\n /** The type of event that is sent. */\n type: string;\n};\n\nexport type EventPayloadPattern<TEvent extends EventObject> = TEvent extends any\n ? Partial<Omit<TEvent, 'type'>>\n : never;\n\nexport interface AnyEventObject extends EventObject {\n [key: string]: any;\n}\n\nexport interface ParameterizedObject {\n type: string;\n params?: NonReducibleUnknown;\n}\n\nexport type UnifiedArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = {\n context: TContext;\n event: TExpressionEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n system: AnyActorSystem;\n} & OutputArg<TExpressionEvent>;\n\nexport type MachineContext = Record<string, any>;\n\ntype DoneEventType = 'xstate.done.actor' | 'xstate.done.state';\n\nexport type OutputArg<TEvent extends EventObject> = TEvent extends {\n type: DoneEventType;\n output: infer TOutput;\n}\n ? { output: TOutput }\n : { output: undefined };\n\nexport type ActionArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = UnifiedArg<TContext, TExpressionEvent, TEvent> & {\n children: Record<string, AnyActor>;\n};\n\nexport type InputFrom<T> =\n // Resolve the actor-logic contract first. Setup-created machines intersect\n // StateMachine with literal identity metadata; inferring StateMachine's\n // generic parameters through that intersection widens optional input.\n T extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TInput\n : T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TInput\n : never;\n\nexport type OutputFrom<T> =\n T extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? (TSnapshot & { status: 'done' })['output']\n : T extends ActorRef<infer TSnapshot, infer _TEvent, infer _TEmitted>\n ? (TSnapshot & { status: 'done' })['output']\n : never;\n\nexport type NoRequiredParams<T extends ParameterizedObject> = T extends any\n ? undefined extends T['params']\n ? T['type']\n : never\n : never;\n\nexport type ConditionalRequired<\n T,\n Condition extends boolean\n> = Condition extends true ? Required<T> : T;\n\nexport type WithDynamicParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n T extends ParameterizedObject\n> = T extends any\n ? ConditionalRequired<\n {\n type: T['type'];\n params?:\n | T['params']\n | (({\n context,\n event,\n output\n }: {\n context: TContext;\n event: TExpressionEvent;\n } & OutputArg<TExpressionEvent>) => T['params']);\n },\n undefined extends T['params'] ? false : true\n >\n : never;\n\nexport type StateKey = string | AnyMachineSnapshot;\n\nexport interface StateValueMap {\n [key: string]: StateValue | undefined;\n}\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\nexport type StateValue = string | StateValueMap;\n\nexport type TransitionTarget = SingleOrArray<string>;\n\nexport type TransitionContextPatch<TContext extends MachineContext> =\n Partial<TContext> & {\n call?: never;\n apply?: never;\n bind?: never;\n };\n\nexport type TransitionContextMapper<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n) => TransitionContextPatch<_TCtx>;\n\nexport interface TransitionConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n actions?: never;\n /** A shallow partial event pattern that must match before guards run. */\n matches?: EventPayloadPattern<TExpressionEvent>;\n guard?: unknown;\n reenter?: boolean;\n target?: TransitionTarget | undefined;\n context?:\n | TransitionContextPatch<TContext>\n | TransitionContextMapper<\n TContext,\n TExpressionEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n to?: TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >;\n meta?: TMeta;\n description?: string;\n /** @internal Overrides transition-domain selection for compiled formats. */\n _transitionDomain?: 'internal' | 'external';\n}\n\nexport interface InitialTransitionConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> extends TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n> {\n target: string;\n}\n\nexport type AnyTransitionConfig = TransitionConfig<\n any, // TContext\n any, // TExpressionEvent\n any, // TEvent\n any, // TEmitted\n any, // TMeta\n any, // TActionMap\n any, // TActorMap\n any, // TGuardMap\n any // TDelayMap\n>;\n\nexport interface InvokeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n id: string;\n\n registryKey: string | undefined;\n\n logic:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: TActorMap;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n /** The source of the actor logic to be invoked */\n src: AnyActorLogic | string;\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its final\n * top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an error\n * event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The duration (in ms) after which this invocation times out if it has not\n * completed.\n */\n timeout?: number | ((args: { context: TContext; event: TEvent }) => number);\n /** The transition to take when the invoke-level `timeout` expires. */\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n}\n\nexport type AnyInvokeDefinition = InvokeDefinition<\n MachineContext,\n EventObject,\n EventObject,\n MetaObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n>;\n\ntype Delay<TDelay extends string> = TDelay | number;\n\nexport type DelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in Delay<keyof TDelayMap & string>]?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >\n | TransitionConfigFunction<\n TContext,\n TEvent,\n TEvent,\n TODO,\n any,\n any,\n any,\n any,\n any\n >;\n};\n\nexport type StateTypes =\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'choice'\n | 'history'\n | ({} & string);\n\nexport type SingleOrArray<T> = readonly T[] | T;\n\nexport type StateNodesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNode<TContext, TEvent>;\n};\n\nexport type TransitionConfigTarget = string | undefined;\n\nexport type TransitionConfigOrTarget<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = SingleOrArray<\n | TransitionConfigTarget\n | TransitionConfig<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n | TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >\n>;\n\nexport type TransitionConfigFunction<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TMeta extends MetaObject,\n TInput = undefined,\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & { input: TInput },\n enq: EnqueueObject<TEvent, TEmitted, SystemRegistry, TActorMap>\n) => {\n target?: string | string[];\n // target?: keyof TSS['states'];\n context?: TransitionContextPatch<_TCtx>;\n reenter?: boolean;\n meta?: TMeta;\n input?: Record<string, unknown>;\n} | void;\n\ntype TransitionFunctionArgs<\n TContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n context: TContext;\n event: TCurrentEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n parent: UnknownActorRef | undefined;\n value: StateValue;\n children: Record<string, AnyActor>;\n system: AnyActorSystem;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n} & OutputArg<TCurrentEvent>;\n\nexport type AnyTransitionConfigFunction = TransitionConfigFunction<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type TransitionsConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in EventDescriptor<TEvent>]?: TransitionConfigOrTarget<\n TContext,\n ExtractEvent<TEvent, K>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n};\n\ntype PartialEventDescriptor<TEventType extends string> =\n TEventType extends `${infer TLeading}.${infer TTail}`\n ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}`\n : never;\n\nexport type EventDescriptor<TEvent extends EventObject> =\n | TEvent['type']\n | PartialEventDescriptor<TEvent['type']>\n | '*';\n\nexport type NormalizeDescriptor<TDescriptor extends string> =\n TDescriptor extends '*'\n ? string\n : TDescriptor extends `${infer TLeading}.*`\n ? `${TLeading}.${string}`\n : TDescriptor;\n\ntype EventTypeMatchesDescriptor<\n TEventType extends string,\n TDescriptor extends string\n> = TEventType extends NormalizeDescriptor<TDescriptor> ? true : false;\n\ntype IsInternalEventType<\n TEventType extends string,\n TDescriptors extends string\n> =\n // Descriptors that collapsed to broad `string` (an untyped machine's\n // config) cannot classify anything: without the guard they would match\n // every event type and reduce the sendable events to `never`.\n string extends TDescriptors\n ? false\n : true extends (\n TDescriptors extends any\n ? EventTypeMatchesDescriptor<TEventType, TDescriptors>\n : never\n )\n ? true\n : false;\n\ntype ExcludeInternalEvents<\n TEvent extends EventObject,\n TDescriptors extends string\n> = TEvent extends any\n ? IsInternalEventType<TEvent['type'], TDescriptors> extends true\n ? never\n : TEvent\n : never;\n\ntype InternalEventDescriptorsFromConfig<\n TEvent extends EventObject,\n TConfig\n> = TConfig extends { internalEvents?: readonly EventDescriptor<TEvent>[] }\n ? TConfig['internalEvents'] extends readonly (infer TDesc)[]\n ? Extract<TDesc, string>\n : never\n : never;\n\ntype InternalEventTypes<TInternalEvent extends EventObject> =\n TInternalEvent extends any ? TInternalEvent['type'] : never;\n\ntype SendableEventFromMachine<\n TEvent extends EventObject,\n TInternalEvent extends EventObject,\n TConfig\n> =\n IsAny<TInternalEvent> extends true\n ? TEvent\n : ExcludeInternalEvents<\n TEvent,\n | InternalEventTypes<TInternalEvent>\n | InternalEventDescriptorsFromConfig<TEvent, TConfig>\n >;\n\nexport type IsLiteralString<T extends string> = string extends T ? false : true;\n\ntype ActorsBySrc<TActor extends ProvidedActor> = {\n [A in TActor as A['src']]: A['logic'];\n};\n\ntype DistributeActors<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n _TAction extends ParameterizedObject,\n _TGuard extends ParameterizedObject,\n _TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TSpecificActor extends ProvidedActor\n> = TSpecificActor extends { src: infer TSrc }\n ?\n | Compute<\n {\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | TSrc\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => TSrc | TSpecificActor['logic']);\n\n /**\n * The unique identifier for the invoked machine. If not specified,\n * this will be the machine's own `id`, or the URL (from `src`).\n */\n id?: TSpecificActor['id'];\n\n // TODO: currently we do not enforce required inputs here\n // in a sense, we shouldn't - they could be provided within the `sources` object\n // how do we verify if the required input has been provided?\n input?:\n | Mapper<\n TContext,\n TEvent,\n InputFrom<TSpecificActor['logic']>,\n TEvent\n >\n | InputFrom<TSpecificActor['logic']>;\n /**\n * The transition to take upon the invoked child machine reaching\n * its final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<OutputFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent<SnapshotFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n } & { [K in RequiredActorOptions<TSpecificActor>]: unknown }\n >\n | {\n id?: never;\n registryKey?: string;\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n }\n : never;\n\nexport type InvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta,\n TActor\n >\n : {\n /**\n * The unique identifier for the invoked machine. If not specified, this\n * will be the machine's own `id`, or the URL (from `src`).\n */\n id?: string;\n\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its\n * final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n };\n\nexport type AnyInvokeConfig = InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TMeta\n>;\n\nexport type AnyStateNodeConfig = Next_StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n// Accept any StateNode instance regardless of generic parameters\n// Using a union type to handle variance issues with machine.resolveState\nexport type AnyStateNode =\n | StateNode<any, any>\n | StateNode<never, EventObject>\n | StateNode<any, EventObject>\n | StateNode<never, any>;\n\ntype LoosenMachineSnapshot<TSnapshot> =\n TSnapshot extends MachineSnapshot<any, any, any, any, any, any, any, any>\n ? Omit<TSnapshot, 'matches' | 'can'> & {\n matches(partialStateValue: StateValue): boolean;\n can(event: any): boolean;\n }\n : never;\n\nexport type AnyMachineSnapshot = LoosenMachineSnapshot<\n MachineSnapshot<any, any, any, any, any, any, any, any>\n>;\n\nexport interface AnyStateMachine extends AnyActorLogic {\n id: string;\n root: AnyStateNode;\n /** @internal */\n _hasEventlessTransitions?: boolean;\n /** @internal */\n idMap: Map<string, AnyStateNode>;\n options?: { maxIterations?: number };\n states: StateNodesConfig<any, any>;\n events: Array<EventDescriptor<any>>;\n sources: Sources;\n config: any;\n version?: string;\n schemas?: import('./types.v6.ts').AnyMachineSchemas;\n snapshotSchema: import('./machineVersion.types.ts').MachineSnapshotSchema;\n eventSchema: import('./machineVersion.types.ts').MachineEventSchema;\n provide(sources: any): AnyStateMachine;\n resolveState(config: any): any;\n /** @internal */\n _getPreInitialState(actorScope: AnyActorScope, initEvent: EventObject): any;\n getTransitionData(\n snapshot: any,\n event: any,\n actorScope: AnyActorScope,\n selectionResults?: Map<AnyTransitionDefinition, unknown>\n ): AnyTransitionDefinition[];\n /** @internal */\n _canTransition(snapshot: AnyMachineSnapshot, event: any): boolean;\n getStateNodeById(stateId: string): AnyStateNode;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n}\n\nexport type AnyStateConfig = StateConfig<any, AnyEventObject>;\n\nexport type DelayConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> = number | DelayExpr<TContext, TExpressionEvent>;\n\nexport type InitialContext<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject\n> = TContext | ContextFactory<TContext, TActorMap, TInput, TEvent>;\n\nexport type ContextFactory<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject = EventObject\n> = ({\n spawn,\n actors,\n input,\n self\n}: {\n spawn: Spawner;\n actors: TActorMap;\n input: TInput;\n self: ActorSelf<\n MachineSnapshot<\n [TContext] extends [never] ? any : TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => [TContext] extends [never] ? MachineContext : TContext;\n\nexport interface ProvidedActor {\n src: string;\n logic: UnknownActorLogic;\n id?: string | undefined; // `| undefined` is required here for compatibility with `exactOptionalPropertyTypes`, see #4613\n}\n\nexport interface SetupTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildrenMap extends Record<string, string>,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n context?: TContext;\n events?: TEvent;\n children?: TChildrenMap;\n tags?: TTag;\n input?: TInput;\n output?: TOutput;\n emitted?: TEmitted;\n meta?: TMeta;\n}\n\nexport interface MachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> extends SetupTypes<\n TContext,\n TEvent,\n // in machine types we currently don't support `TChildren`\n // and IDs can still be configured through `TActor['id']`\n never,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta\n> {\n actors?: TActor;\n actions?: TAction;\n guards?: TGuard;\n delays?: TDelay;\n meta?: TMeta;\n}\n\nexport interface HistoryStateNode<\n TContext extends MachineContext\n> extends StateNode<TContext> {\n history: 'shallow' | 'deep';\n target: string | undefined;\n}\n\nexport type HistoryValue = Record<string, Array<AnyStateNode>>;\n\nexport type PersistedHistoryValue = Record<string, Array<{ id: string }>>;\n\nexport type AnyHistoryValue = HistoryValue;\n\nexport type StateFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> = T extends AnyStateMachine\n ? StateSnapshotFromMachine<T>\n : T extends (...args: any[]) => AnyStateMachine\n ? StateSnapshotFromMachine<ReturnType<T>>\n : never;\n\nexport type StateValueFromStateSchema<T extends StateSchema> =\n StateSchema extends T\n ? StateValue\n : ToStateValue<T> extends infer TStateValue\n ? TStateValue extends StateValue\n ? TStateValue\n : StateValue\n : StateValue;\n\ntype MatchingStateValueForStateFrom<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends StateValueMap\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends StateValueMap\n ? TStateValue extends StateValueMap\n ? MatchingStateValueMapForStateFrom<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ntype MatchingStateValueMapForStateFrom<\n TStateValue extends StateValueMap,\n TTestStateValue extends StateValueMap\n> = false extends {\n [K in keyof TTestStateValue & string]: K extends keyof TStateValue\n ? IsNever<\n MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n > extends true\n ? false\n : true\n : false;\n}[keyof TTestStateValue & string]\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype StateSnapshotFromStateValue<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema,\n TAllStateValue extends StateValue = TStateValue\n> = TStateValue extends unknown\n ? Omit<\n MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TStateValue>,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n 'matches'\n > & {\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches(partialStateValue: StateValue): boolean;\n }\n : never;\n\ntype StateSnapshotFromMachine<T extends AnyStateMachine> =\n SnapshotFrom<T> extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer TStateSchema\n >\n ? StateSnapshotFromStateValue<\n TContext,\n TEvent,\n TChildren,\n StateValueFromStateSchema<TStateSchema>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n StateValueFromStateSchema<TStateSchema>\n >\n : SnapshotFrom<T>;\n\nexport interface DoneActorEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.actor';\n output: TOutput;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorActorEvent<\n TErrorData = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.error.actor';\n error: TErrorData;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorPlatformEvent<\n TErrorData = unknown,\n TKind extends string = string\n> extends EventObject {\n type: `xstate.error.${TKind}`;\n error: TErrorData;\n}\n\nexport type ErrorEvent = ErrorActorEvent | ErrorPlatformEvent;\n\nexport interface SnapshotEvent<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>\n> extends EventObject {\n type: 'xstate.snapshot.actor';\n actorId: string;\n sessionId: string;\n snapshot: TSnapshot;\n}\n\nexport interface DoneStateEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.state';\n stateId: TId;\n output: TOutput;\n}\n\nexport interface AfterEvent extends EventObject {\n type: 'xstate.after';\n delay: number | string;\n stateId: string;\n}\n\nexport interface TimeoutEvent extends EventObject {\n type: 'xstate.timeout';\n stateId: string;\n}\n\nexport interface ActorTimeoutEvent extends EventObject {\n type: 'xstate.timeout.actor';\n actorId: string;\n sessionId?: string;\n}\n\nexport enum SpecialTargets {\n Internal = '#_internal'\n}\n\nexport type Mapper<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TResult,\n TEvent extends EventObject,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n args: {\n context: _TCtx;\n event: TExpressionEvent;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n Record<string, AnyActorRef>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n } & OutputArg<TExpressionEvent>\n) => TResult;\n\nexport interface TransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends Omit<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >,\n 'target' | 'to'\n> {\n target: ReadonlyArray<AnyStateNode> | undefined;\n source: AnyStateNode;\n reenter: boolean;\n eventType: EventDescriptor<TEvent>;\n /** @internal Additional runtime matching for generated transitions. */\n _eventMatcher?: (event: EventObject, snapshot: AnyMachineSnapshot) => boolean;\n to?: ((...args: any[]) => any) | undefined;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: any;\n event: any;\n output: any;\n }) => Record<string, unknown>);\n}\n\nexport type AnyTransitionDefinition = TransitionDefinition<any, any>;\n\nexport type InitialTransitionDefinition = {\n source: AnyStateNode;\n target: AnyStateNode[] | undefined;\n reenter?: boolean;\n eventType?: EventDescriptor<any>;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: MachineContext;\n event: EventObject;\n }) => Record<string, unknown>);\n to?: ((...args: any[]) => any) | undefined;\n};\n\nexport type TransitionDefinitionMap<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in EventDescriptor<TEvent>]: Array<\n TransitionDefinition<TContext, ExtractEvent<TEvent, K>>\n >;\n};\n\nexport type DelayExpr<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = (args: {\n context: [TContext] extends [never] ? any : TContext;\n event: TEvent;\n stateNode: AnyStateNode;\n}) => number;\n\nexport interface DelayedTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n delay: number | string | DelayExpr<TContext, TEvent>;\n}\n\nexport interface StateLike<TContext extends MachineContext> {\n value: StateValue;\n context: TContext;\n event: EventObject;\n}\n\nexport interface StateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n context: TContext;\n historyValue?: HistoryValue;\n /** @internal */\n _nodes: Array<AnyStateNode>;\n /** @internal */\n value?: StateValue;\n children: Record<string, AnyActorRef | undefined>;\n timers?: Record<string, LogicalTimer>;\n status: SnapshotStatus;\n output?: any;\n error?: unknown;\n /** @internal */\n _stateInputs?: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId?: number;\n /**\n * Deterministic generated-child-id counters owned by this snapshot, keyed\n * by src prefix.\n *\n * @internal\n */\n _nextActorIds?: Record<string, number>;\n machine?: StateMachine<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n}\n\n/** A deterministic delayed-delivery declaration owned by a logic snapshot. */\nexport interface LogicalTimer {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n /** `self` or the logical actor that will receive `event`. */\n target: 'self' | AnyActor;\n /**\n * The timer's wall-clock start, stamped at persist time by a running\n * wall-clock actor and carried through restore so re-persisting keeps the\n * original deadline.\n */\n startedAt?: number;\n}\n\n/** The logical input delivered to a timer's source when its runtime delay ends. */\nexport interface TimerEvent extends EventObject {\n type: 'xstate.timer';\n id: string;\n}\n\ndeclare const persistedSnapshotLogic: unique symbol;\n\ntype PersistedSnapshotLogicIdentity<TLogic> = TLogic extends {\n readonly id: infer TId extends string;\n}\n ? {\n readonly id: TId;\n readonly version: TLogic extends {\n readonly version: infer TVersion extends string;\n }\n ? TVersion\n : string;\n }\n : never;\n\n/** A persisted snapshot tied to a versioned actor logic identity. */\nexport type PersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: PersistedSnapshotLogicIdentity<TLogic>;\n};\n\n/**\n * A persisted snapshot restorable into the given actor logic: any snapshot\n * created by logic with the same machine `id` is accepted, regardless of\n * version (version mismatches are handled at runtime, e.g. by `migrate`).\n */\nexport type RestorablePersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: TLogic extends {\n readonly id: infer TId extends string;\n }\n ? { readonly id: TId; readonly version: string }\n : never;\n};\n\nexport interface ActorOptions<TLogic extends AnyActorLogic> {\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n *\n * @remarks\n * You can create your own “clock”. The clock interface supports these\n * methods:\n *\n * - `now` - optional; returns the current time in milliseconds\n * - `setTimeout` - same arguments as `window.setTimeout(fn, timeout)`\n * - `clearTimeout` - same arguments as `window.clearTimeout(id)`\n *\n * By default, `Date.now`, native `setTimeout`, and native `clearTimeout` are\n * used.\n *\n * For testing, XState provides `SimulatedClock`.\n * @see {@link Clock}\n * @see {@link SimulatedClock}\n */\n clock?: Clock;\n /**\n * Specifies the logger to be used for `log(...)` actions. Defaults to the\n * native `console.log(...)` method.\n */\n logger?: (...args: any[]) => void;\n parent?: AnyActor;\n /** @internal */\n syncSnapshot?: boolean;\n /** @internal */\n _systemRef?: { current?: AnyActorSystem };\n /** @internal */\n _sessionId?: string;\n /** @internal */\n _inert?: boolean;\n /** The custom `id` for referencing this service. */\n id?: string;\n /** @deprecated Use `inspect` instead. */\n devTools?: never;\n\n /** The registry key to register this actor under. */\n registryKey?: string;\n /** The input data to pass to the actor. */\n input?: InputFrom<TLogic>;\n\n /**\n * Initializes actor logic from a specific persisted internal state.\n *\n * @remarks\n * If the state is compatible with the actor logic, when the actor is started\n * it will be at that persisted state. Actions from machine actors will not be\n * re-executed, because they are assumed to have been already executed.\n * However, invocations will be restarted, and spawned actors will be restored\n * recursively.\n *\n * Can be generated with {@link Actor.getPersistedSnapshot}.\n * @see https://stately.ai/docs/persistence\n */\n snapshot?: Snapshot<unknown> &\n Partial<RestorablePersistedSnapshotFor<DoNotInfer<TLogic>>>;\n\n /** @deprecated Use `snapshot` instead. */\n state?: Snapshot<unknown>;\n\n /** The source actor logic. */\n src?: string | AnyActorLogic;\n\n /**\n * A callback function or observer object which can be used to inspect actor\n * system updates.\n *\n * @remarks\n * If a callback function is provided, it can accept an inspection event\n * argument. The inspection protocol has two event types:\n *\n * - `@xstate.actor` - An actor ref was created in the system (announces actor\n * topology: identity + parent).\n * - `@xstate.transition` - An actor transitioned. Carries every facet of the\n * transition with flat, always-present fields: `event`, `snapshot`,\n * `sourceRef`, `microsteps`, executed `actions`, and `sent`/scheduled\n * events.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * });\n *\n * const actor = createActor(machine, {\n * inspect: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef, inspectionEvent.parentRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * // flat, always-present facets — no narrowing required\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * });\n * ```\n *\n * Alternately, an observer object (`{ next?, error?, complete? }`) can be\n * provided:\n *\n * @example\n *\n * ```ts\n * const actor = createActor(machine, {\n * inspect: {\n * next: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(\n * inspectionEvent.actorRef,\n * inspectionEvent.parentRef\n * );\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * }\n * });\n * ```\n */\n inspect?:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void);\n}\n\nexport type AnyActor = ActorInstance<any, any, any, any>;\n\n/** @deprecated Use `AnyActor` instead. */\nexport type AnyInterpreter = AnyActor;\n\n// Based on RxJS types\nexport type Observer<T> = {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n};\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface Readable<T> extends Subscribable<T> {\n get: () => T;\n}\n\nexport interface InteropObservable<T> {\n [Symbol.observable]: () => InteropSubscribable<T>;\n}\n\nexport interface InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n}\n\nexport interface Subscribable<T> extends InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n subscribe(\n next: (value: T) => void,\n error?: (error: any) => void,\n complete?: () => void\n ): Subscription;\n}\n\ntype EventDescriptorMatches<\n TEventType extends string,\n TNormalizedDescriptor\n> = TEventType extends TNormalizedDescriptor\n ? true\n : TNormalizedDescriptor extends TEventType\n ? true\n : false;\n\nexport type ExtractEvent<\n TEvent extends EventObject,\n TDescriptor extends EventDescriptor<TEvent>\n> = string extends TEvent['type']\n ? TEvent\n : NormalizeDescriptor<TDescriptor> extends infer TNormalizedDescriptor\n ? TEvent extends any\n ? // true is the check type here to match both true and boolean\n true extends EventDescriptorMatches<\n TEvent['type'],\n TNormalizedDescriptor\n >\n ? TEvent\n : never\n : never\n : never;\n\nexport interface BaseActorRef<TEvent extends EventObject> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorLike<\n TCurrent,\n TEvent extends EventObject\n> extends Subscribable<TCurrent> {\n send: (event: TEvent) => void;\n}\n\n/**\n * A consumer-facing actor handle.\n *\n * `ActorRef` describes the contract a consumer needs: which events can be sent\n * to the actor, which snapshot it publishes for observation, and which emitted\n * events can be listened to. It intentionally does not expose lifecycle control\n * or runtime internals. A concrete `Actor` satisfies this interface, so APIs\n * should accept `ActorRef` whenever they only need to send events, read\n * snapshots, or listen to emitted events.\n */\nexport interface ActorRef<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends Subscribable<TSnapshot>, InteropObservable<TSnapshot> {\n send: (event: TSendEvent) => void;\n getSnapshot: () => TSnapshot;\n on: <TType extends TEmitted['type'] | '*'>(\n type: TType,\n handler: (\n emitted: TEmitted & (TType extends '*' ? unknown : { type: TType })\n ) => void\n ) => Subscription;\n}\n\ntype EventPayload<\n TEvent extends EventObject,\n TType extends TEvent['type']\n> = HomomorphicOmit<ExtractEvent<TEvent, TType>, 'type'>;\n\nexport type ActorTrigger<TEvent extends EventObject> = {\n [K in TEvent['type']]: {} extends EventPayload<TEvent, K>\n ? () => void\n : (payload: EventPayload<TEvent, K>) => void;\n};\n\n/**\n * Runtime-only actor capabilities.\n *\n * These members are needed by the interpreter, scheduler, inspection, and child\n * management code. Public consumer APIs should prefer `ActorRef` unless they\n * genuinely need lifecycle control such as starting, stopping, or accessing\n * system-owned runtime state.\n */\nexport interface ActorRuntime<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n _TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n /** The unique identifier for this actor relative to its parent. */\n id: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`.\n */\n readonly address: string;\n /**\n * The globally unique process ID for this invocation.\n *\n * @remarks\n * This is only defined once the actor is started.\n */\n sessionId: string | undefined;\n /** @internal */\n _send: (event: TEvent) => void;\n start: () => this;\n getPersistedSnapshot: () => Snapshot<unknown>;\n stop: () => void;\n toJSON?: () => any;\n _parent?: any;\n system: any;\n /** @internal Emits the transition inspection event for `snapshot`. */\n _inspectTransition(snapshot: TSnapshot, event: EventObject): void;\n /** @internal */\n _processingStatus: ProcessingStatus;\n /** @internal */\n _isRunning: () => boolean;\n src: string | AnyActorLogic;\n /** Registry key used by the actor system receptionist. */\n registryKey?: string;\n trigger: ActorTrigger<TSendEvent>;\n select<TSelected>(\n selector: (snapshot: TSnapshot) => TSelected,\n equalityFn?: (a: TSelected, b: TSelected) => boolean\n ): Readable<TSelected>;\n}\n\n/**\n * A concrete actor instance type.\n *\n * `ActorInstance` combines the consumer `ActorRef` contract with runtime\n * lifecycle capabilities. Values returned by `createActor(...)` and\n * `spawn(...)` naturally satisfy narrower `ActorRef` contracts.\n */\nexport interface ActorInstance<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends\n ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent>,\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent> {}\n\n/**\n * The actor's own full self handle.\n *\n * Internals and action/guard sources receive this shape because `self` can\n * participate in runtime-owned behavior while still being usable wherever an\n * `ActorRef` is expected.\n */\nexport type ActorSelf<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> = ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent> &\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent>;\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\nexport type ActorRefFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer _TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any //TStateSchema\n >,\n TEvent,\n TEmitted,\n SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n >\n : T extends Promise<infer U>\n ? ActorRefFrom<AsyncActorLogic<U>>\n : T extends ActorLogic<\n infer TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? ActorRef<TSnapshot, TEvent, TEmitted>\n : never;\n\nexport type SendableEventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n : EventFromLogic<TLogic>;\n\ntype OpaqueMachineSnapshot<TSnapshot extends Snapshot<unknown>> =\n TSnapshot extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer _TStateSchema\n >\n ? MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any\n >\n : TSnapshot;\n\nexport type ActorRefFromLogic<T extends AnyActorLogic> = ActorRef<\n OpaqueMachineSnapshot<SnapshotFrom<T>>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\nexport interface AnyActorRef extends Subscribable<any>, InteropObservable<any> {\n send(event: any): void;\n getSnapshot(): any;\n on(type: string, handler: (emitted: any) => void): Subscription;\n}\n\n/** The concrete actor instance type produced from actor logic. */\nexport type ActorFromLogic<T extends AnyActorLogic> = ActorInstance<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\ntype SendableEventFromActorRef<\n TActorRef,\n TFallback extends EventObject = AnyEventObject\n> = [NonNullable<TActorRef>] extends [never]\n ? TFallback\n : NonNullable<TActorRef> extends infer TNonNullableActorRef\n ? TNonNullableActorRef extends { send: (event: infer TEvent) => void }\n ? [TEvent] extends [never]\n ? TFallback\n : TEvent extends EventObject\n ? TEvent\n : TFallback\n : never\n : never;\n\nexport type ActorRefLike = Pick<AnyActor, 'sessionId' | 'send' | 'getSnapshot'>;\n\nexport type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;\n\nexport type DevToolsAdapter = (service: AnyActor) => void;\n\nexport type MachineSourcesFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer TActionMap,\n infer TActorMap,\n infer TGuardMap,\n infer TDelayMap\n >\n ? {\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n }\n : never;\n\nexport interface ActorScope<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem = AnyActorSystem,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n self: ActorSelf<TSnapshot, TEvent, TEmitted, TSendEvent>;\n id: string;\n sessionId: string;\n logger: (...args: any[]) => void;\n defer: (fn: () => void) => void;\n emit: (event: TEmitted) => void | PromiseLike<void>;\n system: TSystem;\n stopChild: (child: AnyActor) => void;\n actionExecutor: ActionExecutor;\n}\n\nexport type AnyActorScope = ActorScope<\n any, // TSnapshot\n any, // TEvent\n AnyActorSystem,\n any, // TEmitted\n any // TSendEvent\n>;\n\nexport type SnapshotStatus = 'active' | 'done' | 'error' | 'stopped';\n\nexport type Snapshot<TOutput> =\n | {\n status: 'active';\n output: undefined;\n error: undefined;\n }\n | {\n status: 'done';\n output: TOutput;\n error: undefined;\n }\n | {\n status: 'error';\n output: undefined;\n error: unknown;\n }\n | {\n status: 'stopped';\n output: undefined;\n error: undefined;\n };\n\nexport type ActorLogicTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect = ExecutableActionObject\n> = [nextSnapshot: TSnapshot, effects: TEffect[]];\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\nexport interface ActorLogic<\n in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope[\"self\"][\"getSnapshot\"]`\n in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope[\"self\"][\"send\"]`\n in TInput = NonReducibleUnknown,\n TSystem extends AnyActorSystem = AnyActorSystem,\n in out TEmitted extends EventObject = EventObject // it's invariant because it's also aprt of `ActorScope[\"self\"][\"on\"]`\n> {\n /** The initial setup/configuration used to create the actor logic. */\n config?: unknown;\n /** Optional runtime validator for pure calculation boundaries. */\n validator?: import('./validation.types.ts').ActorLogicValidator;\n /**\n * Transition function that processes the current state and an incoming event\n * to produce a new state and effects.\n *\n * @param snapshot - The current state.\n * @param event - The incoming event.\n * @param actorScope - The actor scope.\n * @returns A tuple of the next state and effects.\n */\n transition: (\n snapshot: TSnapshot,\n event: TEvent,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Transition function that produces the initial state and effects.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns A tuple of the initial state and effects.\n */\n initialTransition: (\n input: TInput,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Called to provide the initial state of the actor.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns The initial state.\n */\n getInitialSnapshot: (\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>,\n input: TInput\n ) => TSnapshot;\n /**\n * Called when Actor is created to restore the internal state of the actor\n * given a persisted state. The persisted state can be created by\n * `getPersistedSnapshot`.\n *\n * @param persistedState - The persisted state to restore from.\n * @param actorScope - The actor scope.\n * @returns The restored state.\n */\n restoreSnapshot?: (\n persistedState: Snapshot<unknown>,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called when the actor is started.\n *\n * @param snapshot - The starting state.\n * @param actorScope - The actor scope.\n * @param options - Start metadata, including whether the snapshot was\n * restored.\n */\n start?: (\n snapshot: TSnapshot,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>,\n options?: { restored: boolean }\n ) => void;\n /**\n * Obtains the internal state of the actor in a representation which can be be\n * persisted. The persisted state can be restored by `restoreSnapshot`.\n *\n * @param snapshot - The current state.\n * @returns The a representation of the internal state to be persisted.\n */\n getPersistedSnapshot: (\n snapshot: TSnapshot,\n options?: unknown\n ) => Snapshot<unknown>;\n /**\n * Returns an event that the actor should transition with to recover from an\n * execution error, or `undefined` if the given snapshot cannot handle it.\n * Actor logic without error-recovery semantics can omit this.\n */\n getExecutionErrorEvent?: (\n snapshot: TSnapshot,\n error: unknown\n ) => TEvent | undefined;\n}\n\nexport interface AnyActorLogic {\n config?: unknown;\n validator?: import('./validation.types.ts').ActorLogicValidator;\n transition(\n snapshot: any,\n event: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n initialTransition(\n input: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n getInitialSnapshot(actorScope: any, input: any): any;\n restoreSnapshot?(persistedState: Snapshot<unknown>, actorScope: any): any;\n start?(snapshot: any, actorScope: any, options?: { restored: boolean }): void;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n getExecutionErrorEvent?(snapshot: any, error: unknown): any;\n}\n\nexport type UnknownActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n AnyActorSystem,\n any // emitted\n>;\n\nexport type SnapshotFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends ActorRef<infer TSnapshot, infer _, infer __>\n ? TSnapshot\n : R extends Actor<infer TLogic>\n ? SnapshotFrom<TLogic>\n : R extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TSnapshot\n : R extends ActorScope<\n infer TSnapshot,\n infer _TEvent,\n infer _TEmitted,\n infer _TSystem\n >\n ? TSnapshot\n : never\n : never;\n\nexport type EventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TEvent\n : never;\n\nexport type EmittedFrom<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEmitted\n : [TLogic] extends [AnyStateMachine]\n ? AnyEventObject\n : TLogic extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? TEmitted\n : AnyEventObject;\n\ntype ResolveEventType<T> = T extends infer R\n ? R extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEvent\n : R extends MachineSnapshot<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends ActorRef<infer _TSnapshot, infer TEvent, infer _TEmitted>\n ? TEvent\n : never\n : never;\n\nexport type EventFrom<\n T,\n K extends Prop<TEvent, 'type'> = never,\n TEvent extends EventObject = ResolveEventType<T>\n> = IsNever<K> extends true ? TEvent : ExtractEvent<TEvent, K>;\n\nexport type ContextFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TContext\n : T extends MachineSnapshot<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : T extends Actor<infer TActorLogic>\n ? TActorLogic extends AnyStateMachine\n ? ContextFrom<TActorLogic>\n : never\n : never;\n\nexport type InferEvent<E extends EventObject> = {\n [T in E['type']]: { type: T } & Extract<E, { type: T }>;\n}[E['type']];\n\nexport type TODO = any;\n\nexport type StateValueFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['matches']\n>[0];\n\nexport type TagsFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['hasTag']\n>[0];\n\nexport interface ActorSystemInfo {\n actors: Record<string, AnyActorRef>;\n}\n\nexport type SystemRegistry = Record<string, AnyActorLogic>;\n\nexport type RegistryKeyForLogic<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = string extends keyof TSystemRegistry\n ? string\n : Values<{\n [K in keyof TSystemRegistry &\n string]: ActorRefFromLogic<TLogic> extends ActorRefFromLogic<\n TSystemRegistry[K]\n >\n ? K\n : never;\n }>;\n\nexport type RequiredActorOptions<TActor extends ProvidedActor> =\n | (undefined extends TActor['id'] ? never : 'id')\n | (undefined extends InputFrom<TActor['logic']> ? never : 'input');\n\nexport type RequiredLogicInput<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\ntype ExtractLiteralString<T extends string | undefined> = T extends string\n ? string extends T\n ? never\n : T\n : never;\n\ntype ToConcreteChildren<TActor extends ProvidedActor> = {\n [A in TActor as ExtractLiteralString<A['id']>]?: ActorFromLogic<A['logic']>;\n};\n\n// Actors that don't have literal string IDs — these are the only ones\n// that should appear in the index signature fallback, since actors with\n// literal IDs are already covered by ToConcreteChildren.\ntype NonConcreteActors<TActor extends ProvidedActor> = TActor extends any\n ? ExtractLiteralString<TActor['id']> extends never\n ? TActor\n : never\n : never;\n\nexport type ToChildren<TActor extends ProvidedActor> =\n // only proceed further if all configured `src`s are literal strings\n string extends TActor['src']\n ? // TODO: replace `AnyActorRef` with `UnknownActorRef`~\n // or maybe even `TActor[\"logic\"]` since it's possible to configure `{ src: string; logic: SomeConcreteLogic }`\n // TODO: consider adding `| undefined` here\n Record<string, AnyActor>\n : Compute<\n ToConcreteChildren<TActor> &\n {\n include: {\n [id: string]: NonConcreteActors<TActor> extends never\n ? AnyActor | undefined\n : NonConcreteActors<TActor> extends any\n ?\n | ActorFromLogic<NonConcreteActors<TActor>['logic']>\n | undefined\n : never;\n };\n exclude: unknown;\n }[NonConcreteActors<TActor> extends never ? 'exclude' : 'include']\n >;\n\nexport type StateSchema = {\n id?: string;\n route?: unknown;\n states?: Record<string, StateSchema>;\n contextSchema?: StandardSchemaV1;\n outputSchema?: StandardSchemaV1;\n input?: unknown;\n\n // Other types\n // Needed because TS treats objects with all optional properties as a \"weak\" object\n // https://github.com/statelyai/xstate/issues/5031\n type?: unknown;\n history?: unknown;\n target?: unknown;\n invoke?: unknown;\n on?: unknown;\n entry?: unknown;\n exit?: unknown;\n onDone?: unknown;\n onError?: unknown;\n timeout?: unknown;\n onTimeout?: unknown;\n after?: unknown;\n always?: unknown;\n choice?: unknown;\n meta?: unknown;\n output?: unknown;\n tags?: unknown;\n description?: unknown;\n};\n\nexport type StateSchemaFrom<T extends AnyStateMachine> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TStateSchema\n : never;\n\nexport type StateId<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> =\n | (TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: StateId<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n : never);\n\n/** Maps state IDs to their input types based on the StateSchema. */\nexport type StateIdInputs<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> = {\n [K in TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`]: TSchema['input'] extends undefined\n ? undefined\n : TSchema['input'];\n} & (TSchema['states'] extends Record<string, StateSchema>\n ? UnionToIntersection<\n Values<{\n [K in keyof TSchema['states'] & string]: StateIdInputs<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n >\n : {});\n\ntype UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (\n k: infer I\n) => void\n ? I\n : never;\n\ntype ContextFromStateSchema<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext\n> = TSchema['contextSchema'] extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema['contextSchema']> & MachineContext\n : TFallbackContext;\n\ntype ContextFromChildStateValue<\n TChildSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TChildValue\n> = ContextFromStateSchema<TChildSchema, TFallbackContext> &\n StateContextFromStateValue<\n TChildSchema,\n ContextFromStateSchema<TChildSchema, TFallbackContext>,\n TChildValue\n >;\n\nexport type StateContextFromStateValue<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TStateValue\n> = (TSchema['states'] extends Record<string, StateSchema>\n ? TStateValue extends keyof TSchema['states'] & string\n ? ContextFromStateSchema<TSchema['states'][TStateValue], TFallbackContext>\n : TStateValue extends Record<string, unknown>\n ? UnionToIntersection<\n Values<{\n [K in keyof TStateValue &\n keyof TSchema['states'] &\n string]: ContextFromChildStateValue<\n TSchema['states'][K],\n TFallbackContext,\n NonNullable<TStateValue[K]>\n >;\n }>\n >\n : TFallbackContext\n : TFallbackContext) &\n MachineContext;\n\nexport type RoutableStateId<TSchema extends StateSchema> =\n | (TSchema extends { route: any; id: string } ? `#${TSchema['id']}` : never)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: RoutableStateId<\n TSchema['states'][K]\n >;\n }>\n : never);\n\nexport interface StateMachineTypes {\n context: MachineContext;\n events: EventObject;\n actors: ProvidedActor;\n actions: ParameterizedObject;\n guards: ParameterizedObject;\n delays: string;\n tags: string;\n emitted: EventObject;\n}\n\n/** @deprecated */\nexport interface ResolvedStateMachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TEmitted extends EventObject = EventObject\n> {\n context: TContext;\n events: TEvent;\n actors: TActor;\n actions: TAction;\n guards: TGuard;\n delays: TDelay;\n tags: TTag;\n emitted: TEmitted;\n}\n\nexport type GetConcreteByKey<\n T,\n TKey extends keyof T,\n TValue extends T[TKey]\n> = T & Record<TKey, TValue>;\n\ntype _GroupStateKeys<\n T extends StateSchema,\n S extends keyof T['states']\n> = S extends any\n ? T['states'][S] extends { type: 'history' }\n ? [never, never]\n : T extends { type: 'parallel' }\n ? [S, never]\n : T['states'][S] extends { states: Record<string, StateSchema> }\n ? [S, never]\n : [never, S]\n : never;\n\ntype GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {\n nonLeaf: _GroupStateKeys<T, S & string>[0];\n leaf: _GroupStateKeys<T, S & string>[1];\n};\n\nexport type ToStateValue<T extends StateSchema> = T extends {\n states: Record<infer S, any>;\n}\n ? IsNever<S> extends true\n ? {}\n :\n | GroupStateKeys<T, S>['leaf']\n | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false\n ? T extends { type: 'parallel' }\n ? {\n [K in GroupStateKeys<T, S>['nonLeaf']]: ToStateValue<\n T['states'][K]\n >;\n }\n : Compute<\n Values<{\n [K in GroupStateKeys<T, S>['nonLeaf']]: {\n [StateKey in K]: ToStateValue<T['states'][K]>;\n };\n }>\n >\n : never)\n : {};\n\nexport interface BaseExecutableActionObject {\n params: NonReducibleUnknown;\n args: unknown[];\n exec(\n runtime?: Partial<ActorSystemRuntime>\n ): void | PromiseLike<void> | undefined;\n}\n\n/** The terminal result published when an actor completes or errors. */\nexport type ActorTermination =\n | { status: 'done'; output: unknown; error: undefined }\n | { status: 'error'; output: undefined; error: unknown };\n\nexport interface CustomExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'action';\n type: TType;\n action: ((...args: any[]) => void | PromiseLike<void>) | undefined;\n}\n\nexport interface EmitExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'emit';\n type: TType;\n source: AnyActor;\n event: EventObject & { type: TType };\n}\n\nexport interface SpawnExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.spawn';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n logic: AnyActorLogic;\n src: string | AnyActorLogic;\n input: unknown;\n args: Parameters<(typeof builtInActions)['@xstate.spawn']>;\n}\n\nexport interface StartExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.start';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.start']>;\n}\n\nexport interface RaiseExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.raise';\n source: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.raise']>;\n}\n\nexport interface SendToExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.sendTo';\n source: AnyActor;\n target: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.sendTo']>;\n}\n\nexport interface CancelExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.cancel';\n source: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.cancel']>;\n}\n\nexport interface StopExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.stop';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.stop']>;\n}\n\n/** An executable effect that publishes an actor's terminal result. */\nexport type TerminateExecutableActionObject = BaseExecutableActionObject & {\n kind: 'builtin';\n type: '@xstate.terminate';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.terminate']>;\n} & ActorTermination;\n\nexport type BuiltInExecutableActionObject = Values<{\n '@xstate.spawn': SpawnExecutableActionObject;\n '@xstate.start': StartExecutableActionObject;\n '@xstate.raise': RaiseExecutableActionObject;\n '@xstate.sendTo': SendToExecutableActionObject;\n '@xstate.cancel': CancelExecutableActionObject;\n '@xstate.stop': StopExecutableActionObject;\n '@xstate.terminate': TerminateExecutableActionObject;\n}>;\n\nexport type SpecialExecutableAction = BuiltInExecutableActionObject;\n\ntype TransitionExecutableActionObject<TType extends string = never> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType | (string & {})>;\n\ntype KnownSourceKeys<TSourceMap> = string extends keyof TSourceMap\n ? never\n : Extract<keyof TSourceMap, string>;\n\nexport type ExecutableActionObjectFromLogic<T extends AnyActorLogic> =\n T extends StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n infer TActionMap,\n any,\n any,\n any\n >\n ? TransitionExecutableActionObject<KnownSourceKeys<TActionMap>>\n : ExecutableActionObject;\n\nexport type ExecutableActionObject<TType extends string = string & {}> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType>;\n\nexport interface ToExecutableAction<\n T extends ParameterizedObject\n> extends CustomExecutableActionObject<T['type']> {\n type: T['type'];\n params: T['params'];\n action: undefined;\n}\n\nexport type ActionExecutor = (actionToExecute: ExecutableActionObject) => void;\n\n/** Mappers for subscribeTo - maps lifecycle events to machine events */\nexport interface SubscribeToMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\ntype EnqueueSpawnOptions<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = {\n input?: InputFrom<TLogic>;\n id?: string;\n syncSnapshot?: boolean;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n};\n\ntype EnqueueSpawnArgs<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = ConditionalRequired<\n [\n options?: EnqueueSpawnOptions<TLogic, TSystemRegistry> & {\n [K in RequiredLogicInput<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n>;\n\ntype EnqueueSpawner<\n TActorMap extends Sources['actors'],\n TSystemRegistry extends SystemRegistry\n> = {\n <TSource extends keyof TActorMap & string>(\n src: TSource,\n ...[options]: EnqueueSpawnArgs<TActorMap[TSource], TSystemRegistry>\n ): ActorFromLogic<TActorMap[TSource]>;\n <TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EnqueueSpawnArgs<TLogic, TSystemRegistry>\n ): ActorFromLogic<TLogic>;\n};\n\nexport type EnqueueObject<\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TSystemRegistry extends SystemRegistry = SystemRegistry,\n TActorMap extends Sources['actors'] = Sources['actors']\n> = {\n cancel: (id: string) => void;\n raise: (ev: TEvent, options?: { id?: string; delay?: number }) => void;\n /**\n * Spawns a child actor from a registered source key or logic. Without an\n * explicit `id`, the child gets a deterministic src-keyed id (`worker:0`,\n * `worker:1`, …) allocated from the parent snapshot's own counters, so ids\n * replay identically and persist with the parent.\n */\n spawn: EnqueueSpawner<TActorMap, TSystemRegistry>;\n emit: (emittedEvent: TEmittedEvent) => void;\n <T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): void;\n log: (...args: any[]) => void;\n sendTo: <TActorRef extends { send: (...args: any[]) => void } | undefined>(\n actorRef: TActorRef,\n event: SendableEventFromActorRef<NoInfer<TActorRef>>,\n options?: { id?: string; delay?: number }\n ) => void;\n stop: (actor?: AnyActorRef) => void;\n /**\n * Listen to emitted events from an actor. Returns a listener actor that can\n * be stopped via `enq.stop()`.\n *\n * @param actor - The actor to listen to\n * @param eventType - The emitted event type to listen for (supports\n * wildcards: 'event._', '_')\n * @param mapper - Function to transform emitted events into machine events\n */\n listen: <TEmitted extends EventObject, TMappedEvent extends TEvent>(\n actor: AnyActorRef,\n eventType: string,\n mapper: (event: TEmitted) => TMappedEvent\n ) => AnyActor;\n /**\n * Subscribe to lifecycle events (done/error/snapshot) from an actor. Returns\n * a subscription actor that can be stopped via `enq.stop()`.\n *\n * @param actor - The actor to subscribe to\n * @param mappers - Object with done/error/snapshot mappers, or a single\n * snapshot mapper function\n */\n subscribeTo: <TActor extends AnyActorRef, TMappedEvent extends TEvent>(\n actor: TActor,\n mappers:\n | SubscribeToMappers<\n SnapshotFrom<TActor>,\n OutputFrom<TActor>,\n TMappedEvent\n >\n | ((snapshot: SnapshotFrom<TActor>) => TMappedEvent)\n ) => AnyActor;\n};\n\nexport type Action<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TParams = Record<string, unknown> | undefined,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n _: {\n context: _TCtx;\n event: TEvent;\n parent: AnyActorRef | undefined;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n children: Record<string, AnyActor | undefined>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n system?: AnyActorSystem;\n params: TParams;\n },\n enqueue: EnqueueObject<TEvent, TEmittedEvent, SystemRegistry, TActorMap>\n) => {\n context?: Partial<_TCtx>;\n children?: Record<string, AnyActor | undefined>;\n} | void;\n\nexport type AnyAction =\n | Action<\n MachineContext,\n EventObject,\n EventObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n >\n | { action: (...args: any[]) => any; args: any[] }\n | AnyEventObject;\n","import { createInitEvent } from './eventUtils';\nimport { hasAmbientInspector } from './system';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n setInertActorScopeSnapshot\n} from './getNextSnapshot';\nimport {\n getProperAncestors,\n initialMicrostep,\n isAtomicStateNode,\n macrostep\n} from './stateUtils';\nimport {\n AnyActorLogic,\n AnyEventObject,\n AnyStateMachine,\n EventFromLogic,\n InputFrom,\n SnapshotFrom,\n ExecutableActionObjectFromLogic,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyActor,\n AnyActorScope,\n ExecutableActionObject\n} from './types';\nimport {\n beginSpawnAllocation,\n createSpawnEffect,\n finalizeTransitionResult\n} from './transitionActions.ts';\n\nimport type { EventObject } from './types';\n\ntype MachineMicrostep = [AnyMachineSnapshot, ExecutableActionObject[]];\n\nfunction attachMicrostepActorRefs(\n microsteps: MachineMicrostep[],\n actorScope: AnyActorScope,\n inputSnapshot?: AnyMachineSnapshot\n): MachineMicrostep[] {\n if (!microsteps.length) {\n return microsteps;\n }\n const result = microsteps.slice();\n const finalSnapshot = result.at(-1)![0];\n setInertActorScopeSnapshot(actorScope, finalSnapshot, false);\n if (finalSnapshot !== inputSnapshot) {\n attachSnapshotActorRef(actorScope, finalSnapshot);\n }\n for (const [snapshot] of result) {\n if (snapshot !== inputSnapshot && snapshot !== finalSnapshot) {\n const snapshotScope = createInertActorScope(\n snapshot.machine,\n snapshot,\n undefined,\n actorScope\n );\n attachSnapshotActorRef(snapshotScope, snapshot);\n }\n }\n return result;\n}\n\n/**\n * Given actor `logic`, a `snapshot`, and an `event`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute.\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function transition<T extends AnyActorLogic>(\n logic: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): [\n nextSnapshot: SnapshotFrom<T>,\n actions: ExecutableActionObjectFromLogic<T>[]\n] {\n const actorScope = createInertActorScope(logic, snapshot);\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const [nextSnapshot, effects] = finalizeTransitionResult(\n actorScope,\n snapshot,\n logic.transition(snapshot, event, actorScope)\n );\n\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n const returnedSnapshot =\n nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(actorScope, nextSnapshot);\n inspectPureTransition(actorScope, returnedSnapshot, event);\n return [returnedSnapshot, effects as ExecutableActionObjectFromLogic<T>[]];\n}\n\n/**\n * Given actor `logic` and optional `input`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute from the initial transition (no\n * previous state).\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function initialTransition<T extends AnyActorLogic>(\n logic: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): [SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]] {\n const actorScope = createInertActorScope(logic);\n\n const [nextSnapshot, executableActions] = finalizeTransitionResult(\n actorScope,\n undefined,\n logic.initialTransition(input, actorScope)\n );\n\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n const returnedSnapshot = attachSnapshotActorRef(actorScope, nextSnapshot);\n inspectPureTransition(actorScope, returnedSnapshot, createInitEvent(input));\n return [\n returnedSnapshot,\n executableActions as ExecutableActionObjectFromLogic<T>[]\n ];\n}\n\n/**\n * Emits the `@xstate.transition` inspection event for a snapshot produced by\n * the pure transition path, where no live actor loop does it. Free unless an\n * inspector is ambiently installed (a durable execution created with\n * `inspect`): only then is the snapshot's actor ref materialized to emit.\n */\nfunction inspectPureTransition(\n actorScope: unknown,\n snapshot: unknown,\n event: EventObject\n): void {\n if (!hasAmbientInspector()) {\n return;\n }\n const self = (actorScope as { self?: AnyActor }).self;\n if (self?.system._hasInspectionObservers?.()) {\n self._inspectTransition(snapshot as never, event);\n }\n}\n\n/**\n * Given a state `machine`, a `snapshot`, and an `event`, returns an array of\n * microsteps, where each microstep is a tuple of `[snapshot, actions]`.\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function getMicrosteps<T extends AnyStateMachine>(\n machine: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]> {\n const actorScope = createInertActorScope(machine, snapshot);\n beginSpawnAllocation(actorScope);\n\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n\n return attachMicrostepActorRefs(\n microsteps as MachineMicrostep[],\n actorScope,\n snapshot as AnyMachineSnapshot\n ) as Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]>;\n}\n\n/**\n * Given a state `machine` and optional `input`, returns an array of microsteps\n * from the initial transition, where each microstep is a tuple of `[snapshot,\n * actions]`.\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function getInitialMicrosteps<T extends AnyStateMachine>(\n machine: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]> {\n const actorScope = createInertActorScope(machine);\n beginSpawnAllocation(actorScope);\n const initEvent = createInitEvent(input);\n const internalQueue: AnyEventObject[] = [];\n\n const preInitialSnapshot = machine._getPreInitialState(actorScope, initEvent);\n const contextSpawnEffects = Object.values(preInitialSnapshot.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n\n const first = initialMicrostep(\n machine.root,\n preInitialSnapshot,\n actorScope,\n initEvent,\n internalQueue\n );\n\n const { microsteps } = macrostep(\n first[0],\n initEvent,\n actorScope,\n internalQueue,\n [[first[0], [...contextSpawnEffects, ...first[1]]] as MachineMicrostep]\n );\n\n return attachMicrostepActorRefs(\n microsteps as MachineMicrostep[],\n actorScope\n ) as Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]>;\n}\n\n/**\n * Gets all potential next transitions from the current state.\n *\n * Returns all transitions that are available from the current state, including:\n *\n * - All transitions from atomic states (leaf states in the current state\n * configuration)\n * - All transitions from ancestor states (parent states that may handle events)\n * - All guarded transitions (regardless of whether their guards would pass)\n * - Always (eventless) transitions\n * - After (delayed) transitions\n *\n * The order of transitions is deterministic:\n *\n * 1. Atomic states are processed in document order\n * 2. For each atomic state, transitions are collected from the state itself first,\n * then its ancestors\n * 3. Within each state node, transitions are in the order they appear in the state\n * definition\n *\n * @param state - The current machine snapshot\n * @returns Array of transition definitions from the current state, in\n * deterministic order\n */\nexport function getNextTransitions(\n state: AnyMachineSnapshot\n): AnyTransitionDefinition[] {\n if (state.status !== 'active') {\n return [];\n }\n const potentialTransitions: AnyTransitionDefinition[] = [];\n const atomicStates = state.nodes.filter(isAtomicStateNode);\n const visited = new Set();\n\n // Collect all transitions from atomic states and their ancestors\n // Process atomic states in document order (as they appear in state.nodes)\n for (const stateNode of atomicStates) {\n // For each atomic state, process the state itself first, then its ancestors\n // This ensures child state transitions come before parent state transitions\n for (const s of [stateNode].concat(\n getProperAncestors(stateNode, undefined)\n )) {\n if (visited.has(s.id)) {\n continue;\n }\n visited.add(s.id);\n\n // Get all transitions for each event type\n // Include ALL transitions, even if the same event type appears in multiple state nodes\n // This is important for guarded transitions - all are \"potential\" regardless of guard evaluation\n for (const [, transitions] of s.transitions.entries()) {\n potentialTransitions.push(...transitions);\n }\n\n // Also include always (eventless) transitions\n if (s.always) {\n potentialTransitions.push(...s.always);\n }\n }\n }\n\n return potentialTransitions;\n}\n","import isDevelopment from '#is-development';\nimport { AnyActorRef, SnapshotFrom, Subscription } from './types.ts';\n\ninterface WaitForOptions {\n /**\n * How long to wait before rejecting, if no emitted state satisfies the\n * predicate.\n *\n * @defaultValue Infinity\n */\n timeout: number;\n\n /** A signal which stops waiting when aborted. */\n signal?: AbortSignal;\n}\n\nconst defaultWaitForOptions: WaitForOptions = {\n timeout: Infinity // much more than 10 seconds\n};\n\n/**\n * Subscribes to an actor ref and waits for its emitted value to satisfy a\n * predicate, and then resolves with that value. Will throw if the desired state\n * is not reached after an optional timeout. (defaults to Infinity).\n *\n * @example\n *\n * ```js\n * const state = await waitFor(someService, (state) => {\n * return state.hasTag('loaded');\n * });\n *\n * state.hasTag('loaded'); // true\n * ```\n *\n * @param actorRef The actor ref to subscribe to\n * @param predicate Determines if a value matches the condition to wait for\n * @param options\n * @returns A promise that eventually resolves to the emitted value that matches\n * the condition\n */\nexport function waitFor<TActorRef extends AnyActorRef>(\n actorRef: TActorRef,\n predicate: (emitted: SnapshotFrom<TActorRef>) => boolean,\n options?: Partial<WaitForOptions>\n): Promise<SnapshotFrom<TActorRef>> {\n const resolvedOptions: WaitForOptions = {\n ...defaultWaitForOptions,\n ...options\n };\n return new Promise((res, rej) => {\n const { signal } = resolvedOptions;\n if (signal?.aborted) {\n // oxlint-disable-next-line typescript/prefer-promise-reject-errors\n rej(signal.reason);\n return;\n }\n let done = false;\n if (isDevelopment && resolvedOptions.timeout < 0) {\n console.error(\n '`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.'\n );\n }\n const handle =\n resolvedOptions.timeout === Infinity\n ? undefined\n : setTimeout(() => {\n dispose();\n rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));\n }, resolvedOptions.timeout);\n\n const dispose = () => {\n clearTimeout(handle);\n done = true;\n sub?.unsubscribe();\n if (abortListener) {\n signal!.removeEventListener('abort', abortListener);\n }\n };\n\n function checkEmitted(emitted: SnapshotFrom<TActorRef>) {\n if (predicate(emitted)) {\n dispose();\n res(emitted);\n }\n }\n\n /**\n * If the `signal` option is provided, this will be the listener for its\n * `abort` event\n */\n let abortListener: () => void | undefined;\n // oxlint-disable-next-line prefer-const\n let sub: Subscription | undefined; // avoid TDZ when disposing synchronously\n\n // See if the current snapshot already matches the predicate\n checkEmitted(actorRef.getSnapshot());\n if (done) {\n return;\n }\n\n // only define the `abortListener` if the `signal` option is provided\n if (signal) {\n abortListener = () => {\n dispose();\n // XState does not \"own\" the signal, so we should reject with its reason (if any)\n // oxlint-disable-next-line typescript/prefer-promise-reject-errors\n rej(signal.reason);\n };\n signal.addEventListener('abort', abortListener);\n }\n\n sub = actorRef.subscribe({\n next: checkEmitted,\n error: (err) => {\n dispose();\n // oxlint-disable-next-line typescript/prefer-promise-reject-errors\n rej(err);\n },\n complete: () => {\n dispose();\n rej(new Error(`Actor terminated without satisfying predicate`));\n }\n });\n if (done) {\n sub.unsubscribe();\n }\n });\n}\n","import { Clock } from './system.ts';\n\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\nexport interface SimulatedClock extends Clock {\n start(speed: number): void;\n increment(ms: number): void;\n set(ms: number): void;\n}\n\ninterface SimulatedTimeout {\n start: number;\n timeout: number;\n fn: (...args: any[]) => void;\n}\nexport class SimulatedClock implements SimulatedClock {\n private timeouts: Map<number, SimulatedTimeout> = new Map();\n private _now: number = 0;\n private _id: number = 0;\n private _flushing = false;\n private _flushingInvalidated = false;\n\n public now() {\n return this._now;\n }\n private getId() {\n return this._id++;\n }\n public setTimeout(fn: (...args: any[]) => void, timeout: number) {\n this._flushingInvalidated = this._flushing;\n const id = this.getId();\n this.timeouts.set(id, {\n start: this.now(),\n timeout,\n fn\n });\n return id;\n }\n public clearTimeout(id: number) {\n this._flushingInvalidated = this._flushing;\n this.timeouts.delete(id);\n }\n public set(time: number) {\n if (this._now > time) {\n throw new Error('Unable to travel back in time');\n }\n\n this._now = time;\n this.flushTimeouts();\n }\n private flushTimeouts() {\n if (this._flushing) {\n this._flushingInvalidated = true;\n return;\n }\n this._flushing = true;\n\n const sorted = [...this.timeouts].sort(\n ([_idA, timeoutA], [_idB, timeoutB]) => {\n const endA = timeoutA.start + timeoutA.timeout;\n const endB = timeoutB.start + timeoutB.timeout;\n return endB > endA ? -1 : 1;\n }\n );\n\n for (const [id, timeout] of sorted) {\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this._flushing = false;\n this.flushTimeouts();\n return;\n }\n if (this.now() - timeout.start >= timeout.timeout) {\n this.timeouts.delete(id);\n timeout.fn.call(null);\n }\n }\n\n this._flushing = false;\n // Check if new timeouts were added during the last iteration\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this.flushTimeouts();\n }\n }\n public increment(ms: number): void {\n this._now += ms;\n this.flushTimeouts();\n }\n}\n","import { EventDescriptor, EventObject, ExtractEvent } from './types.ts';\nimport { matchesEventDescriptor, toArray } from './utils.ts';\n\n/**\n * Asserts that the given event object is of the specified type or types. Throws\n * an error if the event object is not of the specified types.\n *\n * @example\n *\n * ```ts\n * // ...\n * entry: ({ event }) => {\n * assertEvent(event, 'doNothing');\n * // event is { type: 'doNothing' }\n * },\n * // ...\n * exit: ({ event }) => {\n * assertEvent(event, 'greet');\n * // event is { type: 'greet'; message: string }\n *\n * assertEvent(event, ['greet', 'notify']);\n * // event is { type: 'greet'; message: string }\n * // or { type: 'notify'; message: string; level: 'info' | 'error' }\n * },\n * ```\n */\nexport function assertEvent<\n TEvent extends EventObject,\n TAssertedDescriptor extends EventDescriptor<TEvent>\n>(\n event: TEvent,\n type: TAssertedDescriptor | readonly TAssertedDescriptor[]\n): asserts event is ExtractEvent<TEvent, TAssertedDescriptor> {\n const types = toArray(type);\n\n const matches = types.some((descriptor) =>\n matchesEventDescriptor(event.type, descriptor as string)\n );\n\n if (!matches) {\n const typesText =\n types.length === 1\n ? `type matching \"${types[0]}\"`\n : `one of types matching \"${types.join('\", \"')}\"`;\n throw new Error(\n `Expected event ${JSON.stringify(event)} to have ${typesText}`\n );\n }\n}\n","import { isRemoteActorRef } from './remoteActorRef.ts';\nimport { getActorIdPrefix } from './system.ts';\nimport type { ExecutableActionObject } from './types.ts';\n\n/**\n * A serializable view of an executable effect. Actor references are replaced\n * by their logical addresses and actor sources by their registered source\n * keys, so a durable host can journal, deduplicate, and route effects without\n * holding live actor references. Payload fields (`event`, `input`, `params`,\n * `output`, `error`) pass through by reference and are only as serializable\n * as their values.\n *\n * @experimental\n */\nexport type EffectDescriptor =\n | {\n kind: 'builtin';\n type: '@xstate.spawn';\n source: string | undefined;\n actor: string;\n id: string;\n src: string;\n input: unknown;\n }\n | {\n kind: 'builtin';\n type: '@xstate.start';\n source: string | undefined;\n actor: string;\n id: string;\n }\n | {\n kind: 'builtin';\n type: '@xstate.raise';\n source: string;\n event: unknown;\n id: string | undefined;\n delay: number | undefined;\n }\n | {\n kind: 'builtin';\n type: '@xstate.sendTo';\n source: string;\n target: string;\n /** The target's incarnation token, when the target is a remote handle that carries one. */\n incarnation: string | undefined;\n event: unknown;\n id: string | undefined;\n delay: number | undefined;\n }\n | {\n kind: 'builtin';\n type: '@xstate.cancel';\n source: string;\n id: string;\n }\n | {\n kind: 'builtin';\n type: '@xstate.stop';\n source: string;\n actor: string;\n id: string;\n }\n | {\n kind: 'builtin';\n type: '@xstate.terminate';\n source: string;\n actor: string;\n id: string;\n status: 'done' | 'error';\n output: unknown;\n error: unknown;\n }\n | {\n kind: 'emit';\n type: string;\n source: string;\n event: unknown;\n }\n | {\n kind: 'action';\n type: string;\n params: unknown;\n };\n\n/**\n * Returns the serializable descriptor for an executable effect: the same\n * discriminants (`kind`, `type`) with actor references replaced by logical\n * addresses and actor sources by source keys. Payload fields pass through by\n * reference.\n *\n * @experimental\n */\nexport function getEffectDescriptor(\n effect: ExecutableActionObject\n): EffectDescriptor {\n if (effect.kind === 'action') {\n return {\n kind: 'action',\n type: effect.type,\n params: effect.params\n };\n }\n\n if (effect.kind === 'emit') {\n return {\n kind: 'emit',\n type: effect.type,\n source: effect.source.address,\n event: effect.event\n };\n }\n\n switch (effect.type) {\n case '@xstate.spawn':\n return {\n kind: 'builtin',\n type: '@xstate.spawn',\n source: effect.source?.address,\n actor: effect.actor.address,\n id: effect.id,\n // `src` is only a unique key for registered sources; anonymous inline\n // logic collapses to its logic id or 'x'. The `actor` address is the\n // identity field.\n src: getActorIdPrefix(effect.src),\n input: effect.input\n };\n case '@xstate.start':\n return {\n kind: 'builtin',\n type: '@xstate.start',\n source: effect.source?.address,\n actor: effect.actor.address,\n id: effect.id\n };\n case '@xstate.raise':\n return {\n kind: 'builtin',\n type: '@xstate.raise',\n source: effect.source.address,\n event: effect.event,\n id: effect.id,\n delay: effect.delay\n };\n case '@xstate.sendTo':\n return {\n kind: 'builtin',\n type: '@xstate.sendTo',\n source: effect.source.address,\n target: effect.target.address,\n incarnation: isRemoteActorRef(effect.target)\n ? effect.target.sessionId\n : undefined,\n event: effect.event,\n id: effect.id,\n delay: effect.delay\n };\n case '@xstate.cancel':\n return {\n kind: 'builtin',\n type: '@xstate.cancel',\n source: effect.source.address,\n id: effect.id\n };\n case '@xstate.stop':\n return {\n kind: 'builtin',\n type: '@xstate.stop',\n source: effect.source.address,\n actor: effect.actor.address,\n id: effect.id\n };\n case '@xstate.terminate':\n return {\n kind: 'builtin',\n type: '@xstate.terminate',\n source: effect.source.address,\n actor: effect.actor.address,\n id: effect.id,\n status: effect.status,\n output: effect.output,\n error: effect.error\n };\n }\n}\n","/** The Standard Schema interface. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\n/** Schemas that can be declared for an individual state node. */\nexport type SetupStateSchemas = {\n context?: StandardSchemaV1;\n input?: StandardSchemaV1;\n /** The output emitted when this state node completes. */\n output?: StandardSchemaV1;\n};\n\n/** A type-only Standard Schema produced by {@link types}. */\nexport interface TypeSchema<T> extends StandardSchemaV1<T, T> {\n readonly '~standard': StandardSchemaV1.Props<T, T> & {\n readonly vendor: 'xstate.types';\n };\n}\n\n/**\n * Declares schema types for inference only — no runtime validation.\n *\n * Use in a machine's `schemas` when you want TypeScript types without pulling\n * in a schema library like Zod. The returned value is a valid Standard Schema\n * whose validation is the identity function, so it carries types but never\n * rejects input.\n *\n * @example\n *\n * ```ts\n * import { createMachine, types } from 'xstate';\n *\n * const machine = createMachine({\n * schemas: {\n * context: types<{ count: number }>(),\n * events: {\n * inc: types<{ by: number }>(),\n * reset: types<{}>()\n * }\n * },\n * context: { count: 0 }\n * // ...\n * });\n * ```\n */\nexport function types<T>(): TypeSchema<T> {\n return {\n '~standard': {\n version: 1,\n vendor: 'xstate.types',\n validate: (value) => ({ value: value as T })\n }\n };\n}\n\n/** Returns true if the value is a type-only schema created by {@link types}. */\nexport function isTypeSchema(value: unknown): value is TypeSchema<unknown> {\n return (\n !!value &&\n typeof value === 'object' &&\n '~standard' in value &&\n (value as StandardSchemaV1)['~standard'].vendor === 'xstate.types'\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1;\n /** The vendor name of the schema library. */\n readonly vendor: string;\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>;\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined;\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output;\n /** The non-existent issues. */\n readonly issues?: undefined;\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>;\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string;\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey;\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input;\n /** The output type of the schema. */\n readonly output: Output;\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input'];\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output'];\n}\n","import { MachineSnapshot } from './State.ts';\nimport { isAtomicStateNode } from './stateUtils.ts';\nimport { AnyMachineSnapshot, AnyStateNode, StateSchema } from './types.ts';\n\ntype StateSchemaFromSnapshot<TSnapshot extends AnyMachineSnapshot> =\n TSnapshot extends MachineSnapshot<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer TStateSchema extends StateSchema\n >\n ? TStateSchema\n : StateSchema;\n\n/**\n * A mapper object that defines how to transform a snapshot based on its state.\n * Can be nested to match the state hierarchy of the machine.\n */\ntype StateSchemaMapper<\n TSnapshot extends AnyMachineSnapshot,\n T extends StateSchema,\n TResult\n> = {\n /** Maps the snapshot to a value when this state is active. */\n map?: (snapshot: TSnapshot) => TResult;\n /** Nested mappers for child states. */\n states?: {\n [K in keyof T['states']]?: T['states'][K] extends StateSchema\n ? StateSchemaMapper<TSnapshot, T['states'][K], TResult>\n : never;\n };\n};\n\n/**\n * Maps a machine snapshot to an array of result objects based on active states.\n *\n * Traverses all active state nodes (from atomic/leaf states up to root) and\n * collects results from matching `map` functions in the mapper object. Results\n * are ordered leaf-to-root (most specific state first).\n */\nexport function mapState<T extends AnyMachineSnapshot, TResult>(\n snapshot: T,\n mapper: StateSchemaMapper<T, StateSchemaFromSnapshot<T>, TResult>\n): { stateNode: AnyStateNode; result: TResult }[] {\n const results: { stateNode: AnyStateNode; result: TResult }[] = [];\n\n const findMapper = (\n currentMapper: StateSchemaMapper<T, StateSchemaFromSnapshot<T>, TResult>,\n nodePath: string[]\n ): StateSchemaMapper<T, any, TResult> | undefined => {\n let mapper: StateSchemaMapper<T, any, TResult> | undefined = currentMapper;\n\n for (const key of nodePath) {\n if (!mapper?.states) {\n return undefined;\n }\n const states = mapper.states as Record<\n string,\n StateSchemaMapper<T, any, TResult>\n >;\n if (!(key in states)) {\n return undefined;\n }\n mapper = states[key];\n }\n\n return mapper;\n };\n\n const visited = new Set<AnyStateNode>();\n\n for (const atomicNode of snapshot.nodes.filter(isAtomicStateNode)) {\n let current: AnyStateNode | undefined = atomicNode;\n while (current && !visited.has(current)) {\n visited.add(current);\n\n const nodeMapper = findMapper(mapper, current.path);\n if (nodeMapper?.map) {\n results.push({ stateNode: current, result: nodeMapper.map(snapshot) });\n }\n\n current = current.parent;\n }\n }\n\n return results;\n}\n","import { AnyActorRef, OutputFrom } from './types.ts';\n\n/**\n * Returns a promise that resolves to the `output` of the actor when it is done.\n *\n * @example\n *\n * ```ts\n * const machine = createMachine({\n * // ...\n * output: {\n * count: 42\n * }\n * });\n *\n * const actor = createActor(machine);\n *\n * actor.start();\n *\n * const output = await toPromise(actor);\n *\n * console.log(output);\n * // logs { count: 42 }\n * ```\n */\nexport function toPromise<T extends AnyActorRef>(\n actor: T\n): Promise<OutputFrom<T>> {\n return new Promise((resolve, reject) => {\n actor.subscribe({\n complete: () => {\n resolve(actor.getSnapshot().output);\n },\n error: reject\n });\n });\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_INIT","XSTATE_SPAWN","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","XSTATE_LOGIC_EFFECT_RESOLVE","XSTATE_LOGIC_EFFECT_REJECT","XSTATE_LOGIC_EFFECT_START","createAfterEvent","delayRef","id","type","delay","stateId","createAfterEventId","createTimeoutEventId","createInvokeTimeoutEvent","invokeId","sessionId","actorId","createInvokeTimeoutEventId","createDoneStateEvent","output","createErrorPlatformEvent","kind","error","createInitEvent","input","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","assertSendToEvent","Error","builtInActions","actor","system","spawnActor","_parent","startActor","@xstate.raise","actorScope","_event","options","scheduleTimer","self","@xstate.sendTo","undefined","_relay","@xstate.cancel","sendId","cancelTimer","@xstate.stop","stopActor","@xstate.terminate","termination","terminateActor","sourceKeyCaches","WeakMap","resolveRegisteredActorSource","actors","logic","cache","get","Map","key","Object","keys","registeredLogic","has","set","subscriptions","createAttachedLogic","attach","initialTransition","_","status","state","target","getSnapshot","subscription","parentSubscription","torndown","teardown","unsubscribe","parent","subscribe","complete","transition","delete","getInitialSnapshot","getPersistedSnapshot","snapshot","restoreSnapshot","relayMappedToParent","getEvent","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","on","emittedEvent","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","lazyActorScope","isLazyActorScope","getActorScopeParent","withActorScope","args","actorArgs","defineProperties","enumerable","execCustomEffect","action","execEmitEffect","runtime","source","emitEvent","createCustomEffect","params","exec","execSpawnEffect","execStartEffect","execStopEffect","execTerminateEffect","execRaiseEffect","execSendToEffect","sendEvent","execCancelEffect","updateLogicalTimers","effect","isBuiltInExecutableAction","timers","nextTimerId","_nextTimerId","mergeContextPatch","context","patch","pushBuiltInAction","actions","actionRecord","push","mergeActorIdCounters","current","update","merged","Math","max","applyChildUpdate","children","counters","_nextActorIds","owned","_unregister","getTransitionActionRecord","spawnAllocations","createSpawnAllocation","explicitIds","Set","stoppedIds","beginSpawnAllocation","getWorkingSnapshotOf","_snapshot","nextChildIndex","allocation","prefix","allocateChildId","src","localAllocation","getActorIdPrefix","assertChildIdFree","existing","occupied","add","reserveChildId","generated","parseGeneratedActorId","index","createTransitionEnqueue","internalEvents","actorSubscriptions","createActors","props","cancel","emit","log","logger","raise","raisedEvent","spawn","registeredActors","sources","getRegisteredActors","resolveTransitionSpawnSource","registryKey","createActorRef","childUpdate","pushSpawnedChild","sendTo","message","stop","actorInstance","recordStoppedChild","assign","listen","listenerActor","subscribeTo","subscriptionActor","createEnqueueObject","getBuiltInActionFields","createStartEffect","createSpawnEffect","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","deriveDeferredStarts","attachedStarts","childStarts","resolveActionsWithContext","currentSnapshot","intermediateSnapshot","executableActions","actionArgs","getEventOutput","machine","isInline","resolvedAction","bind","actionParams","_childUpdate","emittedEventParams","name","res","emptyEnqueueObject","builtInFields","isEmittedEvent","typedExecutableAction","enqueueFn","fn","noop","emptyActor","parseDurationToMilliseconds","duration","normalizedDuration","trim","millisecondsMatch","match","parseInt","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","slice","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDelayToMilliseconds","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","getKeyedActors","peek","_peekKeyedActors","call","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","baseState","root","copyRegisteredActors","reverseKeyedActors","create","sourceVersion","_register","_set","String","getAll","fromEntries","_hasInspectionObservers","_sendInspectionEvent","values","getSnapshotActorRef","created","copySnapshotActorRef","ref","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","size","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","isInertActorScope","_inert","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","defer","stopChild","actionExecutor","createMaterializedInertActorScope","actorLogic","sourceRef","sourceChildren","sourceSelf","snapshotRef","previousSelf","createActor","_sessionId","_systemRef","_address","_actorScope","_stop","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","isMachineSnapshot","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","resolveDelay","delaySource","configuredDelay","referencedDelay","getConfiguredDelayValue","getStateInput","stateNodeId","_stateInputs","isAtomicStateNode","stateNode","getChildren","states","filter","sn","getProperAncestors","toStateNode","ancestors","m","getAllStateNodes","stateNodes","nodeSet","activeParentSet","s","initialStates","getInitialStateNodes","initialStateNode","getStateValue","rootNode","config","adjList","getValueFromAdj","baseNode","childStateNodes","childStateNode","stateValue","isInFinalState","stateNodeSet","every","isStateId","str","getLegacyEventType","matchesActorSession","getCandidates","eventTypes","legacyType","getEventTypeAliases","exactMatches","flatMap","transitions","wildcardCandidates","eventDescriptor","includes","sort","a","b","length","scheduleDelayedEvent","timerId","resolveEvent","resolveScheduledDelay","oldEntry","entry","x","enq","oldExit","exit","formatTransition","descriptor","transitionConfig","normalizedTarget","normalizeTarget","reenter","resolveTarget","assertLegalTargetSet","toJSON","map","t","isStateNodeDescendantOf","ancestor","getLeastCommonStateNodeAncestor","left","right","leftAncestors","targets","leftIndex","rightIndex","commonAncestor","getStateNodeById","isInternalTarget","getStateNodeByPath","resolvedTarget","resolveHistoryDefaultTransition","initial","to","_historyDefaultTransition","isHistoryNode","iter","descStateNode","initialState","getStateNode","stateKey","result","statePath","arrayStatePath","toStatePath","currentStateNode","shift","getStateNodes","childStateKeys","Array","allStateNodes","i","subStateNode","transitionNode","selectionResults","subStateKeys","subStateKey","allInnerTransitions","subStateValue","innerTransitions","isDescendant","parentStateNode","marker","hasDescendantState","hasIntersection","s1","s2","s1Size","isArray","s2Size","set1","item","removeConflictingTransitions","enabledTransitions","resolveTransition","filteredTransitions","exitSets","getExitSet","exitSet","computeExitSet","t1","t1Preempted","transitionsToRemove","t2","t3","from","createTransitionResultResolver","resolveActions","getTransitionResult","selectionResult","getEffectiveTargetStates","historyValue","targetSet","targetNode","node","narrowParallelDomain","domain","targetStates","narrowed","region","find","getTransitionDomain","_transitionDomain","head","tail","concat","statesToExit","initialMicrostep","preInitialState","initEvent","internalQueue","initialStateNodes","statesForDefaultEntry","collectDefaultEntryStates","microstep","other","_statesForDefaultEntry","isInitial","mutStateNodeSet","nodes","originalContext","getCurrentTransitionResult","changesState","getStateActionsAndContext","transitionFn","updatedContext","guards","delays","_special","nextState","getInvokeStopActions","invokeDef","invoke","exitStates","changedHistory","order","currentStateNodes","exitStateNode","historyNode","predicate","history","stateInput","exitActions","nextContext","cloneMachineSnapshot","resolvedState","resolvedActions","invokeStopActions","stoppedState","stopEffects","transitionActions","toArray","enterStates","getMachineOutput","rootCompletionNode","completionOutput","rootDoneEvent","e","resolveOutput","stateInputMap","parallelDoneEvent","statesToEnter","historyDefaultsByParent","addAncestorStatesToEnter","reentrancyDomain","anc","addDescendantStatesToEnter","historyStateNodes","historyDefaultTransition","historyParent","defaults","stateInputsChanged","completedNodes","stateNodeToEnter","invoked","resolveReferencedActor","syncSnapshot","contextChangedByEntry","resultActions","nextInternalEvents","defaultTransitions","Boolean","defaultTransition","initialActions","initialContext","initialInput","initialInternalEvents","ancestorMarker","regionOutput","regionDoneEvent","finalChild","resolvedTransitionState","transitionExecutableActions","nextStateNodes","allExitActions","forEach","stopChildren","withoutTimers","cancelEffects","cancelTimers","_nodes","transitionArgs","getTransitionArgs","reusable","resolvedInput","resolvedContext","macrostep","initialMicrosteps","microsteps","removeTerminatedChild","terminalEvent","lastEffects","at","completeMacrostep","starts","shouldTerminate","terminalEffects","lastSnapshot","addMicrostep","step","collectedMicrosteps","_collectedMicrosteps","stoppedChildrenSnapshot","nextEvent","normalizeWithId","idKey","startsWith","normalized","afterPrefix","idMap","delayText","isNaN","normalizeLegacyInternalEvent","timer","currentEvent","isErr","isErrorEvent","getTransitionData","_hasEventlessTransitions","shouldSelectEventlessTransitions","maxIterations","Infinity","iterationCount","microstepCount","selectEventlessTransitions","previousState","hasEffect","evaluateTransitionFunction","enabled","triggerTransitionEffect","transitionEffectSignal","transitionEffectEnqueue","transitionTo","sourceId","transitionEffectTargets","pop","timerIds","enabledTransitionSet","atomicStates","atomicStateNode","loop","always","evaluateCandidate","candidate","matches","pattern","entries","is","matchesEvent","_eventMatcher","guard","guardArgs","withActorSelfAndParent","evaluation","emptySubscription","restoreHint","isRemoteActorRef","actorRef","_remote","remoteSnapshot","freeze","createRemoteActorRef","handle","address","incarnation","_syncSnapshot","send","_send","select","trigger","_isRunning","xstate$type","ACTOR_REF_TYPE","emptySnapshotRecord","compactSnapshotRecord","machineSnapshotMatches","testValue","matchesState","machineSnapshotHasTag","tag","tags","machineSnapshotCan","_canTransition","machineSnapshotToJSON","getMeta","getInputs","can","hasTag","jsonValues","machineSnapshotGetMeta","meta","machineSnapshotGetInputs","collectTags","createMachineSnapshot","configWithSnapshot","clonedSnapshot","serializeHistoryValue","persistContext","contextPart","copy","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","segment","charCodeAt","pathToStateValue","previous","toArrayStrict","isDoneEvent","toTransitionConfigArray","configLike","transitionLike","toObserver","nextHandler","errorHandler","completionHandler","isObserver","indexStr","nodeId","invokeConfig","configSrc","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","async","runStep","sendSelf","getStepEffect","Promise","resolve","reject","waitForStep","deliverEvent","assertEventCanBeSent","runtimeTarget","_lastSourceRef","isInternalEventType","_terminate","systemIdPrefix","nextSystemId","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","toString","padStart","join","randomUUID","replaceAll","Date","now","random","createSystemIdPrefix","logicId","encodeAddressSegment","separator","lastIndexOf","isSafeInteger","getActorIdCounterKey","bumpActorIdCounter","counterKey","emptyScheduledTimers","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_keyedActors","_reverseKeyedActors","_identity","systemId","nextSessionId","scheduler","_clock","_logger","restoredSnapshot","clock","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","targetRef","targetId","schedule","existingId","_timerMap","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","changed","inspect","observerOrFn","observer","resolvedInspectionEvent","rootId","override","stopActorLocally","terminateActorLocally","_emit","deadLetter","reason","runLogic","cancelAllTimers","scheduledTimers","resetScheduledTimers","scheduledId","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","Actor","_trigger","Proxy","payload","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_collectedActions","_initialEffects","_deferred","_restored","resolvedOptions","rootActor","createRuntimeSystem","requestedId","counter","resolveActorId","persistedState","_setSnapshot","parentRef","_getLogger","_defer","defineProperty","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","_next","deferred","deferredFn","_inspectTransition","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","Stopped","handler","listeners","selector","equalityFn","selected","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","startedAt","min","caughtError","reportError","assertValid","validator","request","check","effectStates","executeLogicEffect","getEffectState","cleanup","createLogic","calculateTransition","cleanupLogicEffects","trackedEffects","emitted","createEmitEffect","sendBack","sentEvent","keyOrExec","maybeExec","enqueueEffect","run","eventOrigin","resolveContext","instanceStates","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","XSTATE_ASYNC_RESOLVE","XSTATE_ASYNC_REJECT","TimeoutError","super","emptyLogic","EMPTY_OBJECT","StateNode","path","description","schemas","after","events","ownEvents","_candidateCache","_key","_machine","firstStateKey","choice","validateStateNodeConfig","collection","iteratee","collectionKeys","mapValues","stateConfig","resolvedId","sourceName","_initialize","afterConfig","timeoutConfig","onTimeoutConfig","onTimeout","invokeDefs","fromDelaysMap","eventMatcher","delayedTransitions","eventPattern","delayedTransition","getDelayedTransitions","addTransitions","additions","transitionsConfig","mapTransitionConfigs","onDone","onError","createCancelInvokeTimeoutTransition","timeoutEventId","_args","formatInvokeCompletionTransition","rest","didEnqueue","trackingEnqueue","apply","thisArg","argArray","Reflect","prop","receiver","withInvokeMatch","invokeTimeoutEventId","invokeDoneTransitions","rawTransition","formatTransitions","validateChoiceResult","formatChoiceTransitions","_refreshEventMetadata","object","memoizedData","memo","_target","targetString","resolvedTargets","formatInitialTransition","descriptorKey","getEventDescriptorKey","candidates","transitionConfigs","findEventSchema","hasOwn","emptyCanActor","emptyCanActorScope","getEmptyCanActorScope","StateMachine","_internalEventType","version","snapshotSchema","eventSchema","internalEventDescriptors","_json","vendor","validate","issues","contextSchema","resolveState","eventSchemas","internalEventSchemas","isFrameworkEvent","schema","rootStateNode","routeTransitions","collectRoutes","route","routeId","routeConfig","routeMatches","_guard","routeOptions","formatRouteTransitions","provide","provided","resolvedStateValue","usesInertScope","resolvedActorScope","fastSnapshot","_transitionFast","returnedSnapshot","_attachPureActorRef","_collectEffects","skipInitializingActor","sourceNode","stateChanged","snapshots","emptyActorScope","transitionData","_getPreInitialState","preInitial","spawnedChildren","referencedSrc","createSpawner","withActorSelf","takeSpawnAllocationCounters","contextSpawnEffects","finalizeInitialResult","macroState","errorMacrostep","childId","_rehydrated","fullPath","relativePath","resolvedStateId","STATE_IDENTIFIER","childrenJson","timersJson","embedChildren","embed","remote","snapshotActor","scheduled","persisted","stateInputs","snapshotMachine","persistedMachine","legacyPersistedVersion","persistedVersion","migrate","snapshotData","snapshotChildren","actorData","childState","persistedTimers","targetDescription","revivedHistoryValue","revived","arr","resolved","reviveHistoryValue","validateStateValue","missingStateError","childNode","_persistedSnapshotVersion","_nextActorId","_legacyNextActorId","persistedRest","restoredCounters","seen","WeakSet","reviveContext","createMachine","emptySources","emptyExecutableActions","emptyRawActions","builtInActionSet","resolveTransitionContext","resolveInput","prototype","hasOwnProperty","cloneSnapshot","_stateInput","stopSnapshot","delayToMs","parsedDelay","parseFloat","isExpression","isResolvable","isCode","toPath","extractSerializableDelays","toActionArray","validateChoiceConfig","branch","when","isBuiltInActionJSON","valueToJSON","isActorLogic","isRuntimeSchema","v","jsonValue","invokeToJSON","def","sourcesToJSON","stateNodeConfigToJSON","machineConfigToJSON","isObject","isVersionedStateMachine","finalizeSnapshot","validateEvents","all","validated","setup","extend","extension","base","mergeSchemas","mergeMaps","mergeSetupConfigs","machineConfig","mergedSchemas","mergedStates","mergeStateSchemas","mergedActions","mergedActors","mergedGuards","mergedDelays","createStateConfig","configStates","setupStates","configState","setupState","SpecialTargets","attachMicrostepActorRefs","inputSnapshot","finalSnapshot","inspectPureTransition","defaultWaitForOptions","timeouts","_now","_id","_flushing","_flushingInvalidated","getId","time","flushTimeouts","sorted","_idA","timeoutA","_idB","timeoutB","endA","increment","types","typesText","JSON","stringify","asyncLogic","createBaseLogic","resolvedValue","data","actorSelf","controller","AbortController","timeoutMs","timeoutId","abort","runBody","signal","then","response","errorData","callbackOrConfig","callback","callbackState","receivers","dispose","receive","listener","lazyObservableOrConfig","lazyObservable","_subscription","assertNoStringTransitions","runActions","rawActions","simpleExecutableActions","resolveSimpleEnqueuedActions","runStateActions","actionsConfig","actionCount","currentContext","selectTransition","transitionCount","transitionCore","directTransition","hasContext","hasInput","iterations","nextValue","exited","afterTransition","entered","entryActions","createSnapshot","raisedSnapshot","raisedActions","json","resolvedSources","evaluators","mergeSources","expressionResolver","expressionLanguage","getEvaluator","lang","evaluator","evaluateResolvable","slot","resolveValue","makeScope","extra","getDurationConfig","assertResolvable","createExpressionResolver","resolveCondition","condition","declarativeGuard","guardImpl","makeChoiceConfig","resolveRouteConfig","resolvedGuard","executeActions","stack","definition","iterActions","actionArray","getTransitionConfig","dynamic","assertCondition","assertAction","definitions","assertActions","assertTransition","transitionPath","assertStateNode","invokePath","assertMachineJSON","contextConfig","iterNode","nodeKey","invokes","inv","xstate.stateIn","xstate.not","inner","impl","observableCreatorOrConfig","observableCreator","_config","runtimeRef","pendingObservers","createActorFromLogic","flushObservers","active","preInitialSnapshot","first","transitionResult","potentialTransitions","visited","byIdentity","machinesByIdentity","machineId","unversioned","parseSnapshot","raw","adaptEvents","adaptationOptions","sourceError","sourceValidationFailed","hasTypedSource","sourceEvents","adapter","adapters","wildcardAdapter","cause","migrateSnapshot","migrationOptions","parseError","exactMigration","migrations","wildcardMigration","defaultId","getSnapshotSource","results","findMapper","currentMapper","nodePath","atomicNode","nodeMapper","rej","aborted","sub","abortListener","removeEventListener","checkEmitted","addEventListener"],"mappings":"6OAKO,MAAMA,EAKXC,WAAAA,CAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,KAAAA,GACLJ,KAAKC,SAAU,EACfD,KAAKK,OACP,CAEOC,KAAAA,GAGDN,KAAKE,WACPF,KAAKE,SAASK,KAAO,KACrBP,KAAKG,MAAQH,KAAKE,SAEtB,CAEOM,OAAAA,CAAQC,GACb,MAAMC,EAAW,CACfC,MAAOF,EACPF,KAAM,MAGR,GAAIP,KAAKE,SAGP,OAFAF,KAAKG,MAAOI,KAAOG,OACnBV,KAAKG,MAAQO,GAIfV,KAAKE,SAAWQ,EAChBV,KAAKG,MAAQO,EAETV,KAAKC,SACPD,KAAKK,OAET,CAEQA,KAAAA,GACN,K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AAWI,EAAUlG,EAAO+C,IAGpC0R,GAA2B1R,EAAYqL,GAAc,GACrD,MAAM01B,EACJ11B,IAAiBlI,EACbkI,EACA4G,GAAuBjS,EAAYqL,GAEzC,OADAy9B,GAAsB9oC,EAAY+gC,EAAkB9jC,GAC7C,CAAC8jC,EAAkBz1B,EAC5B,UK/CO,WACL,MAAO,CACL,YAAa,CACX0zB,QAAS,EACTK,OAAQ,eACRC,SAAWniC,IAAW,CAAEA,MAAOA,KAGrC,YJdO,SACLusB,EACA1I,EACA9gB,GAEA,MAAMm1B,EAAkC,IACnC0T,MACA7oC,GAEL,OAAO,IAAIouB,QAAQ,CAAC1hB,EAAKomC,KACvB,MAAMlI,OAAEA,GAAWzV,EACnB,GAAIyV,GAAQmI,QAGV,YADAD,EAAIlI,EAAO1X,QAGb,IAAIlvB,GAAO,EAMX,MAAM6lB,EACJsL,EAAgBhD,UAAY/K,SACxBhnB,EACAnB,WAAW,KACTmsC,IACA0H,EAAI,IAAIxzC,MAAM,cAAc61B,EAAgBhD,yBAC3CgD,EAAgBhD,SAEnBiZ,EAAUA,KACd/Y,aAAaxI,GACb7lB,GAAO,EACPgvC,GAAKvwC,cACDwwC,GACFrI,EAAQsI,oBAAoB,QAASD,IAIzC,SAASE,EAAata,GAChB/X,EAAU+X,KACZuS,IACA1+B,EAAImsB,GAER,CAMA,IAAIoa,EAEAD,EAGJG,EAAa3pB,EAASpnB,eAClB4B,IAKA4mC,IACFqI,EAAgBA,KACd7H,IAGA0H,EAAIlI,EAAO1X,SAEb0X,EAAOwI,iBAAiB,QAASH,IAGnCD,EAAMxpB,EAAS7mB,UAAU,CACvB9F,KAAMs2C,EACNv0C,MAAQI,IACNosC,IAEA0H,EAAI9zC,IAEN4D,SAAUA,KACRwoC,IACA0H,EAAI,IAAIxzC,MAAM,qDAGd0E,GACFgvC,EAAIvwC,gBAGV"}
|
|
1
|
+
{"version":3,"file":"xstate.umd.min.js","sources":["../src/Mailbox.ts","../src/constants.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actions.ts","../src/actorSource.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/actors/subscription.ts","../src/actorScope.ts","../src/transitionActions.ts","../src/delay.ts","../src/snapshotActorRef.ts","../src/getNextSnapshot.ts","../src/stateUtils.ts","../src/utils.ts","../src/remoteActorRef.ts","../src/State.ts","../src/runtimeHelpers.ts","../src/system.ts","../src/createActor.ts","../src/validation.ts","../src/actors/logic.ts","../src/actors/callback.ts","../src/actors/observable.ts","../src/actors/promise.ts","../src/actors/index.ts","../src/memo.ts","../src/StateNode.ts","../src/StateMachine.ts","../src/spawn.ts","../src/createMachine.ts","../src/fsm/effects.ts","../src/fsm.ts","../src/createMachineFromConfig.ts","../src/serialize.ts","../src/machineVersions.ts","../src/setup.ts","../src/types.ts","../src/transition.ts","../src/waitFor.ts","../src/SimulatedClock.ts","../src/assert.ts","../src/effectDescriptor.ts","../src/schema.types.ts","../src/mapState.ts","../src/toPromise.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = '@xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\nexport const XSTATE_STOP = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\nexport function createAfterEventId(delayRef: number | string, id: string) {\n return `xstate.after.${delayRef}.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout', stateId: id };\n}\n\nexport function createTimeoutEventId(id: string) {\n return `xstate.timeout.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createInvokeTimeoutEventId(invokeId: string) {\n return `xstate.timeout.actor.${invokeId}`;\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import isDevelopment from '#is-development';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : `Only event objects may be used with sendTo`\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n _event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, sendId: string) => {\n return actorScope.system.cancelTimer(actorScope.self, sendId);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","import type { AnyActorLogic } from './types.ts';\n\nconst sourceKeyCaches = new WeakMap<object, Map<AnyActorLogic, string>>();\n\n/** @internal */\nexport function resolveRegisteredActorSource(\n actors: Record<string, AnyActorLogic>,\n logic: AnyActorLogic\n): string | undefined {\n let cache = sourceKeyCaches.get(actors);\n if (!cache) {\n cache = new Map();\n for (const key of Object.keys(actors)) {\n const registeredLogic = actors[key];\n // Several source keys may intentionally share one implementation. The\n // first key is its canonical persistence identity when spawning by the\n // raw logic value, which cannot retain which alias was used to access it.\n if (!cache.has(registeredLogic)) {\n cache.set(registeredLogic, key);\n }\n }\n sourceKeyCaches.set(actors, cache);\n }\n\n return cache.get(logic);\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n return {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n 'xstate.listener'\n );\n}\n\n// Singleton logic instance\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, 'xstate.subscription');\n}\n\n// Singleton logic instance\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\n","import type { AnyActor, AnyActorScope } from './types.ts';\n\n/** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */\nexport const lazyActorScope = Symbol();\n\ntype InternalActorScope = AnyActorScope & {\n _parent?: AnyActor;\n [lazyActorScope]?: true;\n};\n\n/** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */\nexport function isLazyActorScope(actorScope: AnyActorScope): boolean {\n return !!(actorScope as InternalActorScope)[lazyActorScope];\n}\n\n/** Reads parent metadata without otherwise touching actor capabilities. @internal */\nexport function getActorScopeParent(\n actorScope: AnyActorScope\n): AnyActor | undefined {\n return isLazyActorScope(actorScope)\n ? (actorScope as InternalActorScope)._parent\n : actorScope.self._parent;\n}\n\n/** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */\nexport function withActorSelf<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> {\n if (!isLazyActorScope(actorScope)) {\n return Object.assign(args, { self: actorScope.self });\n }\n Object.defineProperty(args, 'self', {\n enumerable: true,\n get: () => actorScope.self\n });\n return args as T & Pick<AnyActorScope, 'self'>;\n}\n\n/** Adds the actor reference and parent without exposing the system. @internal */\nexport function withActorSelfAndParent<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined } {\n if (!isLazyActorScope(actorScope)) {\n const self = actorScope.self;\n return Object.assign(args, { self, parent: self._parent });\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined };\n}\n\n/** Adds actor capabilities without reading them until the callback does. @internal */\nexport function withActorScope<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n } {\n if (!isLazyActorScope(actorScope)) {\n const actorArgs = args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n const self = actorScope.self;\n actorArgs.self = self;\n actorArgs.system = actorScope.system;\n actorArgs.parent = self._parent;\n return actorArgs;\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n system: { enumerable: true, get: () => actorScope.system },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n}\n","import isDevelopment from '#is-development';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport { createErrorPlatformEvent } from './eventUtils.ts';\nimport {\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime\n} from './system.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport { getEventOutput } from './utils.ts';\nimport type {\n Action,\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableActionObject,\n CustomExecutableActionObject,\n EmitExecutableActionObject,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n RaiseExecutableActionObject,\n SendToExecutableActionObject,\n Snapshot,\n SpecialExecutableAction,\n SpawnExecutableActionObject,\n StartExecutableActionObject,\n StopExecutableActionObject,\n TerminateExecutableActionObject\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableActionObject\n): void | PromiseLike<void> | undefined {\n return this.action?.(...this.args);\n}\n\nfunction execEmitEffect(\n this: EmitExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.emitEvent!(this.source, this.event);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableActionObject {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableActionObject {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay ?? 0);\n}\n\nfunction execSendToEffect(\n this: SendToExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, this.id);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableActionObject,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableAction(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n if (!snapshot.timers?.[effect.id]) {\n return snapshot;\n }\n const timers = { ...snapshot.timers };\n delete timers[effect.id];\n return { ...snapshot, timers };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n let nextTimerId = snapshot._nextTimerId ?? 0;\n const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;\n effect.id = id;\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n\n return {\n ...snapshot,\n timers: {\n ...snapshot.timers,\n [id]: {\n id,\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n }\n },\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : `Cannot stop non-child actor ${update.actor.id}`\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(`Actor source '${source}' is not provided`);\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved namespace.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (isDevelopment && prefix.startsWith('xstate.')) {\n throw new Error(\n `Child actor ids with the \"xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : `Child actor id '${id}' is already in use`\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n if (typeof raisedEvent === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${raisedEvent}\" }) instead`\n : `Only event objects may be used with raise`\n );\n }\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? src ?? (logic as any).id\n } as AnyActor;\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n if (!actor) {\n internalEvents.push(\n createErrorPlatformEvent('communication', {\n message: 'Unable to send event to an undefined actor',\n event\n })\n );\n return;\n }\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n return createEnqueueObject(props, (action, ...args) => {\n pushBuiltInAction(actions, action, ...args);\n });\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableAction> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, id] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n id\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\nfunction createStartEffect(actor: AnyActor): StartExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\nexport function createSpawnEffect(\n actor: AnyActor\n): SpawnExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableActionObject {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error('Cannot terminate an active or stopped actor');\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableActionObject>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableActionObject>\n): StartExecutableActionObject[] {\n const attachedStarts: StartExecutableActionObject[] = [];\n const childStarts: StartExecutableActionObject[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\nexport function isBuiltInExecutableAction(\n action: ExecutableActionObject\n): action is SpecialExecutableAction {\n return action.kind === 'builtin';\n}\n\n/** Executes transition effects sequentially, awaiting each runtime operation. */\nexport async function executeEffects(\n effects: readonly ExecutableActionObject[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of actions) {\n const actionArgs = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n },\n actorScope\n )\n : {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n };\n\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...actionRecord.args)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (resolvedAction && '_special' in resolvedAction) {\n executableActions.push({\n kind: 'action',\n exec: execCustomEffect,\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : ((action as any).type ?? '(anonymous)')\n : action.name || '(anonymous)',\n params: actionParams,\n args: [],\n action: undefined\n });\n\n const specialAction = resolvedAction as unknown as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n\n const res = specialAction(actionArgs as any, emptyEnqueueObject);\n\n if (res && ('context' in res || 'children' in res)) {\n // Special-action patches never change `nodes`, so a shallow clone is\n // equivalent to `cloneMachineSnapshot` — and keeps this module (and\n // non-machine logic like `createFSM`) independent of State.ts.\n intermediateSnapshot = {\n ...intermediateSnapshot,\n ...(res.context !== undefined\n ? {\n context: mergeContextPatch(\n intermediateSnapshot.context,\n res.context\n )\n }\n : {}),\n ...('children' in res ? { children: res.children } : {})\n };\n }\n continue;\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, action.args)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action ? action.args : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableAction = executableAction as ExecutableActionObject;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableAction,\n actorScope\n );\n executableActions.push(typedExecutableAction);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n\nconst emptyEnqueueObject = createEnqueueObject({}, noop);\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\n}\n","import { hasAmbientInspector } from './inspectionAmbient.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${String(registryKey)}' already exists.`\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import { createActor } from './createActor.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport {\n createSnapshotSystem,\n getSnapshotActorRef,\n getSnapshotActorRefProvider,\n peekSnapshotActorRef,\n setLazySnapshotActorRef,\n setSnapshotActorRef,\n type SnapshotActorRef\n} from './snapshotActorRef.ts';\nimport {\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport { lazyActorScope } from './actorScope.ts';\n\n/** @internal */\nexport function setInertActorScopeSnapshot<T>(\n actorScope: AnyActorScope,\n snapshot: T,\n attachActorRef = true\n): T {\n const lazyState = getLazyInertActorState(actorScope);\n if (lazyState) {\n lazyState.snapshot = snapshot;\n if (lazyState.materialized) {\n (lazyState.materialized.self as any)._snapshot = snapshot;\n }\n } else {\n (actorScope.self as any)._snapshot = snapshot;\n }\n if (attachActorRef && snapshot && typeof snapshot === 'object') {\n setSnapshotActorRef(snapshot as any, actorScope.self);\n }\n return snapshot;\n}\n\n/** @internal */\nexport function isInertActorScope(actorScope: AnyActorScope): boolean {\n return (\n !!getLazyInertActorState(actorScope) ||\n !!(actorScope.self as any).options?._inert\n );\n}\n\n/** @internal */\nexport function attachSnapshotActorRef<TSnapshot>(\n actorScope: AnyActorScope,\n snapshot: TSnapshot\n): TSnapshot {\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const lazyState = getLazyInertActorState(actorScope);\n snapshotActorScopes.set(snapshot as object, actorScope);\n const create = () => {\n setSnapshotActorRef(\n snapshot as Snapshot<unknown>,\n actorScope.self,\n actorScope.system\n );\n return getSnapshotActorRef(snapshot as Snapshot<unknown>)!;\n };\n if (lazyState) {\n if (lazyState.materialized) {\n lazyState.identityProvider = create;\n } else {\n lazyState.identityProvider ??= create;\n }\n }\n setLazySnapshotActorRef(snapshot as Snapshot<unknown>, create);\n return snapshot;\n}\n\ntype LazyInertActorState = {\n snapshot: unknown;\n materialized?: AnyActorScope;\n sourceRef?: () => SnapshotActorRef;\n sourceChildren: Record<string, AnyActor | undefined>;\n identityProvider?: () => SnapshotActorRef;\n parent?: AnyActor;\n parentKnown: boolean;\n materialize: () => AnyActorScope;\n};\n\nconst lazyInertActorState = Symbol();\ntype LazyInertActorScope = AnyActorScope & {\n [lazyInertActorState]?: LazyInertActorState;\n};\nconst snapshotActorScopes = new WeakMap<object, AnyActorScope>();\nlet inertActorMaterializationObserver: (() => void) | undefined;\n\nfunction getLazyInertActorState(\n actorScope: AnyActorScope\n): LazyInertActorState | undefined {\n return (actorScope as LazyInertActorScope)[lazyInertActorState];\n}\n\nfunction materializeInertActorScope(actorScope: AnyActorScope): AnyActorScope {\n return getLazyInertActorState(actorScope)!.materialize();\n}\n\nconst lazyInertActorScopePrototype = {\n [lazyActorScope]: true,\n get _parent() {\n const actorScope = this as AnyActorScope;\n const state = getLazyInertActorState(actorScope)!;\n return state.parentKnown\n ? state.parent\n : materializeInertActorScope(actorScope).self._parent;\n },\n get self() {\n return materializeInertActorScope(this as AnyActorScope).self;\n },\n get defer() {\n return materializeInertActorScope(this as AnyActorScope).defer;\n },\n get id() {\n return materializeInertActorScope(this as AnyActorScope).id;\n },\n get logger() {\n return materializeInertActorScope(this as AnyActorScope).logger;\n },\n get sessionId() {\n return materializeInertActorScope(this as AnyActorScope).sessionId;\n },\n get stopChild() {\n return materializeInertActorScope(this as AnyActorScope).stopChild;\n },\n get system() {\n return materializeInertActorScope(this as AnyActorScope).system;\n },\n get emit() {\n return materializeInertActorScope(this as AnyActorScope).emit;\n },\n get actionExecutor() {\n return materializeInertActorScope(this as AnyActorScope).actionExecutor;\n }\n};\n\n/** Test-only allocation instrumentation. @internal */\nexport function setInertActorMaterializationObserver(\n observer: (() => void) | undefined\n): void {\n inertActorMaterializationObserver = observer;\n}\n\nfunction createMaterializedInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n sourceRef: (() => SnapshotActorRef) | undefined,\n sourceChildren: Record<string, AnyActor | undefined>,\n currentSnapshot: SnapshotFrom<T> | undefined,\n sourceSelf?: AnyActor\n): AnyActorScope {\n inertActorMaterializationObserver?.();\n const snapshotRef = sourceRef?.();\n const previousSelf = sourceSelf ?? snapshotRef?.actor;\n const baseSystem = previousSelf?.system;\n const system =\n previousSelf && baseSystem\n ? createSnapshotSystem(\n baseSystem,\n sourceChildren,\n sourceSelf ? undefined : snapshotRef?.systemState\n )\n : undefined;\n const self = createActor(\n actorLogic as AnyActorLogic,\n {\n _inert: true,\n ...(previousSelf\n ? {\n id: previousSelf.id,\n _sessionId: previousSelf.sessionId\n }\n : {}),\n ...(system ? { _systemRef: { current: system } } : {})\n } as any\n );\n if (previousSelf?._parent) {\n self._parent = previousSelf._parent;\n // `address` memoizes on first read assuming `_parent` is final; nothing\n // reads it between construction and this assignment, but drop any memo so\n // a future construction-time read cannot pin a root-shaped address.\n (self as unknown as { _address?: string })._address = undefined;\n }\n if (currentSnapshot) {\n (self as any)._snapshot = currentSnapshot;\n }\n\n // Reuse the branch actor's scope while keeping planning transactional.\n return Object.create((self as any)._actorScope, {\n defer: { value: () => {} },\n stopChild: { value: (child: AnyActor) => (child as any)._stop() },\n actionExecutor: { value: () => {} }\n });\n}\n\n/** @internal */\nexport function createInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot?: SnapshotFrom<T>,\n sourceSelf?: AnyActor,\n sourceActorScope?: AnyActorScope\n): AnyActorScope {\n const sourceScope =\n sourceActorScope ??\n (snapshot && typeof snapshot === 'object'\n ? snapshotActorScopes.get(snapshot as object)\n : undefined);\n const sourceState = sourceScope\n ? getLazyInertActorState(sourceScope)\n : undefined;\n const eagerSourceRef =\n snapshot && typeof snapshot === 'object'\n ? peekSnapshotActorRef(snapshot as Snapshot<unknown>)\n : undefined;\n const sourceRef =\n sourceState?.identityProvider ??\n (snapshot && typeof snapshot === 'object'\n ? getSnapshotActorRefProvider(snapshot as Snapshot<unknown>)\n : undefined);\n const state = {\n snapshot,\n sourceRef,\n sourceChildren: isMachineSnapshot(snapshot)\n ? (snapshot as any).children\n : {},\n identityProvider: sourceState?.identityProvider ?? sourceRef,\n parent:\n sourceSelf?._parent ??\n sourceState?.parent ??\n eagerSourceRef?.actor._parent,\n parentKnown:\n !!sourceSelf ||\n !!sourceState?.parentKnown ||\n !!eagerSourceRef ||\n !snapshot\n } as LazyInertActorState;\n state.materialize = () =>\n (state.materialized ??= createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n state.snapshot as SnapshotFrom<T>,\n sourceSelf\n ));\n if (!state.identityProvider && !snapshot) {\n const identitySnapshot = {} as Snapshot<unknown>;\n const identitySourceRef = state.sourceRef;\n const identitySourceChildren = state.sourceChildren;\n let identityScope: AnyActorScope | undefined;\n let identityRef: SnapshotActorRef | undefined;\n const getIdentityScope = () =>\n (identityScope ??= createMaterializedInertActorScope(\n actorLogic,\n identitySourceRef,\n identitySourceChildren,\n undefined,\n sourceSelf\n ));\n state.materialize = () => {\n const scope = getIdentityScope();\n if (state.snapshot !== undefined) {\n (scope.self as any)._snapshot = state.snapshot;\n }\n return (state.materialized = scope);\n };\n state.identityProvider = () => {\n if (identityRef) {\n return identityRef;\n }\n const scope = getIdentityScope();\n setSnapshotActorRef(identitySnapshot, scope.self, scope.system);\n return (identityRef = getSnapshotActorRef(identitySnapshot)!);\n };\n }\n const actorScope = Object.create(lazyInertActorScopePrototype) as ActorScope<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n any,\n EmittedFrom<T>\n >;\n (actorScope as LazyInertActorScope)[lazyInertActorState] = state;\n return actorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nexport function getInitialSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.initialTransition(input, actorScope)[0];\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @deprecated Use `transition(…)` instead.\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * undefined, // snapshot (or initial state if undefined)\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * nextSnapshot, // snapshot\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nexport function getNextSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic, snapshot);\n const transitionResult = actorLogic.transition(snapshot, event, actorScope);\n const nextSnapshot = Array.isArray(transitionResult)\n ? transitionResult[0]\n : transitionResult;\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n return nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(actorScope, nextSnapshot);\n}\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport {\n createAfterEvent,\n createAfterEventId,\n createDoneStateEvent,\n createInvokeTimeoutEvent,\n createInvokeTimeoutEventId,\n createTimeoutEvent,\n createTimeoutEventId\n} from './eventUtils.ts';\nimport {\n XSTATE_INIT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n XSTATE_TIMER\n} from './constants.ts';\nimport {\n getEventOutput,\n isErrorEvent,\n matchesEvent,\n matchesEventDescriptor\n} from './utils.ts';\nimport {\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n ExecutableActionObject,\n HistoryValue,\n MachineContext,\n StateValue,\n TransitionDefinition,\n AnyAction,\n AnyTransitionConfig,\n AnyActor,\n AnyActorScope,\n DoneStateEvent\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n resolveReferencedActor,\n toTransitionConfigArray\n} from './utils.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n assertChildIdFree,\n createEnqueueObject,\n createTerminationEffect,\n createTransitionEnqueue,\n createSendToEffect,\n deriveDeferredStarts,\n mergeContextPatch,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { parseDurationToMilliseconds } from './delay.ts';\nimport { transitionEffectSignal, transitionEffectTargets } from './system.ts';\nimport { isInertActorScope } from './getNextSnapshot.ts';\nimport {\n getActorScopeParent,\n isLazyActorScope,\n withActorSelfAndParent,\n withActorScope\n} from './actorScope.ts';\n\ntype AnyStateNodeIterable = Iterable<AnyStateNode>;\n\nfunction getConfiguredDelayValue(\n delay: number | string,\n delaySource: Record<string, any>\n) {\n if (typeof delay !== 'string') {\n return delay;\n }\n\n const referencedDelay = delaySource[delay];\n if (referencedDelay !== undefined) {\n return referencedDelay;\n }\n\n return parseDurationToMilliseconds(delay) ?? delay;\n}\n\nfunction resolveDelay(\n delay: number | string | ((args: any) => number),\n delaySource: Record<string, any>,\n args: {\n context: MachineContext;\n event: EventObject;\n stateNode: AnyStateNode;\n input?: Record<string, unknown>;\n }\n) {\n if (typeof delay === 'function') {\n return delay(args);\n }\n\n const configuredDelay = getConfiguredDelayValue(delay, delaySource);\n if (typeof configuredDelay === 'function') {\n return configuredDelay(args);\n }\n\n return configuredDelay;\n}\n\nfunction getStateInput(snapshot: AnyMachineSnapshot, stateNodeId: string) {\n return snapshot._stateInputs?.[stateNodeId];\n}\n\nexport function isAtomicStateNode(stateNode: AnyStateNode) {\n return (\n stateNode.type === 'atomic' ||\n stateNode.type === 'final' ||\n stateNode.type === 'choice'\n );\n}\n\nfunction getChildren(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nexport function getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n const activeParentSet = new Set<AnyStateNode>();\n for (const stateNode of nodeSet) {\n if (stateNode.parent) {\n activeParentSet.add(stateNode.parent);\n }\n }\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && !activeParentSet.has(s)) {\n for (const sn of getInitialStateNodes(s)) {\n nodeSet.add(sn);\n }\n continue;\n }\n\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodes(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n\n // add all ancestors\n // Stop walking up as soon as we hit a node already in the set: its own\n // ancestor chain is guaranteed to be added when it is visited by this loop\n // (Set iteration visits elements added during iteration), so shared ancestor\n // chains are never re-walked once per descendant.\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m && !nodeSet.has(m)) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n const adjList = new Map<AnyStateNode, Array<AnyStateNode>>();\n\n for (const s of config) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (!s.parent) {\n continue;\n }\n\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n\n const getValueFromAdj = (baseNode: AnyStateNode): StateValue => {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (!childStateNode) {\n return {};\n }\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode);\n }\n\n return stateValue;\n };\n\n return getValueFromAdj(rootNode);\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nfunction getLegacyEventType(event: EventObject): string | undefined {\n switch (event.type) {\n case 'xstate.done.actor':\n case 'xstate.error.actor':\n return `${event.type}.${(event as any).actorId}`;\n case 'xstate.snapshot.actor':\n return `xstate.snapshot.${(event as any).actorId}`;\n case 'xstate.done.state':\n return `xstate.done.state.${(event as any).stateId}`;\n case 'xstate.after':\n return `xstate.after.${(event as any).delay}.${(event as any).stateId}`;\n case 'xstate.timeout':\n return `xstate.timeout.${(event as any).stateId}`;\n case 'xstate.timeout.actor':\n return `xstate.timeout.actor.${(event as any).actorId}`;\n default:\n return undefined;\n }\n}\n\nfunction getEventTypeAliases(event: EventObject): string[] {\n const legacyType = getLegacyEventType(event);\n return legacyType ? [event.type, legacyType] : [event.type];\n}\n\nexport function getEventDescriptorKey(event: EventObject): string {\n const legacyType = getLegacyEventType(event);\n return legacyType ? `${event.type}|${legacyType}` : event.type;\n}\n\nexport function matchesActorSession(\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorId: string\n): boolean {\n const child = snapshot.children[actorId];\n if (!child || !('sessionId' in event)) {\n return true;\n }\n // One rule: a ref that knows its incarnation compares it; a remote handle\n // without a host-supplied token (sessionId undefined) defers to the\n // runtime that owns the child.\n return (\n child.sessionId === undefined ||\n child.sessionId === (event as { sessionId?: string }).sessionId\n );\n}\n\nfunction normalizeLegacyInternalEvent(\n event: EventObject,\n machine: AnyStateMachine\n): EventObject {\n if (\n event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.done.state' ||\n event.type === 'xstate.after' ||\n event.type === 'xstate.timeout' ||\n event.type === 'xstate.timeout.actor'\n ) {\n return event;\n }\n\n const normalizeWithId = (\n prefix: string,\n type: string,\n idKey: 'actorId' | 'stateId'\n ) =>\n event.type.startsWith(prefix)\n ? {\n ...event,\n type,\n [idKey]: (event as any)[idKey] ?? event.type.slice(prefix.length)\n }\n : undefined;\n\n const normalized =\n normalizeWithId('xstate.done.actor.', 'xstate.done.actor', 'actorId') ??\n normalizeWithId('xstate.error.actor.', 'xstate.error.actor', 'actorId') ??\n normalizeWithId('xstate.snapshot.', 'xstate.snapshot.actor', 'actorId') ??\n normalizeWithId('xstate.done.state.', 'xstate.done.state', 'stateId') ??\n normalizeWithId(\n 'xstate.timeout.actor.',\n 'xstate.timeout.actor',\n 'actorId'\n ) ??\n normalizeWithId('xstate.timeout.', 'xstate.timeout', 'stateId');\n\n if (normalized) {\n return normalized;\n }\n\n const afterPrefix = 'xstate.after.';\n if (!event.type.startsWith(afterPrefix)) {\n return event;\n }\n\n const stateId = [...machine.idMap.keys()]\n .sort((a, b) => b.length - a.length)\n .find((id) => event.type.endsWith(`.${id}`));\n if (!stateId) {\n return event;\n }\n const delayText = event.type.slice(afterPrefix.length, -stateId.length - 1);\n return {\n ...event,\n type: 'xstate.after',\n delay: Number.isNaN(+delayText) ? delayText : +delayText,\n stateId\n } as AnyEventObject;\n}\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n event: TEvent\n): Array<TransitionDefinition<any, TEvent>> {\n const eventTypes = getEventTypeAliases(event);\n const exactMatches = eventTypes.flatMap(\n (eventType) => stateNode.transitions.get(eventType) ?? []\n );\n const wildcardCandidates = [...stateNode.transitions.keys()]\n .filter(\n (eventDescriptor) =>\n !eventTypes.includes(eventDescriptor) &&\n eventTypes.some((eventType) =>\n matchesEventDescriptor(eventType, eventDescriptor)\n )\n )\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return exactMatches.length\n ? [...exactMatches, ...wildcardCandidates]\n : wildcardCandidates;\n}\n\nfunction scheduleDelayedEvent(\n stateNode: AnyStateNode,\n timerId: string,\n resolveEvent: (args: any) => AnyEventObject,\n resolveScheduledDelay: (x: {\n context: MachineContext;\n event: EventObject;\n delays: Record<string, any>;\n input?: Record<string, unknown>;\n }) => any\n) {\n const oldEntry = stateNode.entry;\n stateNode.entry = (x: any, enq: any) => {\n enq.raise(resolveEvent(x) as any, {\n id: timerId,\n delay: resolveScheduledDelay(x)\n });\n return typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;\n };\n const oldExit = stateNode.exit;\n stateNode.exit = (_: any, enq: any) => {\n enq.cancel(timerId);\n return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;\n };\n}\n\n/** All delayed transitions from the config. */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n const timeoutConfig = (stateNode.config as any).timeout;\n const onTimeoutConfig = (stateNode.config as any).onTimeout;\n const invokeDefs = stateNode.invoke.filter(\n (invokeDef) => invokeDef.timeout !== undefined\n );\n\n if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {\n return [];\n }\n\n if (isDevelopment && timeoutConfig !== undefined && !onTimeoutConfig) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n\n if (isDevelopment) {\n for (const invokeDef of invokeDefs) {\n if (!invokeDef.onTimeout) {\n throw new Error(\n `Invoke on state \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n }\n }\n\n // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and\n // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on\n // entry (and cancelled on exit) plus a transition that catches it. They\n // differ only in the event raised, the transition(s) caught, and whether the\n // delay resolves against the machine's `delays` map (invoke timeouts do not).\n //\n // `xstate.timeout` is a dedicated event category so a state-level `timeout`\n // cannot collide with an explicit `after` entry on the same state. Invoke\n // timeouts are scheduled on the enclosing state; completion transitions\n // cancel the timer separately, so it clears even when the parent stays active.\n const sources: Array<{\n event: AnyEventObject;\n timerId: string;\n resolveEvent?: (args: any) => AnyEventObject;\n eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n delay: any;\n transitions: unknown;\n fromDelaysMap: boolean;\n }> = [];\n\n if (afterConfig) {\n for (const key of Object.keys(afterConfig)) {\n const delay = Number.isNaN(+key) ? key : +key;\n sources.push({\n event: createAfterEvent(delay, stateNode.id),\n timerId: createAfterEventId(delay, stateNode.id),\n delay,\n transitions: afterConfig[key],\n fromDelaysMap: true\n });\n }\n }\n\n if (timeoutConfig !== undefined && onTimeoutConfig) {\n sources.push({\n event: createTimeoutEvent(stateNode.id),\n timerId: createTimeoutEventId(stateNode.id),\n delay: timeoutConfig,\n transitions: onTimeoutConfig,\n fromDelaysMap: true\n });\n }\n\n for (const invokeDef of invokeDefs) {\n sources.push({\n event: createInvokeTimeoutEvent(invokeDef.id),\n timerId: createInvokeTimeoutEventId(invokeDef.id),\n resolveEvent: ({ children }: any) =>\n createInvokeTimeoutEvent(\n invokeDef.id,\n children[invokeDef.id]?.sessionId\n ),\n eventMatcher: (event, snapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id),\n delay: invokeDef.timeout!,\n transitions: invokeDef.onTimeout,\n fromDelaysMap: false\n });\n }\n\n // `delay` here is the raw config value, retained only as metadata on the\n // transition definition — the live delay is resolved at runtime in the\n // scheduled entry action, so no eager resolution is needed.\n const delayedTransitions: Array<\n AnyTransitionConfig & {\n event: string;\n delay: any;\n _eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n }\n > = [];\n\n for (const {\n event,\n timerId,\n resolveEvent,\n eventMatcher,\n delay,\n transitions,\n fromDelaysMap\n } of sources) {\n scheduleDelayedEvent(\n stateNode,\n timerId,\n resolveEvent ?? (() => event),\n (x) =>\n resolveDelay(delay, fromDelaysMap ? x.delays : {}, {\n context: x.context,\n event: x.event,\n stateNode,\n input: x.input\n })\n );\n const { type: eventType, ...eventPattern } = event;\n for (const transition of toTransitionConfigArray(transitions as any)) {\n delayedTransitions.push({\n ...transition,\n matches: {\n ...transition.matches,\n ...Object.fromEntries(\n Object.entries(eventPattern).filter(\n ([, value]) => value !== undefined\n )\n )\n },\n event: eventType,\n delay,\n _eventMatcher: eventMatcher\n });\n }\n }\n\n return delayedTransitions.map((delayedTransition) => ({\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition as AnyTransitionConfig\n ),\n delay: delayedTransition.delay\n }));\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n assertLegalTargetSet(stateNode, target);\n\n const transition = {\n ...transitionConfig,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nfunction isStateNodeDescendantOf(\n stateNode: AnyStateNode,\n ancestor: AnyStateNode\n): boolean {\n for (let current = stateNode.parent; current; current = current.parent) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLeastCommonStateNodeAncestor(\n left: AnyStateNode,\n right: AnyStateNode\n): AnyStateNode | undefined {\n const leftAncestors = new Set<AnyStateNode>();\n for (\n let current: AnyStateNode | undefined = left;\n current;\n current = current.parent\n ) {\n leftAncestors.add(current);\n }\n for (\n let current: AnyStateNode | undefined = right;\n current;\n current = current.parent\n ) {\n if (leftAncestors.has(current)) {\n return current;\n }\n }\n return undefined;\n}\n\nfunction assertLegalTargetSet(\n source: AnyStateNode,\n targets: readonly AnyStateNode[] | undefined\n): void {\n if (!targets || targets.length < 2) {\n return;\n }\n for (let leftIndex = 0; leftIndex < targets.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < targets.length;\n rightIndex++\n ) {\n const left = targets[leftIndex];\n const right = targets[rightIndex];\n const commonAncestor = getLeastCommonStateNodeAncestor(left, right);\n if (\n left === right ||\n isStateNodeDescendantOf(left, right) ||\n isStateNodeDescendantOf(right, left) ||\n commonAncestor?.type !== 'parallel'\n ) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${source.id}': target set is not a legal SCXML configuration.`\n : `Invalid target set for '${source.id}'`\n );\n }\n }\n }\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nexport function formatRouteTransitions(rootStateNode: AnyStateNode): void {\n const routeTransitions: AnyTransitionDefinition[] = [];\n const collectRoutes = (states: Record<string, AnyStateNode>) => {\n Object.values(states).forEach((sn) => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const routeConfig = sn.config.route;\n const routeMatches = ({ event }: { event: any }) =>\n event.to === `#${routeId}`;\n\n if (typeof routeConfig === 'function') {\n // Transition-style route: the function is the guard and resolver.\n // Returning undefined/false blocks the route; returning true or a\n // config object allows it.\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', {\n guard: routeMatches,\n to: (args: any) => {\n const result = routeConfig(args);\n if (!result) {\n return undefined;\n }\n return {\n ...(result === true ? {} : result),\n target: `#${routeId}`\n };\n }\n } as AnyTransitionConfig)\n );\n if (sn.states) {\n collectRoutes(sn.states);\n }\n return;\n }\n\n const { guard: _guard, ...routeOptions } = routeConfig as any;\n const transition: AnyTransitionConfig = {\n ...routeOptions,\n guard: routeMatches,\n target: `#${routeId}`\n };\n\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', transition)\n );\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions as any);\n }\n}\n\nfunction resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map((target) => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n : `Invalid transition for '${stateNode.id}': ${err.message}`\n );\n }\n } else {\n throw new Error(\n isDevelopment\n ? `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n : `Invalid target: \"${target}\"`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition(\n stateNode: AnyStateNode & { type: 'history' }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n if (stateNode.parent!.type === 'parallel') {\n return {\n target: [stateNode.parent!],\n source: stateNode,\n reenter: false,\n eventType: '' as any\n };\n }\n return stateNode.parent!.initial as AnyTransitionDefinition;\n }\n const target = normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n assertLegalTargetSet(stateNode, target);\n return {\n target,\n source: stateNode,\n reenter: false,\n eventType: '' as any,\n to: (stateNode.config as any)._historyDefaultTransition\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const target of descStateNode.initial.target ?? []) {\n iter(target);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n for (const initialState of set) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n set.add(ancestor);\n }\n }\n\n return set;\n}\n\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n const result = stateNode.states?.[stateKey];\n if (!result) {\n throw new Error(\n isDevelopment && !stateNode.states\n ? `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n : `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n );\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift()!;\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nexport function getStateNodes(\n stateNode: AnyStateNode,\n stateValue: StateValue\n): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(\n `State '${stateValue}' does not exist on '${stateNode.id}'`\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = new Array<AnyStateNode>(childStateKeys.length);\n const allStateNodes: Array<AnyStateNode> = [\n stateNode.machine.root,\n stateNode\n ];\n\n for (let i = 0; i < childStateKeys.length; i++) {\n const subStateNode = getStateNode(stateNode, childStateKeys[i]);\n childStateNodes[i] = subStateNode;\n allStateNodes.push(subStateNode);\n }\n\n for (let i = 0; i < childStateKeys.length; i++) {\n allStateNodes.push(\n ...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]!)\n );\n }\n\n return allStateNodes;\n}\n\nexport type TransitionSelectionResult = {\n enabled: boolean;\n result: unknown;\n reusable: boolean;\n};\n\nexport type TransitionSelectionResults = Map<\n AnyTransitionDefinition,\n TransitionSelectionResult\n>;\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any // TStateSchema\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const subStateKeys = Object.keys(stateValue);\n const subStateKey = subStateKeys[0];\n\n if (subStateKeys.length === 1) {\n const childStateNode = getStateNode(stateNode, subStateKey);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKey]!,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of subStateKeys) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return allInnerTransitions;\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction hasDescendantState(\n stateNodes: Set<AnyStateNode>,\n parentStateNode: AnyStateNode\n): boolean {\n for (const stateNode of stateNodes) {\n if (isDescendant(stateNode, parentStateNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const s1Size =\n s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;\n const s2Size =\n s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;\n\n if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {\n [s1, s2] = [s2, s1];\n }\n\n const set1 = s1 instanceof Set ? s1 : new Set(s1);\n for (const item of s2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n const exitSets = new Map<AnyTransitionDefinition, Array<AnyStateNode>>();\n\n const getExitSet = (transition: AnyTransitionDefinition) => {\n let exitSet = exitSets.get(transition);\n if (!exitSet) {\n exitSet = computeExitSet(\n [transition],\n stateNodeSet,\n snapshot,\n resolveTransition\n );\n exitSets.set(transition, exitSet);\n }\n\n return exitSet;\n };\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(getExitSet(t1), getExitSet(t2))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else if (t2.source.type === 'final' && t1.source.type !== 'final') {\n // A transition sourced in a final state yields to a conflicting\n // transition from a live state, so a done region doesn't keep\n // consuming events its siblings can still handle.\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n\n return Array.from(filteredTransitions);\n}\n\ntype ResolvableTransition = Parameters<typeof getTransitionResult>[0];\ntype TransitionResultResolver = (\n transition: ResolvableTransition\n) => ReturnType<typeof getTransitionResult>;\n\nfunction createTransitionResultResolver(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n resolveActions: boolean,\n selectionResults?: TransitionSelectionResults\n): TransitionResultResolver {\n let cache:\n | Map<ResolvableTransition, ReturnType<typeof getTransitionResult>>\n | undefined;\n return (transition) => {\n if (!transition.to) {\n return getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n }\n let result = cache?.get(transition);\n if (!result) {\n result = getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n (cache ??= new Map()).set(transition, result);\n }\n return result;\n };\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target' | 'source'>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const historyValue = snapshot.historyValue;\n const { targets } = resolveTransition(transition);\n if (!targets) {\n return [];\n }\n\n const targetSet = new Set<AnyStateNode>();\n\n for (const targetNode of targets) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targetSet.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n snapshot,\n resolveTransition\n )) {\n targetSet.add(node);\n }\n }\n } else {\n targetSet.add(targetNode);\n }\n }\n\n return [...targetSet];\n}\n\n/**\n * Narrows a parallel domain to the single child region that contains every\n * effective target, so that a transition confined to one region does not exit\n * (and reset) its sibling regions.\n */\nfunction narrowParallelDomain(\n domain: AnyStateNode,\n targetStates: Array<AnyStateNode>\n): AnyStateNode {\n let narrowed = domain;\n while (narrowed.type === 'parallel') {\n const region = getChildren(narrowed).find((child) =>\n targetStates.every(\n (target) => target === child || isDescendant(target, child)\n )\n );\n if (!region) {\n break;\n }\n narrowed = region;\n }\n return narrowed;\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(\n transition,\n snapshot,\n resolveTransition\n );\n\n const { targets, reenter } = resolveTransition(transition);\n\n if (transition._transitionDomain) {\n if (\n transition._transitionDomain === 'internal' &&\n transition.source.type === 'compound' &&\n targetStates.every((target) => isDescendant(target, transition.source))\n ) {\n return transition.source;\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (\n ancestor.type === 'compound' &&\n tail.every((stateNode) => isDescendant(stateNode, ancestor))\n ) {\n return ancestor;\n }\n }\n\n return;\n }\n\n // A history target that restores the source itself must exit and reenter\n // the source (SCXML domain = the source's ancestor), unlike a plain\n // non-reentering self-target: the enter set restores the stored\n // configuration from outside the source, so the exit set must match or the\n // source's invoked actors are re-created without being stopped.\n const restoresSourceViaHistory =\n targets?.some(isHistoryNode) &&\n targetStates.some((target) => target === transition.source);\n\n if (\n !restoresSourceViaHistory &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n // Targets are contained within the source. A reentering transition\n // exits and reenters the source itself; otherwise the domain narrows\n // past parallel nodes so sibling regions are left untouched.\n return reenter\n ? transition.source\n : narrowParallelDomain(transition.source, targetStates);\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n // Find the least common ancestor (LCA) of the source and effective targets.\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n // A cross-region transition (source in one parallel region, targets in\n // another) only exits the region containing its targets; the source\n // region and other sibling regions stay put unless it reenters.\n return reenter ? ancestor : narrowParallelDomain(ancestor, targetStates);\n }\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (reenter) {\n return;\n }\n\n return narrowParallelDomain(transition.source.machine.root, targetStates);\n}\n\nfunction computeExitSet(\n transitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n for (const transition of transitions) {\n const { targets, reenter } = resolveTransition(transition);\n\n if (targets?.length) {\n const domain = getTransitionDomain(\n transition,\n snapshot,\n resolveTransition\n );\n\n if (reenter && transition.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\ntype Microstep = readonly [AnyMachineSnapshot, ExecutableActionObject[]];\n\nexport function initialMicrostep(\n root: AnyStateNode,\n preInitialState: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n initEvent: AnyEventObject,\n internalQueue: AnyEventObject[]\n): Microstep {\n const initialStateNodes = [...getInitialStateNodes(root)];\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const collectDefaultEntryStates = (stateNode: AnyStateNode): void => {\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n for (const target of stateNode.initial.target ?? []) {\n collectDefaultEntryStates(target);\n }\n } else if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n collectDefaultEntryStates(child);\n }\n }\n };\n collectDefaultEntryStates(root);\n return microstep(\n [\n {\n target: initialStateNodes.filter(\n (stateNode) =>\n !initialStateNodes.some(\n (other) => other !== stateNode && isDescendant(other, stateNode)\n )\n ),\n source: root,\n reenter: true,\n eventType: null as any,\n toJSON: null as any,\n _statesForDefaultEntry: [...statesForDefaultEntry]\n } as AnyTransitionDefinition\n ],\n preInitialState,\n actorScope,\n initEvent,\n true,\n internalQueue\n );\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>,\n selectionResults?: TransitionSelectionResults\n): Microstep {\n const executableActions: ExecutableActionObject[] = [];\n\n if (!transitions.length) {\n return [currentSnapshot, executableActions];\n }\n\n {\n const mutStateNodeSet = new Set(currentSnapshot.nodes as StateNode[]);\n let historyValue = currentSnapshot.historyValue;\n const originalContext = currentSnapshot.context;\n\n const filteredTransitions =\n transitions.length === 1\n ? transitions\n : removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n currentSnapshot,\n createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n false,\n selectionResults\n )\n );\n const getCurrentTransitionResult = createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n true,\n selectionResults\n );\n const changesState = filteredTransitions.some((transition) => {\n const { targets, reenter } = getCurrentTransitionResult(transition);\n return !!targets?.length || !!reenter;\n });\n const getStateActionsAndContext = (\n transitionFn: any,\n context: MachineContext,\n children: AnyMachineSnapshot['children'],\n input: Record<string, unknown> | undefined\n ): [\n actions: any[],\n context: MachineContext | undefined,\n internalEvents: EventObject[] | undefined\n ] => {\n if (transitionFn.length === 2) {\n // enqueue action; retrieve\n const actions: any[] = [];\n const internalEvents: EventObject[] = [];\n let updatedContext: MachineContext | undefined;\n\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true\n );\n\n const args = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context,\n event,\n children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n },\n actorScope\n )\n : {\n context,\n event,\n parent: actorScope.self._parent,\n self: actorScope.self,\n children,\n system: actorScope.system,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n };\n const res = transitionFn(args, enqueue);\n\n if (res?.context !== undefined) {\n updatedContext = mergeContextPatch(context, res.context);\n }\n\n return [actions, updatedContext, internalEvents];\n }\n\n // For 1-argument actions, wrap them to include input\n // Preserve _special flag if present (for entry/exit actions)\n const wrappedAction = Object.assign(\n (args: any, enqueue: any) =>\n transitionFn(\n isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: args.context,\n event: args.event,\n output: args.output,\n children: args.children,\n actions: args.actions,\n actors: args.actors,\n input\n },\n actorScope\n )\n : { ...args, input },\n enqueue\n ),\n '_special' in transitionFn ? { _special: true } : {}\n );\n return [[wrappedAction], undefined, undefined];\n };\n\n let nextState = currentSnapshot;\n const getInvokeStopActions = (\n stateNode: AnyStateNode,\n children: AnyMachineSnapshot['children']\n ): AnyAction[] => {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const invokeDef of stateNode.invoke) {\n const child = children[invokeDef.id];\n if (child) {\n enqueue.stop(child);\n }\n }\n return actions;\n };\n const exitStates = () => {\n const statesToExit = computeExitSet(\n filteredTransitions,\n mutStateNodeSet,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: HistoryValue | undefined;\n const currentStateNodes = [...mutStateNodeSet];\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of Object.values(exitStateNode.states)) {\n if (historyNode.type !== 'history') {\n continue;\n }\n\n const predicate =\n historyNode.history === 'deep'\n ? (sn: AnyStateNode) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode)\n : (sn: AnyStateNode) => sn.parent === exitStateNode;\n\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] = currentStateNodes.filter(predicate);\n }\n }\n\n for (const exitStateNode of statesToExit) {\n const stateInput = getStateInput(currentSnapshot, exitStateNode.id);\n\n const [exitActions, nextContext, internalEvents] = exitStateNode.exit\n ? getStateActionsAndContext(\n exitStateNode.exit,\n nextState.context,\n currentSnapshot.children,\n stateInput\n )\n : [[], undefined, undefined];\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n if (nextContext) {\n nextState = cloneMachineSnapshot(nextState, {\n context: nextContext\n });\n }\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n exitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const invokeStopActions = getInvokeStopActions(\n exitStateNode,\n nextState.children\n );\n if (invokeStopActions.length) {\n const [stoppedState, stopEffects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n invokeStopActions\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n }\n\n mutStateNodeSet.delete(exitStateNode);\n }\n\n historyValue = changedHistory || historyValue;\n };\n\n // Exit states\n if (!isInitial && changesState) {\n exitStates();\n }\n\n let context = nextState.context;\n const transitionActions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n\n for (const t of filteredTransitions) {\n if (t.actions) {\n transitionActions.push(...toArray(t.actions));\n }\n const res = getCurrentTransitionResult(t);\n if (res.context !== undefined) {\n context = mergeContextPatch(context, res.context);\n }\n if (res.actions) {\n transitionActions.push(...res.actions);\n }\n if (res.internalEvents) {\n internalEvents.push(...res.internalEvents);\n }\n }\n\n if (internalEvents.length) {\n internalQueue.push(...internalEvents);\n }\n\n const enterStates = () => {\n const getMachineOutput = (rootCompletionNode: AnyStateNode) => {\n const rootNode = nextState.machine.root;\n\n let completionOutput: unknown;\n if (\n rootCompletionNode.output !== undefined &&\n rootCompletionNode.parent\n ) {\n const rootDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootNode.id\n ) as DoneStateEvent | undefined;\n completionOutput =\n rootDoneEvent && rootCompletionNode.parent === rootNode\n ? rootDoneEvent.output\n : resolveOutput(\n rootCompletionNode.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[rootCompletionNode.id]\n );\n } else if (rootCompletionNode.type === 'parallel') {\n const parallelDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootCompletionNode.id\n ) as DoneStateEvent | undefined;\n completionOutput = parallelDoneEvent?.output;\n }\n\n if (rootNode.output === undefined) {\n return rootCompletionNode.parent === rootNode\n ? completionOutput\n : undefined;\n }\n\n return resolveOutput(\n rootNode.output,\n nextState.context,\n createDoneStateEvent(rootCompletionNode.id, completionOutput),\n actorScope.self\n );\n };\n\n const statesToEnter = new Set<AnyStateNode>();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const historyDefaultsByParent = new Map<\n AnyStateNode,\n AnyTransitionDefinition[]\n >();\n const addAncestorStatesToEnter = (\n ancestors: AnyStateNode[],\n reentrancyDomain: AnyStateNode | undefined\n ) => {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n }\n };\n\n const addDescendantStatesToEnter = (stateNode: AnyStateNode) => {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s);\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n } else {\n const historyDefaultTransition =\n resolveHistoryDefaultTransition(stateNode);\n const historyParent = stateNode.parent!;\n statesForDefaultEntry.add(historyParent);\n const defaults = historyDefaultsByParent.get(historyParent) ?? [];\n defaults.push(historyDefaultTransition);\n historyDefaultsByParent.set(historyParent, defaults);\n const { targets } = getCurrentTransitionResult(\n historyDefaultTransition\n );\n for (const s of targets ?? []) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(s);\n }\n\n for (const s of targets ?? []) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n }\n return;\n }\n\n if (stateNode.type === 'compound') {\n const initialStates =\n getCurrentTransitionResult(stateNode.initial).targets ?? [];\n\n for (const initialState of initialStates) {\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n }\n }\n statesForDefaultEntry.add(stateNode);\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(initialState);\n }\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n getProperAncestors(initialState, stateNode),\n undefined\n );\n }\n return;\n }\n\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n };\n\n for (const transition of filteredTransitions) {\n const domain = getTransitionDomain(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n const { targets, reenter } = getCurrentTransitionResult(transition);\n\n for (const targetNode of targets ?? []) {\n if (\n !isHistoryNode(targetNode) &&\n (transition.source !== targetNode ||\n transition.source !== domain ||\n reenter)\n ) {\n statesToEnter.add(targetNode);\n statesForDefaultEntry.add(targetNode);\n }\n addDescendantStatesToEnter(targetNode);\n }\n const targetStates = getEffectiveTargetStates(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(\n ancestors,\n !transition.source.parent && reenter ? undefined : domain\n );\n }\n if (reenter && domain === transition.source) {\n // A reentering transition whose domain is its own source exits and\n // reenters the source, so the source must be entered explicitly —\n // it has no ancestor inside the domain to add it.\n statesToEnter.add(transition.source);\n }\n }\n\n if (isInitial) {\n for (const stateNode of (filteredTransitions[0] as any)\n ._statesForDefaultEntry ?? [currentSnapshot.machine.root]) {\n statesForDefaultEntry.add(stateNode);\n }\n }\n\n const stateInputMap: Record<string, Record<string, unknown>> = {\n ...currentSnapshot._stateInputs\n };\n let stateInputsChanged = false;\n for (const transition of filteredTransitions) {\n const { targets, input } = getCurrentTransitionResult(transition);\n if (input && targets) {\n for (const targetNode of targets) {\n stateInputMap[targetNode.id] = input;\n stateInputsChanged = true;\n }\n }\n }\n\n const completedNodes = new Set<AnyStateNode>();\n const children = { ...nextState.children };\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: AnyAction[] = [];\n\n let invoked = false;\n for (const invokeDef of stateNodeToEnter.invoke) {\n invoked = true;\n\n let src = invokeDef.logic;\n if (typeof src === 'function') {\n src = src({\n actors: currentSnapshot.machine.sources.actors,\n context: nextState.context,\n event,\n self: actorScope.self\n });\n }\n\n const logic =\n typeof src === 'string'\n ? resolveReferencedActor(currentSnapshot.machine, src)\n : src;\n\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in machine '${currentSnapshot.machine.id}'`\n : `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented`\n );\n }\n\n const input =\n typeof invokeDef.input === 'function'\n ? invokeDef.input({\n self: actorScope.self,\n context: nextState.context,\n event,\n output: getEventOutput(event)\n })\n : invokeDef.input;\n\n assertChildIdFree(actorScope, invokeDef.id);\n const actor = actorScope.system.createActorRef(logic, {\n ...invokeDef,\n input,\n parent: actorScope.self,\n syncSnapshot: !!invokeDef.onSnapshot\n });\n\n actions.push({\n action: builtInActions['@xstate.spawn'],\n args: [actor]\n });\n\n if (invokeDef.id) {\n children[invokeDef.id] = actor;\n }\n }\n\n if (invoked) {\n nextState = cloneMachineSnapshot(nextState, { children });\n }\n let context = nextState.context;\n let contextChangedByEntry = false;\n\n const stateInput = stateInputMap[stateNodeToEnter.id];\n\n if (stateNodeToEnter.entry) {\n const [resultActions, nextContext, nextInternalEvents] =\n getStateActionsAndContext(\n stateNodeToEnter.entry,\n context,\n children,\n stateInput\n );\n actions.push(...resultActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n if (nextContext) {\n context = nextContext;\n contextChangedByEntry = true;\n }\n }\n\n if (contextChangedByEntry) {\n nextState.context = context;\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const defaultTransitions = [\n stateNodeToEnter.initial,\n ...(historyDefaultsByParent.get(stateNodeToEnter) ?? [])\n ].filter(Boolean);\n for (const defaultTransition of defaultTransitions) {\n const {\n actions: initialActions,\n context: initialContext,\n input: initialInput,\n internalEvents: initialInternalEvents\n } = getTransitionResult(\n defaultTransition,\n nextState,\n event,\n actorScope\n );\n if (initialActions) {\n actions.push(...initialActions);\n }\n if (initialInternalEvents?.length) {\n internalQueue.push(...initialInternalEvents);\n }\n if (initialContext !== undefined) {\n nextState.context = mergeContextPatch(\n nextState.context,\n initialContext\n );\n }\n if (initialInput && defaultTransition.target) {\n for (const targetNode of defaultTransition.target) {\n stateInputMap[targetNode.id] = initialInput;\n stateInputsChanged = true;\n }\n }\n }\n }\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n actions.length = 0;\n executableActions.push(...resolvedActions);\n\n if (stateNodeToEnter.type !== 'final') {\n continue;\n }\n\n const parent = stateNodeToEnter.parent;\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent.id,\n stateNodeToEnter.output !== undefined\n ? resolveOutput(\n stateNodeToEnter.output,\n nextState.context,\n event,\n actorScope.self,\n stateInput\n )\n : undefined\n )\n );\n }\n\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n const regionOutput: Record<string, unknown> = {};\n for (const region of getChildren(ancestorMarker)) {\n if (region.type === 'final') {\n regionOutput[region.key] =\n region.output !== undefined\n ? resolveOutput(\n region.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[region.id]\n )\n : undefined;\n continue;\n }\n\n if (region.type === 'parallel') {\n const regionDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === region.id\n ) as DoneStateEvent | undefined;\n regionOutput[region.key] = regionDoneEvent?.output;\n continue;\n }\n\n const finalChild = getChildren(region).find(\n (s) => s.type === 'final' && mutStateNodeSet.has(s)\n );\n regionOutput[region.key] =\n finalChild?.output !== undefined\n ? resolveOutput(\n finalChild.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[finalChild.id]\n )\n : undefined;\n }\n internalQueue.push(\n createDoneStateEvent(ancestorMarker.id, regionOutput)\n );\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextState = cloneMachineSnapshot(nextState, {\n status: 'done',\n output: getMachineOutput(rootCompletionNode)\n });\n }\n\n if (stateInputsChanged) {\n nextState = cloneMachineSnapshot(nextState, {\n _stateInputs: stateInputMap\n });\n }\n };\n\n // Execute transition content\n const [resolvedTransitionState, transitionExecutableActions] =\n resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n transitionActions\n );\n nextState = resolvedTransitionState;\n executableActions.push(...transitionExecutableActions);\n if (context && context !== currentSnapshot.context) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n // Enter states\n if (isInitial || changesState) {\n enterStates();\n }\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n const allExitActions: AnyAction[] = [];\n const nextStateNodesToExit = nextStateNodes.sort(\n (a, b) => b.order - a.order\n );\n\n nextStateNodesToExit.forEach((stateNode) => {\n if (stateNode.exit) {\n const stateInput = getStateInput(nextState, stateNode.id);\n const [exitActions, , nextInternalEvents] = getStateActionsAndContext(\n stateNode.exit,\n nextState.context,\n nextState.children,\n stateInput\n );\n allExitActions.push(...exitActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n }\n });\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n allExitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const [stoppedState, stopEffects] = stopChildren(\n nextState,\n event,\n actorScope\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n\n const [withoutTimers, cancelEffects] = cancelTimers(\n nextState,\n event,\n actorScope\n );\n nextState = withoutTimers;\n executableActions.push(...cancelEffects);\n }\n\n if (\n historyValue === currentSnapshot.historyValue &&\n currentSnapshot.nodes.length === mutStateNodeSet.size &&\n currentSnapshot.nodes.every((node) =>\n mutStateNodeSet.has(node as StateNode)\n )\n ) {\n // If context was changed (e.g. by entry actions during self-transition),\n // clone to ensure reference inequality for eventless transition re-evaluation\n if (nextState.context !== originalContext) {\n return [\n nextState === currentSnapshot\n ? cloneMachineSnapshot(nextState)\n : nextState,\n executableActions\n ];\n }\n return [nextState, executableActions];\n }\n\n return [\n cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }),\n executableActions\n ];\n }\n}\n\n/**\n * Gets the transition result for a given transition without executing the\n * transition.\n */\nexport function getTransitionResult(\n transition: Pick<AnyTransitionDefinition, 'target' | 'to' | 'source'> & {\n reenter?: AnyTransitionDefinition['reenter'];\n input?: AnyTransitionDefinition['input'];\n context?: AnyTransitionDefinition['context'];\n },\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n options?: {\n resolveActions?: boolean;\n selectionResult?: TransitionSelectionResult;\n }\n): {\n targets: Readonly<AnyStateNode[]> | undefined;\n context: MachineContext | undefined;\n actions: AnyAction[] | undefined;\n reenter?: boolean;\n internalEvents: EventObject[] | undefined;\n input: Record<string, unknown> | undefined;\n} {\n let transitionArgs: any;\n const getTransitionArgs = () =>\n (transitionArgs ??= isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n },\n actorScope\n )\n : {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n system: actorScope.system,\n parent: actorScope.self._parent,\n self: actorScope.self,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n });\n\n if (transition.to) {\n const actions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n const res = options?.selectionResult?.reusable\n ? options.selectionResult.result\n : transition.to(\n getTransitionArgs(),\n createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true,\n options?.resolveActions ?? true\n )\n );\n\n const targets = res?.target\n ? resolveTarget(transition.source, toArray(res.target) as string[])\n : undefined;\n\n const resolvedInput =\n res?.input ??\n (typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input);\n\n return {\n targets: targets,\n context: res?.context,\n reenter: res?.reenter,\n actions,\n internalEvents,\n input: resolvedInput\n };\n }\n\n // Resolve input for regular transitions\n const resolvedInput =\n typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input;\n const resolvedContext =\n typeof transition.context === 'function'\n ? transition.context(getTransitionArgs())\n : transition.context;\n\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: resolvedContext,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: resolvedInput\n };\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[],\n initialMicrosteps: Microstep[] = []\n): {\n snapshot: typeof snapshot;\n microsteps: Microstep[];\n} {\n let nextSnapshot = snapshot;\n const microsteps: Microstep[] = initialMicrosteps.slice();\n\n function removeTerminatedChild(terminalEvent: EventObject) {\n if (\n terminalEvent.type !== 'xstate.done.actor' &&\n terminalEvent.type !== 'xstate.error.actor'\n ) {\n return;\n }\n\n const { actorId, sessionId } = terminalEvent as AnyEventObject & {\n actorId?: string;\n sessionId?: string;\n };\n if (!actorId) {\n return;\n }\n const child = nextSnapshot.children[actorId];\n if (!child) {\n return;\n }\n // The same staleness rule matchesActorSession applies to transition\n // selection: a completion from a different incarnation must not remove\n // the still-running child either.\n if (child.sessionId !== undefined && child.sessionId !== sessionId) {\n return;\n }\n\n const children = { ...nextSnapshot.children };\n delete children[actorId];\n actorScope.system._unregister(child);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { children });\n\n if (microsteps.length) {\n const [, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [nextSnapshot, lastEffects];\n } else {\n microsteps.push([nextSnapshot, []]);\n }\n }\n\n function completeMacrostep() {\n const effects = microsteps.flatMap(([, actions]) => actions);\n const starts = deriveDeferredStarts(effects);\n const shouldTerminate =\n (snapshot.status === 'active' || initialMicrosteps.length > 0) &&\n (nextSnapshot.status === 'done' || nextSnapshot.status === 'error');\n\n if (starts.length || shouldTerminate) {\n const terminalEffects = shouldTerminate\n ? [...starts, createTerminationEffect(actorScope, nextSnapshot)]\n : starts;\n if (microsteps.length) {\n const [lastSnapshot, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n lastSnapshot,\n [...lastEffects, ...terminalEffects]\n ];\n } else {\n microsteps.push([nextSnapshot, terminalEffects]);\n }\n }\n\n return { snapshot: nextSnapshot, microsteps };\n }\n\n function addMicrostep(\n step: Microstep,\n transitions: AnyTransitionDefinition[]\n ) {\n // collect microsteps; surfaced on the enclosing '@xstate.transition' event\n // via its `microsteps[]` facet (there is no standalone microstep event)\n if (\n !isInertActorScope(actorScope) &&\n (event.type === XSTATE_INIT ||\n (actorScope.system._hasInspectionObservers?.() ?? true))\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(...transitions);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n microsteps.push(step);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n const [stoppedChildrenSnapshot, stopEffects] = stopChildren(\n nextSnapshot,\n event,\n actorScope\n );\n const [withoutTimers, cancelEffects] = cancelTimers(\n stoppedChildrenSnapshot,\n event,\n actorScope\n );\n nextSnapshot = cloneMachineSnapshot(withoutTimers, {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);\n return completeMacrostep();\n }\n\n let nextEvent = normalizeLegacyInternalEvent(event, snapshot.machine);\n\n if (event.type === XSTATE_TIMER) {\n const timer = nextSnapshot.timers[(event as any).id];\n if (!timer) {\n return completeMacrostep();\n }\n\n const timers = { ...nextSnapshot.timers };\n delete timers[timer.id];\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { timers });\n if (timer.type === '@xstate.raise') {\n internalQueue.push(timer.event);\n addMicrostep([nextSnapshot, []], []);\n } else {\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n addMicrostep(\n [nextSnapshot, [createSendToEffect(actorScope, target, timer.event)]],\n []\n );\n }\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT && nextEvent.type !== XSTATE_TIMER) {\n const currentEvent = nextEvent;\n const isErr = isErrorEvent(currentEvent);\n const selectionResults: TransitionSelectionResults = new Map();\n\n const transitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n currentEvent,\n actorScope,\n selectionResults\n );\n\n if (isErr && !transitions.length) {\n if (\n currentEvent.type === 'xstate.error.actor' &&\n !matchesActorSession(\n currentEvent,\n nextSnapshot,\n (currentEvent as AnyEventObject).actorId\n )\n ) {\n return completeMacrostep();\n }\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], []);\n removeTerminatedChild(currentEvent);\n return completeMacrostep();\n }\n const step = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n addMicrostep(step, transitions);\n removeTerminatedChild(currentEvent);\n }\n\n if (\n !internalQueue.length &&\n snapshot.machine._hasEventlessTransitions === false\n ) {\n return completeMacrostep();\n }\n\n let shouldSelectEventlessTransitions = true;\n const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;\n let iterationCount = 0;\n\n let microstepCount = 0;\n while (nextSnapshot.status === 'active') {\n microstepCount++;\n if (microstepCount > 1000) {\n throw new Error('Microstep count exceeded 1000');\n }\n iterationCount++;\n if (iterationCount > maxIterations) {\n throw new Error(\n isDevelopment\n ? `Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`\n : `Infinite loop detected (>${maxIterations} microsteps)`\n );\n }\n\n let selectionResults: TransitionSelectionResults | undefined;\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope)\n : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n selectionResults = new Map();\n enabledTransitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n nextEvent,\n actorScope,\n selectionResults\n );\n }\n\n const step = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, enabledTransitions);\n removeTerminatedChild(nextEvent);\n }\n\n return completeMacrostep();\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, allStateNodes);\n}\n\nexport function hasEffect(\n transition: AnyTransitionDefinition,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope\n): boolean {\n if (transition.to) {\n return evaluateTransitionFunction(\n transition.to,\n context,\n event,\n snapshot,\n actorScope,\n snapshot.machine.sources,\n transition.source.id\n ).enabled;\n }\n\n return false;\n}\n\nconst triggerTransitionEffect = () => {\n throw transitionEffectSignal;\n};\nlet transitionEffectEnqueue: ReturnType<typeof createEnqueueObject> | undefined;\nfunction getTransitionEffectEnqueue() {\n return (transitionEffectEnqueue ??= createEnqueueObject(\n {\n emit: triggerTransitionEffect,\n cancel: triggerTransitionEffect,\n log: triggerTransitionEffect,\n raise: triggerTransitionEffect,\n spawn: triggerTransitionEffect,\n sendTo: triggerTransitionEffect,\n stop: triggerTransitionEffect,\n listen: triggerTransitionEffect,\n subscribeTo: triggerTransitionEffect\n },\n triggerTransitionEffect\n ));\n}\n\nfunction evaluateTransitionFunction(\n transitionTo: NonNullable<AnyTransitionDefinition['to']>,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n sources: AnyMachineSnapshot['machine']['sources'],\n sourceId: string\n): TransitionSelectionResult {\n let res;\n const parent = getActorScopeParent(actorScope);\n if (parent) {\n transitionEffectTargets.push(parent);\n }\n\n try {\n res = transitionTo(\n withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: sources.actions,\n actors: sources.actors,\n guards: sources.guards,\n delays: sources.delays,\n input: getStateInput(snapshot, sourceId)\n },\n actorScope\n ),\n getTransitionEffectEnqueue()\n );\n } catch (err) {\n if (err === transitionEffectSignal) {\n return { enabled: true, result: undefined, reusable: false };\n }\n throw err;\n } finally {\n if (parent) {\n transitionEffectTargets.pop();\n }\n }\n\n return { enabled: res !== undefined, result: res, reusable: true };\n}\n\nfunction stopChildren(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let children: AnyActor[];\n if (\n !snapshot.children ||\n (children = Object.values(snapshot.children).filter(Boolean) as AnyActor[])\n .length === 0\n ) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const child of children) {\n enqueue.stop(child);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction cancelTimers(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n const timerIds = Object.keys(snapshot.timers);\n if (!timerIds.length) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const id of timerIds) {\n enqueue.cancel(id);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction selectEventlessTransitions(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = snapshot.nodes.filter(isAtomicStateNode);\n\n for (const atomicStateNode of atomicStates) {\n loop: for (\n let stateNode: AnyStateNode | undefined = atomicStateNode;\n stateNode;\n stateNode = stateNode.parent\n ) {\n if (!stateNode.always) {\n continue;\n }\n for (const transition of stateNode.always) {\n if (\n evaluateCandidate(transition, event, snapshot, stateNode, actorScope)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(snapshot.nodes),\n snapshot,\n createTransitionResultResolver(snapshot, event, actorScope, false)\n );\n}\n\nexport function evaluateCandidate(\n candidate: AnyTransitionDefinition,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n stateNode: AnyStateNode,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): boolean {\n if (candidate.matches && !matchesEvent(event, candidate.matches)) {\n return false;\n }\n\n if (candidate._eventMatcher && !candidate._eventMatcher(event, snapshot)) {\n return false;\n }\n\n if (candidate.guard) {\n const guardArgs = withActorSelfAndParent(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n children: snapshot.children,\n actions: stateNode.machine.sources.actions,\n actors: stateNode.machine.sources.actors,\n guards: stateNode.machine.sources.guards,\n delays: stateNode.machine.sources.delays,\n _snapshot: snapshot\n },\n actorScope\n );\n if (!(candidate.guard as (args: typeof guardArgs) => boolean)(guardArgs)) {\n return false;\n }\n }\n\n if (candidate.to) {\n const evaluation = evaluateTransitionFunction(\n candidate.to,\n snapshot.context,\n event,\n snapshot,\n actorScope,\n stateNode.machine.sources,\n candidate.source.id\n );\n selectionResults?.set(candidate, evaluation);\n return evaluation.enabled;\n }\n\n return true;\n}\n","import isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY, WILDCARD } from './constants.ts';\nimport { isStateId } from './stateUtils.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n AnyTransitionConfigFunction,\n ErrorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n OutputArg,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\nexport function checkStateIn(\n snapshot: AnyMachineSnapshot,\n stateValue: StateValue\n) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot.nodes.some((sn) => sn === target);\n }\n\n return snapshot.matches(stateValue);\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n const result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nfunction toStateValue(stateValue: StateLike<any> | StateValue): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nfunction toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActor,\n input?: Record<string, unknown>\n): unknown {\n if (typeof mapper === 'function') {\n const outputMapper = mapper as Mapper<\n TContext,\n TExpressionEvent,\n unknown,\n EventObject\n >;\n const args = {\n context,\n event,\n output: getEventOutput(event),\n self,\n input\n } as unknown as Parameters<typeof outputMapper>[0];\n\n return outputMapper(args);\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function getEventOutput<TEvent extends EventObject>(\n event: TEvent\n): OutputArg<TEvent>['output'] {\n if (isDoneEvent(event)) {\n const doneEvent = event as unknown as EventObject & { output: unknown };\n return doneEvent.output as OutputArg<TEvent>['output'];\n }\n\n return undefined as OutputArg<TEvent>['output'];\n}\n\nfunction isDoneEvent(event: EventObject): boolean {\n return (\n event.type === 'xstate.done.actor' || event.type === 'xstate.done.state'\n );\n}\n\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorEvent(event: AnyEventObject): event is ErrorEvent {\n return event.type.startsWith('xstate.error.');\n}\n\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<\n AnyTransitionConfig | TransitionConfigTarget | AnyTransitionConfigFunction\n >\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n if (typeof transitionLike === 'function') {\n return { to: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.sources.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n const configSrc = (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any // TMeta\n >)\n ).src;\n // A referenced actor may itself be registered by name.\n return typeof configSrc === 'string'\n ? machine.sources.actors[configSrc]\n : configSrc;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot.nodes.flatMap((sn) => sn.ownEvents)])];\n}\n\n/** @internal Events synthesized from active transition descriptors. */\nexport function getAllOwnEvents(snapshot: AnyMachineSnapshot) {\n const events = snapshot.nodes.flatMap((stateNode) =>\n [...stateNode.transitions.values()].flatMap((transitions) =>\n transitions.map((transition) => {\n const event: AnyEventObject = {\n type: transition.eventType,\n ...transition.matches\n };\n if (\n 'actorId' in event &&\n (event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.timeout.actor')\n ) {\n event.sessionId = snapshot.children[event.actorId]?.sessionId;\n }\n return event;\n })\n )\n );\n return events.filter(\n (event, index) =>\n events.findIndex((candidate) => {\n const keys = Object.keys(event);\n return (\n keys.length === Object.keys(candidate).length &&\n keys.every((key) => Object.is(event[key], candidate[key]))\n );\n }) === index\n );\n}\n\nexport function matchesEvent(\n event: EventObject,\n pattern: Record<string, unknown>\n): boolean {\n return Object.entries(pattern).every(([key, value]) =>\n Object.is((event as AnyEventObject)[key], value)\n );\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nexport function matchesEventDescriptor(\n eventType: string,\n descriptor: string\n): boolean {\n if (descriptor === eventType) {\n return true;\n }\n\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n}\n","import { ACTOR_REF_TYPE } from './createActor.ts';\nimport type { AnyActorSystem } from './system.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n Snapshot,\n Subscription\n} from './types.ts';\n\nconst emptySubscription: Subscription = { unsubscribe() {} };\n\nconst restoreHint =\n 'or restore this snapshot with embedded children on the runtime that owns them.';\n\n/** @internal */\nexport function isRemoteActorRef(actorRef: AnyActor): boolean {\n return (actorRef as { _remote?: boolean })._remote === true;\n}\n\n/**\n * The lifecycle-only snapshot a remote handle exposes. `active` is accurate\n * by construction: a completion removes the child from its parent's\n * `children`, so a handle only exists while the child is presumed active,\n * and the terminal result arrives as a completion event instead of a\n * snapshot. Full snapshots are a co-location capability.\n */\nconst remoteSnapshot: Snapshot<undefined> = Object.freeze({\n status: 'active' as const,\n output: undefined,\n error: undefined\n});\n\n/**\n * Creates a location-transparent handle to an actor whose state lives with\n * another runtime. The handle is constructed from identity alone — no lookup\n * — and every send routes through the system's runtime; its state is not\n * synchronously readable.\n *\n * The surface is deliberately minimal: it covers every member the runtime\n * reaches for a restored child (send/_send, lifecycle via start/_stop and\n * system.stopActor, persistence, subscribe/on as inert subscriptions).\n * Members that only make sense for a co-located actor (public stop(),\n * select(), trigger) throw a descriptive error rather than being absent, so\n * calling one reports what went wrong instead of a bare TypeError. Observable\n * interop and _processingStatus are omitted entirely.\n *\n * @internal\n */\nexport function createRemoteActorRef(\n system: AnyActorSystem,\n options: {\n id: string;\n address: string;\n src: string;\n parent: AnyActor | undefined;\n registryKey?: string;\n syncSnapshot?: boolean;\n incarnation?: string;\n }\n): AnyActor {\n const handle = {\n _remote: true as const,\n // Self-reference so context persistence recognizes the handle as an\n // actor reference instead of recursing into it.\n ref: undefined as unknown as AnyActor,\n id: options.id,\n address: options.address,\n src: options.src,\n registryKey: options.registryKey,\n // The host-supplied incarnation token, when present: the owner's\n // sessionId for this child, letting this side drop stale completions and\n // journaled sends name the intended incarnation. Without one the handle\n // does not know the child's incarnation and the owning runtime is the\n // authority on staleness.\n sessionId: options.incarnation as string,\n system,\n _parent: options.parent,\n // Round-trips through persistence verbatim (undefined stays undefined,\n // so re-persisting is byte-stable); a remote handle cannot act on it\n // locally.\n _syncSnapshot: options.syncSnapshot,\n send(event: AnyEventObject) {\n void system.sendEvent(undefined, ref, event);\n },\n _send(event: AnyEventObject) {\n throw new Error(\n `Remote actor '${options.address}' has no local mailbox to receive \"${event.type}\". Its state lives with another runtime; install a runtime that can reach it (via \\`createDurable\\`'s adapter runtime operations, or \\`system.runtime\\`) before sending, ${restoreHint}`\n );\n },\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n getPersistedSnapshot(): never {\n throw new Error(\n `Cannot persist remote actor '${options.address}' from here: its state lives with the runtime that owns it. Persist it there, ${restoreHint}`\n );\n },\n start() {},\n _stop() {},\n stop() {\n throw new Error(\n `Cannot stop remote actor '${options.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\\`system.stopActor(ref)\\`), ${restoreHint}`\n );\n },\n select() {\n throw new Error(\n `Cannot select from remote actor '${options.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${restoreHint}`\n );\n },\n get trigger(): never {\n throw new Error(\n `Remote actor '${options.address}' has no \\`trigger\\` shorthand: it requires a co-located actor. Use \\`send(...)\\`, which routes through the system runtime.`\n );\n },\n // Observation is a co-location capability: a remote handle never emits,\n // so subscriptions are inert rather than errors — generic observers may\n // attach to any ref.\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n _isRunning() {\n return false;\n },\n // The same shape Actor.toJSON produces, so serialized snapshots carry\n // one actor-reference marker whether a child is co-located or remote.\n toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: options.id,\n address: options.address,\n src: options.src\n };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE } from './createActor.ts';\nimport { getStateValue } from './stateUtils.ts';\nimport type {\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyActor,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n StateValueMap,\n AnyActorRef,\n Snapshot,\n MetaObject,\n StateSchema,\n StateId,\n StateIdInputs,\n StateContextFromStateValue,\n SnapshotStatus,\n PersistedHistoryValue,\n AnyStateNode,\n LogicalTimer\n} from './types.ts';\nimport { matchesState } from './utils.ts';\nimport {\n copySnapshotActorRef,\n getSnapshotActorRef,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\nimport { isRemoteActorRef } from './remoteActorRef.ts';\n\nconst emptySnapshotRecord = Object.freeze({});\n\nfunction compactSnapshotRecord<T extends object>(value: T | undefined): T {\n if (value === emptySnapshotRecord) {\n return value;\n }\n return value && Object.keys(value).length\n ? value\n : (emptySnapshotRecord as T);\n}\n\nexport function isMachineSnapshot(value: unknown): value is AnyMachineSnapshot {\n return (\n !!value &&\n typeof value === 'object' &&\n 'machine' in value &&\n 'value' in value\n );\n}\n\ntype Values<T> = T[keyof T];\n\ntype MatchingObjectStateValue<\n TStateValue extends Record<string, unknown>,\n TTestStateValue extends Record<string, unknown>\n> =\n false extends Values<{\n [K in keyof TTestStateValue]: K extends keyof TStateValue\n ? NonNullable<TStateValue[K]> extends StateValue\n ? NonNullable<TTestStateValue[K]> extends StateValue\n ? [\n MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n ] extends [never]\n ? false\n : true\n : false\n : false\n : false;\n }>\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype MatchingStateValue<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = StateValue extends TTestStateValue\n ? TStateValue\n : string extends TTestStateValue\n ? TStateValue\n : TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends Record<string, unknown>\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends Record<string, unknown>\n ? TStateValue extends Record<string, unknown>\n ? MatchingObjectStateValue<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ninterface MachineSnapshotBase<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n _TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: AnyStateMachine;\n /** The tags of the active state nodes that represent the current state value. */\n tags: Set<string>;\n /**\n * The current state value.\n *\n * This represents the active state nodes in the state machine.\n *\n * - For atomic state nodes, it is a string.\n * - For compound parent state nodes, it is an object where:\n *\n * - The key is the parent state node's key\n * - The value is the current state value of the active child state node(s)\n *\n * @example\n *\n * ```ts\n * // single-level state node\n * snapshot.value; // => 'yellow'\n *\n * // nested state nodes\n * snapshot.value; // => { red: 'wait' }\n * ```\n */\n value: TStateValue;\n /** The current status of this snapshot. */\n status: SnapshotStatus;\n error: unknown;\n context: TContext;\n\n historyValue: Readonly<HistoryValue>;\n /** The enabled state nodes representative of the state value. */\n nodes: Array<AnyStateNode>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n /** Pending logical timers owned by this machine snapshot. */\n timers: Readonly<Record<string, LogicalTimer>>;\n /** @internal */\n _stateInputs: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId: number;\n /** @internal */\n _nextActorIds?: Record<string, number>;\n /**\n * Whether the current state value is a subset of the given partial state\n * value.\n *\n * @param partialStateValue\n */\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches(partialStateValue: StateValue): boolean;\n\n /**\n * Whether the current state nodes has a state node with the specified `tag`.\n *\n * @param tag\n */\n hasTag: (tag: TTag) => boolean;\n\n /**\n * Determines whether sending the `event` will cause a non-forbidden\n * transition to be selected, even if the transitions have no actions nor\n * change the state value.\n *\n * @param event The event to test\n * @returns Whether the event will cause a transition\n */\n can: (event: TEvent) => boolean;\n\n getMeta: () => Record<\n StateId<TStateSchema> & string,\n TMeta | undefined // States might not have meta defined\n >;\n\n /**\n * Returns the inputs for the current active state nodes, keyed by state node\n * id.\n */\n getInputs: () => StateIdInputs<TStateSchema>;\n\n toJSON: () => unknown;\n}\n\ninterface ActiveMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'active';\n output: undefined;\n error: undefined;\n}\n\ninterface DoneMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'done';\n output: TOutput;\n error: undefined;\n}\n\ninterface ErrorMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'error';\n output: undefined;\n error: unknown;\n}\n\ninterface StoppedMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\nexport type MachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\n) {\n return matchesState(testValue, this.value);\n};\n\nconst machineSnapshotHasTag = function hasTag(\n this: AnyMachineSnapshot,\n tag: string\n) {\n return this.tags.has(tag);\n};\n\nconst machineSnapshotCan = function can(\n this: AnyMachineSnapshot,\n event: EventObject\n) {\n if (isDevelopment && !this.machine) {\n console.warn(\n `state.can(...) used outside of a machine-created State object; this will always return false.`\n );\n }\n\n // The dry-run logic lives on the machine so that non-machine bundles\n // (e.g. `createFSM`) don't pay for the transition-resolution machinery.\n return this.machine?._canTransition(this, event) ?? false;\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n getMeta,\n getInputs,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return { ...jsonValues, tags: Array.from(tags) };\n};\n\nconst machineSnapshotGetMeta = function getMeta(this: AnyMachineSnapshot) {\n const meta: Record<string, any> = {};\n for (const stateNode of this.nodes) {\n if (stateNode.meta !== undefined) {\n meta[stateNode.id] = stateNode.meta;\n }\n }\n return meta;\n};\n\nconst machineSnapshotGetInputs = function getInputs<\n TStateSchema extends StateSchema\n>(\n this: AnyMachineSnapshot & {\n _stateInputs: StateIdInputs<TStateSchema>;\n }\n): StateIdInputs<TStateSchema> {\n return this._stateInputs;\n};\n\nfunction collectTags(stateNodes: Array<AnyStateNode>): Set<string> {\n const tags = new Set<string>();\n for (const stateNode of stateNodes) {\n for (const tag of stateNode.tags) {\n tags.add(tag);\n }\n }\n return tags;\n}\n\nexport function createMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n>(\n config: StateConfig<TContext, TEvent>,\n machine: AnyStateMachine,\n actorRef?: AnyActor\n): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n const snapshot = {\n status: config.status as never,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n nodes: config._nodes,\n value: (config.value ??\n getStateValue(machine.root, config._nodes)) as never,\n tags: collectTags(config._nodes),\n children: compactSnapshotRecord(config.children) as TChildren,\n timers: compactSnapshotRecord(config.timers),\n historyValue: compactSnapshotRecord(config.historyValue),\n _stateInputs: compactSnapshotRecord(config._stateInputs),\n _nextTimerId: config._nextTimerId ?? 0,\n _nextActorIds: config._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n };\n if (actorRef) {\n setSnapshotActorRef(snapshot, actorRef);\n }\n return snapshot;\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n const configWithSnapshot = {\n ...snapshot,\n ...config\n } as StateConfig<any, any>;\n\n if ((config._nodes ?? snapshot.nodes) === snapshot.nodes) {\n const clonedSnapshot = {\n status: configWithSnapshot.status as never,\n output: configWithSnapshot.output,\n error: configWithSnapshot.error,\n machine: snapshot.machine,\n context: configWithSnapshot.context,\n nodes: snapshot.nodes,\n value: snapshot.value,\n tags: snapshot.tags,\n children: compactSnapshotRecord(configWithSnapshot.children),\n timers: compactSnapshotRecord(configWithSnapshot.timers),\n historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),\n _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),\n _nextTimerId: configWithSnapshot._nextTimerId ?? 0,\n _nextActorIds: configWithSnapshot._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n } as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n }\n\n const clonedSnapshot = createMachineSnapshot(\n {\n ...configWithSnapshot,\n value: undefined\n },\n snapshot.machine\n ) as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n}\n\nfunction serializeHistoryValue(\n historyValue: HistoryValue\n): PersistedHistoryValue {\n const result: PersistedHistoryValue = {};\n\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map((item) => ({ id: item.id }));\n }\n }\n\n return result;\n}\n\nexport function getPersistedSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject\n>(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any // state schema\n >,\n options?: unknown\n): Snapshot<unknown> {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n children,\n timers,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n getInputs,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n const childrenJson: Record<string, unknown> = {};\n const timersJson: Record<string, unknown> = {};\n\n const embedChildren =\n (options as { embedChildren?: boolean } | undefined)?.embedChildren !==\n false;\n for (const id in children) {\n const child = children[id] as any;\n if (\n typeof child.src !== 'string' &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error('An inline child actor cannot be persisted.');\n }\n // Children are referenced by their logical address. Embedding the child\n // state is the co-locating runtime's whole-tree checkpoint capability;\n // remote handles never embed — their state lives with another runtime.\n const embed = embedChildren && !isRemoteActorRef(child);\n if (!embed && typeof child.src !== 'string') {\n // Fail where it is actionable: a by-address reference without a\n // registered source key could be persisted but never restored.\n throw new Error(\n `Unable to persist child '${id}' by address: it requires a registered source key.`\n );\n }\n childrenJson[id as keyof typeof childrenJson] = {\n address: child.address,\n // The explicit marker disambiguates a by-address reference from a child\n // whose own persisted snapshot happens to be undefined.\n ...(embed\n ? { snapshot: child.getPersistedSnapshot(options) }\n : {\n remote: true,\n // A remote handle's sessionId IS the host-supplied incarnation\n // token, round-tripped verbatim. A local child persisted by\n // address never stamps its own sessionId: that value is this\n // incarnation's, not a durable identity, and it would make\n // persisted snapshots nondeterministic across replays.\n incarnation: isRemoteActorRef(child) ? child.sessionId : undefined\n }),\n src: child.src,\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const snapshotActor = getSnapshotActorRef(snapshot)?.actor;\n // Only the wall clock is stamped into persisted timers: a custom clock's\n // readings (a simulated clock, a monotonic counter) are meaningless in any\n // other process, and restoring them under the wall clock would fire every\n // pending delay instantly. Pure-transition snapshots have no local\n // schedule and persist no timestamp.\n const scheduledTimers = snapshotActor?.system?._clock?.now\n ? undefined\n : snapshotActor?.system?._snapshot?._scheduledTimers;\n for (const id in timers) {\n const timer = timers[id];\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n event = { ...event };\n delete (event as EventObject & { sessionId?: string }).sessionId;\n }\n let target: string | { type: 'parent' };\n if (timer.target === 'self') {\n target = 'self';\n } else {\n const childId = Object.entries(children).find(\n ([, child]) => child === timer.target\n )?.[0];\n if (childId) {\n target = childId;\n } else if (\n timer.target === getSnapshotActorRef(snapshot)?.actor._parent\n ) {\n target = { type: 'parent' };\n } else {\n throw new Error(\n `Unable to persist timer '${id}': target actor '${timer.target.id}' is no longer addressable from this snapshot.`\n );\n }\n }\n // A live runtime knows when the timer is due; persist the wall-clock\n // start (dueAt - declared delay) so restore can honor the absolute\n // deadline. Derived from dueAt, not the scheduling moment, so repeated\n // persist/restore cycles keep the same deadline. Without a live schedule\n // (a restored-but-never-started actor, a pure-transition snapshot) the\n // timer's carried-in start — which only a wall-clock actor ever stamped —\n // passes through, so re-persisting cannot push the deadline back.\n const scheduled = scheduledTimers?.[`${snapshotActor!.sessionId}.${id}`];\n const startedAt = scheduled\n ? scheduled.dueAt - timer.delay\n : timer.startedAt;\n timersJson[id] = {\n id: timer.id,\n delay: timer.delay,\n type: timer.type,\n event,\n target,\n ...(startedAt !== undefined && { startedAt })\n };\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n context: persistContext(context) as any,\n children: childrenJson,\n timers: timersJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n\n if (_stateInputs && Object.keys(_stateInputs).length > 0) {\n persisted.stateInputs = _stateInputs;\n }\n\n if (machine.version !== undefined) {\n persisted.machine = {\n id: machine.id,\n version: machine.version\n };\n persisted.version = machine.version;\n }\n\n return persisted as Snapshot<unknown>;\n}\n\nfunction persistContext(contextPart: Record<string, unknown>) {\n let copy: typeof contextPart | undefined;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = {\n xstate$type: ACTOR_REF_TYPE,\n id: (value as any as AnyActor).id\n };\n } else {\n const result = persistContext(value as typeof contextPart);\n if (result !== value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport type { ActorTermination, AnyActor, AnyEventObject } from './types.ts';\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n return (actor.getSnapshot() as { effects?: StepEffects }).effects?.[key];\n}\n\nfunction waitForStep<TStepOutput>(\n actor: AnyActor,\n key: string\n): Promise<TStepOutput> {\n return new Promise((resolve, reject) => {\n const subscription = actor.subscribe((snapshot) => {\n const effect = (snapshot as { effects?: StepEffects }).effects?.[key];\n if (effect?.status === 'done') {\n subscription.unsubscribe();\n resolve(effect.output as TStepOutput);\n } else if (effect?.status === 'error') {\n subscription.unsubscribe();\n reject(effect.error as Error);\n }\n });\n });\n}\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n if (effect?.status === 'active') {\n return waitForStep(actor, key);\n }\n\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n try {\n const output = await exec();\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n return output;\n } catch (error) {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n throw error;\n }\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n assertEventCanBeSent(source, target, event);\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n _lastSourceRef?: AnyActor;\n _send(event: AnyEventObject): void;\n };\n\n runtimeTarget._lastSourceRef = source;\n runtimeTarget._send(event);\n}\n\n/**\n * Ensures internal events cannot cross an actor boundary from an external\n * sender. Host runtimes must call this before taking ownership of delivery.\n */\nexport function assertEventCanBeSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n throw new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","import isDevelopment from '#is-development';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription,\n AnyActorLogic,\n ActorOptions\n} from './types.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { toObserver } from './utils.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n assertEventCanBeSent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n id: string;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, id: string, delay: number): void;\n cancel(source: AnyActor, id: string): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet systemIdPrefix: string | undefined;\nlet nextSystemId = 0;\n\n/** @internal */\nexport const transitionEffectSignal = new Error('Transition effect');\n/** @internal */\nexport const transitionEffectTargets: AnyActor[] = [];\n\nfunction createSystemIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createSystemId(): string {\n systemIdPrefix ??= createSystemIdPrefix();\n return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n systemId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Anonymous machines get the placeholder id '(machine)'; only named logic\n // earns a named id prefix.\n return typeof logicId === 'string' &&\n logicId.length &&\n logicId !== '(machine)'\n ? logicId\n : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.systemId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Publishes an emitted event. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /** Schedules a logical timer. */\n scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, id: string): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry: the default logs in development and emits an\n * inspection event.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: string\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(actor: AnyActor, id: string): ScheduledTimerId {\n return `${actor.sessionId}.${id}` as ScheduledTimerId;\n}\n\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n systemId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n systemId: createSystemId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n ) {\n const restoredSnapshot =\n typeof options.snapshot === 'object' && options.snapshot !== null\n ? (options.snapshot as {\n scheduler?: Record<ScheduledTimerId, ScheduledTimer>;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, id: string, delay: number): void {\n const existingId = createScheduledTimerId(source, id);\n if (this._timerMap?.[existingId] !== undefined) {\n this.cancel(source, id);\n }\n\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n id,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n const scheduledTimerId = createScheduledTimerId(source, id);\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, id });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, id: string): void {\n const scheduledTimerId = createScheduledTimerId(source, id);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.id);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${registryKey as string}' already exists.`\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n assertEventCanBeSent(source, target, event);\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: string\n ): void | PromiseLike<void> {\n this._sendInspectionEvent({\n type: '@xstate.deadletter',\n actorRef: target,\n sourceRef: source,\n event,\n reason\n });\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason);\n }\n if (isDevelopment) {\n console.warn(\n `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n return override(source, id, delay);\n }\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, id);\n }\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, id } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n id,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotFor,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableActionObject,\n Readable,\n ActorLogicTransitionResult\n} from './types.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\n/**\n * Marks a serialized object as an actor reference (`xstate$type` in JSON\n * output and persisted context).\n */\nexport const ACTOR_REF_TYPE = 'actorRef';\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableActionObject[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (event: EventFromLogic<TLogic>) => void;\n private mailbox?: Mailbox<EventFromLogic<TLogic>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableActionObject[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n snapshot: resolvedOptions.snapshot ?? resolvedOptions.state,\n createActorRef\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const persistedState = options?.snapshot ?? options?.state;\n this._restored = persistedState !== undefined;\n try {\n if (persistedState) {\n this._setSnapshot(\n this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n );\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._setSnapshot({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>);\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n this.system.emitEvent(this, event);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableActionObject) => void {\n const actionExecutor = (action: ExecutableActionObject) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : `Cannot stop non-child actor ${child.id}`\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableActionObject): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n void action.exec();\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n type RestoredTimer = { id: string; delay: number; startedAt?: number };\n const timers =\n (\n this._snapshot as unknown as {\n timers?: Record<string, RestoredTimer>;\n }\n ).timers ?? {};\n // startedAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of Object.values(timers)) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.startedAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.startedAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, timer.id, delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n private _error(err: unknown): void {\n this._stopProcedure();\n if (!this.observers?.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n } else {\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n safeCall(errorListener, err);\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(\n this._lastSourceRef,\n this as AnyActor,\n event,\n 'stopped'\n );\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: its `id`, `address`,\n * and registered source key (when the actor was created from one).\n */\n public toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: this.id,\n address: this.address,\n src: typeof this.src === 'string' ? this.src : undefined\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n public getPersistedSnapshot(\n options?: unknown\n ): Snapshot<unknown> & PersistedSnapshotFor<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START,\n XSTATE_STOP\n} from '../constants.ts';\nimport { createInitEvent } from '../eventUtils.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { ActorSystemRuntime, AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n finalizeTransitionResult,\n createCustomEffect,\n createEmitEffect,\n createSendToEffect\n} from '../transitionActions.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n ActorScope,\n AnyActorRef,\n EventObject,\n ExecutableActionObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type LogicSnapshot<TContext, TOutput, TInput> = Snapshot<TOutput> & {\n context: TContext;\n input: TInput | undefined;\n effects?: Record<string, LogicEffectState>;\n};\n\nexport type LogicEffectState =\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown };\n\nexport interface LogicArgs<TContext, TEvent extends EventObject, TInput> {\n context: TContext;\n event: TEvent;\n input: TInput;\n system: AnyActorSystem;\n self: LogicActorRef<TContext, unknown, TEvent, TInput>;\n}\n\nexport type LogicEffect<\n _TEvent extends EventObject,\n _TEmitted extends EventObject\n> = ExecutableActionObject;\n\nexport interface LogicEnqueue<\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n emit: (emitted: TEmitted) => void;\n sendBack: (event: EventObject) => void;\n raise: (event: TEvent) => void;\n effect: {\n (\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n };\n}\n\nexport type LogicPatch<TContext, TOutput, TInput> = Partial<{\n context: TContext;\n input: TInput | undefined;\n status: LogicSnapshot<TContext, TOutput, TInput>['status'];\n output: TOutput;\n error: unknown;\n effects: Record<string, LogicEffectState>;\n}>;\n\nexport type LogicFunction<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> = (\n args: LogicArgs<TContext, TEvent, TInput>,\n enq: LogicEnqueue<TEvent, TEmitted>\n) => void | LogicPatch<TContext, TOutput, TInput>;\n\nexport interface LogicConfig<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n id?: string;\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n context: TContext | ((args: { input: TInput }) => TContext);\n run: LogicFunction<TContext, TOutput, TEvent, TInput, TEmitted>;\n}\n\ninterface LogicTransition<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> {\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): [\n LogicSnapshot<TContext, TOutput, TInput>,\n LogicEffect<TEvent, TEmitted>[]\n ];\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): LogicSnapshot<TContext, TOutput, TInput>;\n}\n\nexport type LogicActorLogic<\n TContext,\n TOutput,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = Omit<\n ActorLogic<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >,\n 'transition'\n> & {\n id?: string;\n transition: LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n};\n\nexport type LogicActorRef<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput\n> = ActorRefFromLogic<LogicActorLogic<TContext, TOutput, TEvent, TInput>>;\n\nconst effectStates = new WeakMap<\n AnyActorRef,\n Map<PropertyKey, { cleanup?: () => void }>\n>();\n\nfunction getEffectState(self: AnyActorRef) {\n let state = effectStates.get(self);\n if (!state) {\n state = new Map();\n effectStates.set(self, state);\n }\n return state;\n}\n\nfunction executeLogicEffect(\n self: AnyActorRef,\n key: string | undefined,\n effect: () => void | (() => void)\n): void {\n const state = getEffectState(self);\n if (key !== undefined && state.has(key)) {\n return;\n }\n const cleanup = effect();\n state.set(key ?? Symbol(), {\n cleanup: typeof cleanup === 'function' ? cleanup : undefined\n });\n}\n\nfunction cleanupLogicEffects(self: AnyActorRef): void {\n const state = effectStates.get(self);\n if (!state) {\n return;\n }\n for (const { cleanup } of state.values()) {\n cleanup?.();\n }\n effectStates.delete(self);\n}\n\nfunction resolveContext<TContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext),\n input: TInput\n) {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : context;\n}\n\nexport function createLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput,\n const TInputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & {\n schemas: { input: TInputSchema; output?: undefined };\n }\n): LogicActorLogic<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: undefined; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> {\n const calculateTransition = ((snapshot, event, actorScope) => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n\n if (event.type === XSTATE_STOP) {\n return [\n {\n ...snapshot,\n status: 'stopped',\n input: undefined\n },\n [\n createCustomEffect('xstate.logic.cleanup', () =>\n cleanupLogicEffects(actorScope.self)\n )\n ]\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_START) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: { status: 'active' }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'done',\n output: (event as any).output\n }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'error',\n error: (event as any).error\n }\n }\n },\n []\n ];\n }\n\n const effects: LogicEffect<TEvent, TEmitted>[] = [];\n const trackedEffects: Record<string, LogicEffectState> = {};\n const enqueueEffect = (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ) => {\n if (snapshot.effects?.[key]) {\n return;\n }\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, key, () => exec(runtime)),\n { key }\n )\n );\n trackedEffects[key] = { status: 'active' };\n };\n const enq: LogicEnqueue<TEvent, TEmitted> = {\n emit: (emitted) => {\n effects.push(createEmitEffect(actorScope, emitted));\n },\n sendBack: (sentEvent) => {\n const parent = actorScope.self._parent;\n if (parent) {\n effects.push(createSendToEffect(actorScope, parent, sentEvent));\n }\n },\n raise: (raisedEvent) => {\n effects.push(\n createSendToEffect(actorScope, actorScope.self, raisedEvent)\n );\n },\n effect: ((keyOrExec, maybeExec) => {\n if (typeof keyOrExec === 'string') {\n enqueueEffect(keyOrExec, maybeExec);\n return;\n }\n const exec = keyOrExec as (\n runtime?: Partial<ActorSystemRuntime>\n ) => void | (() => void);\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, undefined, () =>\n exec(runtime)\n )\n )\n );\n }) as LogicEnqueue<TEvent, TEmitted>['effect']\n };\n\n const patch = config.run(\n {\n context: snapshot.context,\n event,\n input: snapshot.input!,\n system: actorScope.system,\n self: actorScope.self as any,\n emit: actorScope.emit\n } as LogicArgs<TContext, TEvent, TInput>,\n enq\n );\n\n const nextSnapshot = {\n ...snapshot,\n ...(patch || {})\n } as LogicSnapshot<TContext, TOutput, TInput>;\n\n if ('context' in snapshot || patch?.context !== undefined) {\n (nextSnapshot as any).context = patch?.context ?? snapshot.context;\n }\n if (patch?.effects || Object.keys(trackedEffects).length) {\n (nextSnapshot as any).effects = {\n ...snapshot.effects,\n ...patch?.effects,\n ...trackedEffects\n };\n }\n\n return finalizeTransitionResult(actorScope, snapshot, [\n nextSnapshot,\n effects\n ]);\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const transition = ((snapshot, event, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'event',\n logic,\n event,\n eventOrigin: (actorScope.self as any)._lastSourceRef\n ? 'actor'\n : 'external'\n });\n }\n const result = calculateTransition(snapshot, event, actorScope);\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'result',\n logic,\n snapshot: result[0],\n effects: result[1]\n });\n }\n return result;\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const logic: LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> = {\n id: config.id,\n config,\n validator: config.validator,\n transition,\n start: (snapshot, actorScope, options) => {\n if (!options?.restored) {\n return;\n }\n const [nextSnapshot, effects] = transition(\n snapshot,\n createInitEvent(snapshot.input) as unknown as TEvent,\n actorScope\n );\n Object.assign(snapshot, nextSnapshot);\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n },\n initialTransition: (input, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'input',\n logic,\n input\n });\n }\n const context = resolveContext(config.context, input);\n const snapshot = {\n status: 'active' as const,\n output: undefined,\n error: undefined,\n input\n };\n\n if (context !== undefined) {\n (snapshot as any).context = context;\n }\n\n return transition(\n { ...snapshot } as LogicSnapshot<TContext, TOutput, TInput>,\n createInitEvent(input) as unknown as TEvent,\n actorScope\n );\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\ninterface CallbackInstanceState<TEvent extends EventObject> {\n receivers: Set<(e: TEvent) => void> | undefined;\n dispose: (() => void) | void;\n}\n\nconst instanceStates = /* #__PURE__ */ new WeakMap<\n AnyActorRef,\n CallbackInstanceState<any>\n>();\n\nexport type CallbackSnapshot<TInput> = Snapshot<undefined> & {\n input: TInput;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n CallbackSnapshot<TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createCallbackLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createCallbackLogic, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = createCallbackLogic<Event, Input>(\n * ({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef<Event, Input>\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * }\n * );\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link createCallbackLogic}\n */\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorRefFromLogic<CallbackActorLogic<TEvent, TInput>>;\n\ntype Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type CallbackLogicFunction<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n sendBack,\n receive,\n emit\n}: {\n /**\n * Data that was provided to the callback actor\n *\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /** The actor system to which the callback actor belongs */\n system: AnyActorSystem;\n /** The parent actor of the callback actor */\n self: CallbackActorRef<TEvent>;\n /** A function that can send events back to the parent actor */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument; the\n * listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n emit: (emitted: TEmitted) => void;\n}) => (() => void) | void;\n\nexport interface CallbackLogicConfig<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: CallbackLogicFunction<TEvent, TSentEvent, TInput, TEmitted>;\n}\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = createCallbackLogic(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createCallbackLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<\n TEvent,\n AnyEventObject,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): CallbackActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callback: CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callbackOrConfig:\n | CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n | CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted> {\n const callback =\n typeof callbackOrConfig === 'function'\n ? callbackOrConfig\n : callbackOrConfig.run;\n const schemas =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.schemas;\n const validator =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.validator;\n\n return createBaseLogic<undefined, undefined, TEvent, TInput, TEmitted>({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n const emit = (args as any).emit as (emitted: TEmitted) => void;\n const callbackState = instanceStates.get(self as any);\n callbackState?.receivers?.forEach((receiver) => receiver(event));\n\n enq.effect('callback', () => {\n const callbackState: CallbackInstanceState<TEvent> = {\n receivers: undefined,\n dispose: undefined\n };\n\n instanceStates.set(self as any, callbackState);\n\n callbackState.dispose = callback({\n input,\n system,\n self: self as any,\n sendBack: (event) => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n const parent = (self as any)._parent;\n if (parent) {\n system._relay(self as any, parent, event);\n }\n },\n receive: (listener) => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit: emit as (emitted: TEmitted) => void\n });\n\n return () => {\n instanceStates.delete(self as any);\n callbackState.receivers?.clear();\n callbackState.dispose?.();\n };\n });\n }\n }) as unknown as CallbackActorLogic<TEvent, TInput, TEmitted>;\n}\n","import { XSTATE_INIT, XSTATE_STOP } from '../constants';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot,\n Subscribable,\n Subscription\n} from '../types';\nimport { createLogic as createBaseLogic } from './logic.ts';\nimport { finalizeTransitionResult } from '../transitionActions.ts';\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\nexport type ObservableSnapshot<\n TContext,\n TInput extends NonReducibleUnknown\n> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createObservableLogic` or\n * `createEventObservableLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = createObservableLogic<Context, Input>(\n * ({ input, self }) => {\n * self;\n * // ^? ObservableActor<Event, Input>\n *\n * return interval(input.period ?? 1_000);\n * }\n * );\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActor<Event, Input>\n * ```\n *\n * @see {@link createObservableLogic}\n * @see {@link createEventObservableLogic}\n */\nexport type ObservableActorRef<TContext> = ActorRefFromLogic<\n ObservableActorLogic<TContext, any>\n>;\n\ntype ObservableActor<\n TContext,\n TInput extends NonReducibleUnknown = any,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<ObservableActorLogic<TContext, TInput, TEmitted>>;\n\nexport type ObservableLogicFunction<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TContext, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TContext>;\n\nexport interface ObservableLogicConfig<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: ObservableLogicFunction<TContext, TInput, TEmitted>;\n}\n\nexport type EventObservableLogicFunction<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TEvent, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TEvent>;\n\nexport interface EventObservableLogicConfig<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: EventObservableLogicFunction<TEvent, TInput, TEmitted>;\n}\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = createObservableLogic((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nexport function createObservableLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<TContext, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreator: ObservableLogicFunction<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreatorOrConfig:\n | ObservableLogicFunction<TContext, TInput, TEmitted>\n | ObservableLogicConfig<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted> {\n const observableCreator =\n typeof observableCreatorOrConfig === 'function'\n ? observableCreatorOrConfig\n : observableCreatorOrConfig.run;\n const schemas =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.schemas;\n const validator =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.validator;\n\n return createBaseLogic<\n TContext | undefined,\n undefined,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT: {\n return {\n context: event.data as TContext\n };\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n status: 'error',\n error: (event as any).data,\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'error', error: (event as any).data }\n }\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n status: 'done',\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'done' }\n }\n };\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const subscription = observableCreator({\n input,\n system,\n self: self as any,\n emit: ((event: TEmitted) =>\n void runtime.emitEvent!(actorSelf, event)) as (\n emitted: TEmitted\n ) => void\n }).subscribe({\n next: (value) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: (err) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n sendSelf({\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n\n return () => subscription.unsubscribe();\n });\n }\n }) as unknown as ObservableActorLogic<TContext, TInput, TEmitted>;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * createEventObservableLogic,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = createEventObservableLogic(\n * () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<TEvent, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservable: EventObservableLogicFunction<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservableOrConfig:\n | EventObservableLogicFunction<TEvent, TInput, TEmitted>\n | EventObservableLogicConfig<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted> {\n const lazyObservable =\n typeof lazyObservableOrConfig === 'function'\n ? lazyObservableOrConfig\n : lazyObservableOrConfig.run;\n const validator =\n typeof lazyObservableOrConfig === 'function'\n ? undefined\n : lazyObservableOrConfig.validator;\n\n // TODO: event types\n const logic: ObservableActorLogic<TEvent, TInput, TEmitted> = {\n config: lazyObservableOrConfig,\n validator,\n transition: (state, event, actorScope) => {\n if (state.status !== 'active') {\n return [state, []];\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_OBSERVABLE_COMPLETE:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return [\n {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n },\n []\n ];\n default:\n return [state, []];\n }\n },\n initialTransition: (input, _) => {\n if (validator) {\n assertValid(validator, { kind: 'input', logic, input });\n }\n const snapshot = {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>;\n return [snapshot, []];\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n start: (state, { self, system, emit }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self,\n emit: (event) => {\n void emit(event);\n }\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot: any) => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n","import { parseDelayToMilliseconds } from '../delay.ts';\nimport { runStep } from '../runtimeHelpers.ts';\nimport { XSTATE_INIT } from '../constants.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\nexport type AsyncSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nconst XSTATE_ASYNC_RESOLVE = 'xstate.async.resolve';\nconst XSTATE_ASYNC_REJECT = 'xstate.async.reject';\n\nexport type AsyncActorLogic<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n AsyncSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\nexport type AsyncActorRef<TOutput> = ActorRefFromLogic<\n AsyncActorLogic<TOutput, unknown>\n>;\n\ntype AsyncActor<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<AsyncActorLogic<TOutput, TInput, TEmitted>>;\n\nexport interface LogicArgs<TOutput, TInput> {\n /** Data that was provided to the async actor. */\n input: TInput;\n /** The actor system to which the async actor belongs. */\n system: AnyActorSystem;\n /** The async actor. */\n self: AsyncActor<TOutput, TInput>;\n /** Aborted when the async actor is stopped or times out. */\n signal: AbortSignal;\n}\n\nexport interface LogicEnqueue<TEmitted extends EventObject> {\n /** Emits an event that can be observed with `actor.on(...)`. */\n emit: (emitted: TEmitted) => void;\n /**\n * Executes async work as a durable effect keyed by `key`.\n *\n * @experimental The durability semantics (step journaling, replay, and\n * resumption across persistence) are not finalized and may change.\n */\n step: <TStepOutput>(\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>\n ) => Promise<TStepOutput>;\n}\n\nexport type LogicFunction<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = (\n args: LogicArgs<TOutput, TInput>,\n enq: LogicEnqueue<TEmitted>\n) => PromiseLike<TOutput>;\n\ntype AsyncLogicFunctionOutput<\n TLogicFunction extends (...args: any[]) => PromiseLike<any>\n> = Awaited<ReturnType<TLogicFunction>>;\n\nexport interface LogicConfig<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n /**\n * Stable identifier for this async logic. This identifies the logic, not a\n * particular actor instance.\n */\n id?: string;\n validator?: ActorLogicValidator;\n /** Schemas for inferring async logic types. */\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n /** Maximum time this async logic may run before it is aborted and errors. */\n timeout?: number | string;\n /** The async work to execute when the actor starts. */\n run: LogicFunction<TOutput, TInput, TEmitted>;\n}\n\nexport class TimeoutError extends Error {\n constructor(timeout: number | string) {\n super(`Async logic timed out after ${timeout}.`);\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Represents an actor created by `createAsyncLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createAsyncLogic, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = createAsyncLogic<Output, Input>({\n * run: async ({ input, self }, enq) => {\n * self;\n * // ^? AsyncActor<Output, Input>\n * enq.emit({ type: 'request.start' });\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * }\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? AsyncActor<Output, Input>\n * ```\n *\n * @see {@link createAsyncLogic}\n */\n\n/**\n * An actor logic creator which returns async logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from async actor logic can:\n *\n * - Output the resolved value of the async process\n * - Error with the rejected value of the async process\n * - Abort when stopped or timed out\n *\n * Sending events to async actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const asyncLogic = createAsyncLogic({\n * id: 'fetch-user',\n * timeout: '30s',\n * run: async ({ signal }, enq) => {\n * enq.emit({ type: 'request.start' });\n * const result = await fetch('https://example.com/...', {\n * signal\n * }).then((data) => data.json());\n *\n * return result;\n * }\n * });\n *\n * const asyncActor = createActor(asyncLogic);\n * asyncActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * asyncActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param asyncLogic A config object with a `run` function which returns a\n * Promise, and accepts an object with the following properties:\n *\n * - `input` - Data that was provided to the async actor\n * - `self` - The async actor ref\n * - `system` - The actor system to which the async actor belongs\n * - `signal` - An abort signal for cancellation\n *\n * `run` also receives an `enq` object with the following properties:\n *\n * - `emit` - Emits an event that can be observed with `actor.on(...)`\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject,\n TLogicFunction extends LogicFunction<\n any,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n > = LogicFunction<any, StandardSchemaV1.InferOutput<TInputSchema>, TEmitted>\n>(\n asyncLogic: Omit<\n LogicConfig<\n never,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n >,\n 'run' | 'schemas'\n > & {\n schemas: { input: TInputSchema; output?: never };\n run: TLogicFunction;\n }\n): AsyncActorLogic<\n AsyncLogicFunctionOutput<TLogicFunction>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TOutputSchema extends StandardSchemaV1,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: never; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: Omit<LogicConfig<TOutput, TInput, TEmitted>, 'schemas'> & {\n schemas?: undefined;\n }\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<TOutput, TInput, TEmitted>\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string } {\n const config = asyncLogic;\n\n return createBaseLogic<\n undefined,\n TOutput,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n id: config.id,\n validator: config.validator,\n schemas: config.schemas,\n context: undefined,\n run: ({ event, input, self, system }, enq) => {\n switch (event.type) {\n case XSTATE_ASYNC_RESOLVE: {\n const resolvedValue = (event as any).data ?? (event as any).output;\n return {\n status: 'done',\n output: resolvedValue,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'done', output: resolvedValue }\n }\n };\n }\n case XSTATE_ASYNC_REJECT: {\n const error = (event as any).data ?? (event as any).error;\n return {\n status: 'error',\n error,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'error', error }\n }\n };\n }\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const controller = new AbortController();\n const timeout = config.timeout;\n const timeoutMs = parseDelayToMilliseconds(timeout);\n const timeoutId =\n timeoutMs === undefined\n ? undefined\n : system._clock.setTimeout(() => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controller.abort();\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: new TimeoutError(timeout!)\n });\n }, timeoutMs);\n\n const clearTimeout = () => {\n if (timeoutId !== undefined) {\n system._clock.clearTimeout(timeoutId);\n }\n };\n\n const runBody = () =>\n Promise.resolve(\n config.run(\n {\n input,\n system,\n self: self as any,\n signal: controller.signal\n },\n {\n emit: (event) => void runtime.emitEvent!(actorSelf, event),\n // Steps route through the runtime: a durable host that\n // implements `runStep` owns the step journal; otherwise the\n // built-in behavior memoizes into this actor's own snapshot,\n // self-sending through the same runtime as the other effects.\n step: (key, exec) =>\n runtime.runStep\n ? (Promise.resolve(\n runtime.runStep(actorSelf, key, exec)\n ) as Promise<any>)\n : runStep(actorSelf, key, exec, sendSelf)\n }\n )\n );\n // The whole body is one durable unit: a host that implements\n // `runLogic` journals it by the actor's address — or re-runs the\n // registered logic from (src, input) on a remote executor, ignoring\n // the closure. The default runs it here, unjournaled.\n const resolvedPromise = runtime.runLogic\n ? Promise.resolve(runtime.runLogic(actorSelf, runBody))\n : runBody();\n\n resolvedPromise.then(\n (response) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_RESOLVE,\n data: response\n });\n },\n (errorData) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: errorData\n });\n }\n );\n\n return () => {\n controller.abort();\n clearTimeout();\n };\n });\n\n return {\n effects: {\n async: { status: 'active' }\n }\n };\n }\n }) as unknown as AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorFromLogic } from '../types.ts';\nimport { createLogic } from './logic.ts';\nexport {\n createCallbackLogic,\n type CallbackActorLogic,\n type CallbackActorRef,\n type CallbackLogicConfig,\n type CallbackSnapshot,\n type CallbackLogicFunction\n} from './callback.ts';\nexport {\n createObservableLogic,\n createEventObservableLogic,\n type EventObservableLogicConfig,\n type EventObservableLogicFunction,\n type ObservableActorLogic,\n type ObservableActorRef,\n type ObservableLogicConfig,\n type ObservableLogicFunction,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n createLogic,\n type LogicActorLogic,\n type LogicActorRef,\n type LogicArgs,\n type LogicConfig,\n type LogicEffect,\n type LogicEffectState,\n type LogicEnqueue,\n type LogicFunction,\n type LogicPatch,\n type LogicSnapshot\n} from './logic.ts';\nexport {\n createAsyncLogic,\n type AsyncActorLogic,\n type AsyncActorRef,\n type AsyncSnapshot,\n type LogicArgs as AsyncLogicArgs,\n type LogicConfig as AsyncLogicConfig,\n type LogicEnqueue as AsyncLogicEnqueue,\n type LogicFunction as AsyncLogicFunction,\n TimeoutError\n} from './promise.ts';\nexport {\n createListenerLogic,\n listenerLogic,\n type ListenerActorLogic,\n type ListenerActorRef,\n type ListenerSnapshot,\n type ListenerInput\n} from './listener.ts';\nexport {\n createSubscriptionLogic,\n subscriptionLogic,\n type SubscriptionActorLogic,\n type SubscriptionActorRef,\n type SubscriptionSnapshot,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './subscription.ts';\n\nconst emptyLogic = /* #__PURE__ */ createLogic<undefined, undefined>({\n context: undefined,\n run: () => undefined\n});\n\nexport function createEmptyActor(): ActorFromLogic<typeof emptyLogic> {\n return createActor(emptyLogic);\n}\n","const cache = new WeakMap<any, any>();\n\nexport function memo<T>(object: any, key: string, fn: () => T): T {\n let memoizedData = cache.get(object);\n\n if (!memoizedData) {\n memoizedData = { [key]: fn() };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n\n return memoizedData[key];\n}\n","import isDevelopment from '#is-development';\nimport { NULL_EVENT, STATE_DELIMITER } from './constants.ts';\nimport type { SetupStateSchemas } from './schema.types.ts';\nimport { createInvokeTimeoutEventId } from './eventUtils.ts';\nimport { memo } from './memo.ts';\nimport {\n evaluateCandidate,\n formatTransition,\n getCandidates,\n getEventDescriptorKey,\n getDelayedTransitions,\n matchesActorSession,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport type {\n DelayedTransitionDefinition,\n EventObject,\n InitialTransitionDefinition,\n MachineContext,\n Mapper,\n StateNodesConfig,\n TransitionDefinition,\n TransitionDefinitionMap,\n AnyStateMachine,\n AnyStateNodeConfig,\n NonReducibleUnknown,\n EventDescriptor,\n AnyActorScope,\n AnyStateNode,\n AnyEventObject,\n AnyAction,\n AnyTransitionConfig,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyInvokeDefinition\n} from './types.ts';\nimport {\n createInvokeId,\n mapValues,\n toArray,\n toTransitionConfigArray\n} from './utils.ts';\n\nconst EMPTY_OBJECT = {};\nconst CHOICE_CONFIG_KEYS = [\n 'invoke',\n 'after',\n 'on',\n 'entry',\n 'exit',\n 'always',\n 'states',\n 'initial',\n 'onDone',\n 'timeout',\n 'onTimeout',\n 'history',\n 'target',\n 'output'\n] as const;\n\ninterface StateNodeOptions<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n _key: string;\n _parent?: StateNode<TContext, TEvent>;\n _machine: AnyStateMachine;\n}\n\nexport class StateNode<\n TContext extends MachineContext = MachineContext,\n TEvent extends EventObject = EventObject\n> {\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n public key: string;\n /** The unique ID of the state node. */\n public id: string;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'choice'` - pure routing decision state node\n * - `'final'` - final state node\n */\n public type:\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | 'choice';\n /** The string path from the root machine node to this node. */\n public path: string[];\n /** The child state nodes. */\n public states: StateNodesConfig<any, any>;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n public history: false | 'shallow' | 'deep';\n /** The action(s) to be executed upon entering the state node. */\n public entry: AnyAction | undefined;\n /** The action(s) to be executed upon exiting the state node. */\n public exit: AnyAction | undefined;\n /** The parent state node. */\n public parent?: StateNode<any, any>;\n /** The root machine node. */\n public machine: AnyStateMachine;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n public meta?: any;\n /**\n * The output data sent with the `xstate.done.state` event if this is a final\n * state node.\n */\n public output?:\n | Mapper<MachineContext, EventObject, unknown, EventObject>\n | NonReducibleUnknown;\n\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n public order: number = -1;\n\n public description?: string;\n\n public schemas: SetupStateSchemas | undefined;\n\n public tags: string[] = [];\n public transitions!: Map<string, AnyTransitionDefinition[]>;\n public always?: Array<AnyTransitionDefinition>;\n public invoke: Array<AnyInvokeDefinition>;\n public on!: TransitionDefinitionMap<any, any>;\n public after!: Array<DelayedTransitionDefinition<any, any>>;\n public events!: Array<EventDescriptor<any>>;\n public ownEvents!: Array<EventDescriptor<any>>;\n private _candidateCache?: Map<string, AnyTransitionDefinition[]>;\n\n constructor(\n /** The raw config used to create the machine. */\n public config: AnyStateNodeConfig,\n options: StateNodeOptions<TContext, TEvent>\n ) {\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n const firstStateKey = this.config.states\n ? Object.keys(this.config.states)[0]\n : undefined;\n this.id =\n this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type =\n this.config.type ||\n (firstStateKey !== undefined\n ? 'compound'\n : this.config.history\n ? 'history'\n : 'atomic');\n this.description = this.config.description;\n this.schemas = this.config.schemas;\n\n validateStateNodeConfig(this);\n\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n\n this.states = (\n this.config.states\n ? mapValues(\n this.config.states,\n (stateConfig: AnyStateNodeConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }\n )\n : EMPTY_OBJECT\n ) as StateNodesConfig<TContext, TEvent>;\n\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(\n isDevelopment\n ? `No initial state specified for compound state node \"#${\n this.id\n }\". Try adding { initial: \"${firstStateKey}\" } to the state config.`\n : `No initial state specified for compound state node \"#${this.id}\".`\n );\n }\n\n // History config\n this.history =\n this.config.history === true ? 'shallow' : this.config.history || false;\n\n this.entry = this.config.entry as AnyAction | undefined;\n this.exit = this.config.exit as AnyAction | undefined;\n\n if (this.entry) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.entry._special = true;\n }\n\n if (this.exit) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.exit._special = true;\n }\n\n this.meta = this.config.meta;\n this.output =\n this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {\n const { src, registryKey } = invokeConfig;\n const invokeId = createInvokeId(this.id, i);\n const resolvedId = invokeConfig.id ?? invokeId;\n // Referenced (string) actors keep their logical name so persisted\n // snapshots reference `src: 'fetchUser'` rather than a positional id;\n // only inline logic gets the synthetic source name.\n const sourceName =\n typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;\n\n return {\n ...invokeConfig,\n src: sourceName,\n logic: src,\n id: resolvedId,\n registryKey\n } as AnyInvokeDefinition;\n });\n }\n\n /** @internal */\n public _initialize() {\n this.after = getDelayedTransitions(this) as any;\n this.transitions = formatTransitions(this);\n if (this.type === 'choice') {\n this.always = formatChoiceTransitions(this);\n } else if (this.config.always) {\n this.always = mapTransitionConfigs(this.config.always, (transition) =>\n formatTransition(this, NULL_EVENT, transition)\n );\n }\n\n for (const key of Object.keys(this.states)) {\n this.states[key]._initialize();\n }\n\n this._refreshEventMetadata();\n }\n\n /** @internal */\n public _refreshEventMetadata() {\n const on = {} as TransitionDefinitionMap<TContext, TEvent>;\n const ownEvents: EventDescriptor<any>[] = [];\n for (const [descriptor, transitions] of this.transitions) {\n (on as any)[descriptor] = transitions.slice();\n if (\n transitions.some(\n (transition) =>\n transition.target || transition.reenter || transition.to\n )\n ) {\n ownEvents.push(descriptor);\n }\n }\n this.on = on;\n this.ownEvents = ownEvents;\n\n const events = new Set<EventDescriptor<any>>(ownEvents);\n for (const state of Object.values(this.states)) {\n for (const event of state.events) {\n events.add(event);\n }\n }\n this.events = Array.from(events);\n }\n\n public get initial(): InitialTransitionDefinition {\n return memo(this, 'initial', () =>\n formatInitialTransition(this, this.config.initial)\n );\n }\n\n /** @internal */\n public next(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> | undefined {\n const descriptorKey = getEventDescriptorKey(event);\n let candidates = this._candidateCache?.get(descriptorKey);\n if (!candidates) {\n candidates = getCandidates(this, event);\n (this._candidateCache ??= new Map()).set(descriptorKey, candidates);\n }\n\n for (const candidate of candidates) {\n const guardPassed = evaluateCandidate(\n candidate,\n event,\n snapshot,\n this,\n actorScope,\n selectionResults\n );\n\n if (guardPassed) {\n return [candidate];\n }\n }\n\n return undefined;\n }\n}\n\nfunction validateStateNodeConfig(stateNode: AnyStateNode) {\n const config = stateNode.config as any;\n\n if (\n stateNode.type === 'history' &&\n !(\n (typeof config.target === 'string' && config.target.trim().length > 0) ||\n (Array.isArray(config.target) &&\n config.target.length > 0 &&\n config.target.every(\n (target: unknown) =>\n typeof target === 'string' && target.trim().length > 0\n ))\n )\n ) {\n throw new Error(\n isDevelopment\n ? `History state \"${stateNode.id}\" must declare a non-empty \\`target\\`.`\n : `Missing history target on \"${stateNode.id}\"`\n );\n }\n\n if (stateNode.type !== 'choice') {\n if (isDevelopment && config.choice !== undefined) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`choice\\`, but \\`choice\\` can only be used with \\`type: 'choice'\\`.`\n );\n }\n return;\n }\n\n if (typeof config.choice !== 'function') {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must declare a \\`choice\\` function.`\n : `Missing \\`choice\\` function on \"${stateNode.id}\"`\n );\n }\n\n if (isDevelopment) {\n for (const key of CHOICE_CONFIG_KEYS) {\n if (config[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\`.`\n );\n }\n }\n }\n}\n\nfunction formatChoiceTransitions(\n stateNode: AnyStateNode\n): AnyTransitionDefinition[] {\n const choice = (stateNode.config as any).choice;\n const validateChoiceResult = (result: any): AnyTransitionConfig => {\n if (!result || result.target === undefined) {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must resolve to a target.`\n : `Choice \"${stateNode.id}\" has no target`\n );\n }\n if (isDevelopment) {\n for (const key of ['actions', 'to'] as const) {\n if (result[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\` on a choice.`\n );\n }\n }\n }\n return result;\n };\n\n return [\n formatTransition(stateNode, NULL_EVENT, {\n to: (args: any) => validateChoiceResult(choice(args))\n } as AnyTransitionConfig)\n ];\n}\n\nfunction mapTransitionConfigs<T>(\n transitionsConfig: unknown,\n mapper: (transition: AnyTransitionConfig) => T\n): T[] {\n const transitionConfigs = toTransitionConfigArray(transitionsConfig as any);\n const transitions = new Array<T>(transitionConfigs.length);\n\n for (let i = 0; i < transitionConfigs.length; i++) {\n transitions[i] = mapper(transitionConfigs[i]);\n }\n\n return transitions;\n}\n\nfunction formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n const addTransitions = (\n descriptor: string,\n additions: AnyTransitionDefinition[]\n ) => {\n transitions.set(descriptor, [\n ...(transitions.get(descriptor) ?? []),\n ...additions\n ]);\n };\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n isDevelopment\n ? 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n : 'Null event transition key'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n mapTransitionConfigs(transitionsConfig, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = 'xstate.done.state';\n addTransitions(\n descriptor,\n mapTransitionConfigs(stateNode.config.onDone, (transition) =>\n formatTransition(stateNode, descriptor, {\n ...transition,\n matches: { ...transition.matches, stateId: stateNode.id }\n })\n )\n );\n }\n if (stateNode.config.onError) {\n const descriptor = 'xstate.error.*';\n transitions.set(\n descriptor,\n mapTransitionConfigs(stateNode.config.onError, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n const createCancelInvokeTimeoutTransition = (\n descriptor: string,\n timeoutEventId: string,\n actorId: string\n ): AnyTransitionDefinition =>\n formatTransition(stateNode, descriptor, {\n matches: { actorId },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, actorId),\n to: (_args: any, enq: any) => {\n enq.cancel(timeoutEventId);\n return {};\n }\n } as AnyTransitionConfig);\n const formatInvokeCompletionTransition = (\n descriptor: string,\n transitionConfig: AnyTransitionConfig,\n timeoutEventId: string\n ): AnyTransitionDefinition => {\n const { target, to, reenter, ...rest } = transitionConfig;\n\n return formatTransition(stateNode, descriptor, {\n ...rest,\n reenter,\n to: (args: any, enq: any) => {\n if (to) {\n let didEnqueue = false;\n const trackingEnqueue = new Proxy(enq, {\n apply(target, thisArg, argArray) {\n didEnqueue = true;\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n return (...argArray: any[]) => {\n didEnqueue = true;\n return value.apply(target, argArray);\n };\n }\n });\n const result = to(args, trackingEnqueue);\n\n if (result !== undefined || didEnqueue) {\n enq.cancel(timeoutEventId);\n }\n\n return result;\n }\n\n enq.cancel(timeoutEventId);\n return {\n target,\n reenter\n };\n }\n } as AnyTransitionConfig);\n };\n for (const invokeDef of stateNode.invoke) {\n const withInvokeMatch = (transition: AnyTransitionConfig) => ({\n ...transition,\n matches: { ...transition.matches, actorId: invokeDef.id },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id)\n });\n const invokeTimeoutEventId =\n invokeDef.timeout !== undefined\n ? createInvokeTimeoutEventId(invokeDef.id)\n : undefined;\n\n if (invokeDef.onDone) {\n const descriptor = 'xstate.done.actor';\n const invokeDoneTransitions = mapTransitionConfigs(\n invokeDef.onDone,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n );\n\n if (invokeTimeoutEventId) {\n invokeDoneTransitions.push(\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n );\n }\n\n addTransitions(descriptor, invokeDoneTransitions);\n } else if (invokeTimeoutEventId) {\n const descriptor = 'xstate.done.actor';\n addTransitions(descriptor, [\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n ]);\n }\n if (invokeDef.onError) {\n const descriptor = 'xstate.error.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onError, (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n })\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = 'xstate.snapshot.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onSnapshot, (transition) =>\n formatTransition(stateNode, descriptor, withInvokeMatch(transition))\n )\n );\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(\n delayedTransition as TransitionDefinition<TContext, AnyEventObject>\n );\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nfunction formatInitialTransition(\n stateNode: AnyStateNode,\n _target:\n | string\n | { target: string | string[]; input?: any; to?: (...args: any[]) => any }\n | undefined\n): InitialTransitionDefinition {\n const targetString =\n typeof _target === 'object' && _target !== null ? _target.target : _target;\n const input =\n typeof _target === 'object' && _target !== null ? _target.input : undefined;\n const to =\n typeof _target === 'object' && _target !== null ? _target.to : undefined;\n const targetStrings = Array.isArray(targetString)\n ? targetString\n : targetString\n ? [targetString]\n : [];\n const resolvedTargets = targetStrings.map((target) =>\n target.startsWith('#')\n ? stateNode.machine.getStateNodeById(target.slice(1))\n : stateNode.states[target]\n );\n if (resolvedTargets.some((target) => !target)) {\n throw new Error(\n isDevelopment\n ? `Initial state node \"${targetStrings.find((_, index) => !resolvedTargets[index])}\" not found on parent state node #${stateNode.id}`\n : `Initial state not found on \"#${stateNode.id}\"`\n );\n }\n const transition: InitialTransitionDefinition = {\n source: stateNode,\n target: resolvedTargets.length\n ? (resolvedTargets as AnyStateNode[])\n : undefined,\n input,\n to\n };\n\n return transition;\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE, createActor } from './createActor.ts';\nimport {\n createErrorPlatformEvent,\n createInitEvent,\n createInvokeTimeoutEvent\n} from './eventUtils.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { parseGeneratedActorId } from './system.ts';\nimport { createRemoteActorRef } from './remoteActorRef.ts';\n\nimport { createSpawner } from './spawn.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from './getNextSnapshot.ts';\nimport { withActorSelf } from './actorScope.ts';\nimport {\n createMachineSnapshot,\n cloneMachineSnapshot,\n getPersistedSnapshot,\n MachineSnapshot\n} from './State.ts';\nimport { setSnapshotActorRef } from './snapshotActorRef.ts';\nimport { StateNode } from './StateNode.ts';\nimport {\n formatRouteTransitions,\n getAllStateNodes,\n getStateNodeByPath,\n getStateNodes,\n getTransitionResult,\n hasEffect,\n initialMicrostep,\n isInFinalState,\n isStateId,\n macrostep,\n resolveStateValue,\n transitionNode,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport {\n beginSpawnAllocation,\n createSpawnEffect,\n resolveActionsWithContext,\n mergeActorIdCounters,\n takeSpawnAllocationCounters\n} from './transitionActions.ts';\nimport { AnyActorSystem } from './system.ts';\nimport type {\n ActorLogic,\n ActorLogicTransitionResult,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyTransitionDefinition,\n Equals,\n EventDescriptor,\n EmittedFrom,\n EventObject,\n EventFromLogic,\n ExecutableActionObject,\n ExecutableActionObjectFromLogic,\n HistoryValue,\n InputFrom,\n IsAny,\n LogicalTimer,\n MachineContext,\n MetaObject,\n OutputFrom,\n Snapshot,\n SnapshotFrom,\n StateValue,\n StateSchema,\n SnapshotStatus,\n AnyStateNode\n} from './types.ts';\nimport {\n AnyMachineSchemas,\n DelaySourceMap,\n GuardSourceMap,\n Sources,\n Next_MachineConfig,\n MachineOptions\n} from './types.v6.ts';\nimport {\n matchesEventDescriptor,\n resolveReferencedActor,\n toStatePath\n} from './utils.ts';\nimport { assertValid } from './validation.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type { PersistedMachineSnapshot } from './machineVersion.types.ts';\n\nconst STATE_IDENTIFIER = '#';\n\nfunction findEventSchema(\n schemas: Record<string, StandardSchemaV1> | undefined,\n eventType: string\n): StandardSchemaV1 | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (Object.hasOwn(schemas, eventType)) {\n return schemas[eventType];\n }\n\n const descriptor = Object.keys(schemas).find((key) =>\n matchesEventDescriptor(eventType, key)\n );\n return descriptor === undefined ? undefined : schemas[descriptor];\n}\n\nlet emptyCanActor: AnyActor | undefined;\nlet emptyCanActorScope: AnyActorScope | undefined;\n\nfunction getEmptyCanActor(): AnyActor {\n // A minimal inert actor used purely as the `self`/`parent` argument when\n // dry-running transitions for `snapshot.can(...)`. Intentionally not built\n // on `createLogic` so `can()` does not pull that machinery into bundles.\n return (emptyCanActor ??= createActor({\n transition: (snapshot: any) => [snapshot, []],\n initialTransition: () => [\n { status: 'active', output: undefined, error: undefined },\n []\n ],\n getInitialSnapshot: () => ({\n status: 'active',\n output: undefined,\n error: undefined\n }),\n getPersistedSnapshot: (snapshot: any) => snapshot\n } as any) as AnyActor);\n}\n\nfunction getEmptyCanActorScope(): AnyActorScope {\n if (emptyCanActorScope) {\n return emptyCanActorScope;\n }\n\n const actor = getEmptyCanActor();\n emptyCanActorScope = {\n self: actor,\n logger: () => {},\n id: '',\n sessionId: '',\n defer: () => {},\n system: actor.system,\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n return emptyCanActorScope;\n}\n\ntype CompatibleProvidedActorSource<\n TExpected extends AnyActorLogic,\n TActual extends AnyActorLogic\n> =\n IsAny<TActual> extends true\n ? TActual\n : [OutputFrom<TActual>] extends [OutputFrom<TExpected>]\n ? [Omit<SnapshotFrom<TActual>, 'input'>] extends [\n Omit<SnapshotFrom<TExpected>, 'input'>\n ]\n ? [InputFrom<TExpected>] extends [InputFrom<TActual>]\n ? [EventFromLogic<TExpected>] extends [EventFromLogic<TActual>]\n ? [EmittedFrom<TActual>] extends [EmittedFrom<TExpected>]\n ? TActual\n : never\n : never\n : never\n : never\n : never;\n\ntype ProvidedActors<\n TExpectedActorMap extends Sources['actors'],\n TProvidedActorMap extends Partial<\n Record<keyof TExpectedActorMap & string, AnyActorLogic>\n >\n> = {\n [K in keyof TProvidedActorMap]: K extends keyof TExpectedActorMap\n ? TProvidedActorMap[K] extends AnyActorLogic\n ? CompatibleProvidedActorSource<\n TExpectedActorMap[K],\n TProvidedActorMap[K]\n >\n : never\n : never;\n};\n\nexport class StateMachine<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TConfig extends StateSchema,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TInternalEvent extends EventObject = never\n> implements ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n> {\n /**\n * @internal Type-only marker for the actor's internal event protocol. Not\n * `declare` (the build's babel pipeline rejects declare class fields); the\n * one `undefined` property this emits per machine instance is inert.\n */\n readonly _internalEventType!: TInternalEvent;\n\n /** The machine's own version. */\n public version?: string;\n\n public schemas: AnyMachineSchemas | undefined;\n\n /** Standard Schema for snapshots persisted by this machine version. */\n public readonly snapshotSchema: StandardSchemaV1<\n unknown,\n Snapshot<unknown> & PersistedMachineSnapshot & { context: TContext }\n >;\n\n /** Standard Schema for complete events accepted by this machine version. */\n public readonly eventSchema: StandardSchemaV1<unknown, TEvent>;\n\n public sources: Sources;\n\n /** Runtime options for machine execution. */\n public options: MachineOptions;\n\n /** @internal */\n public idMap: Map<string, AnyStateNode> = new Map();\n\n public root: StateNode<TContext, TEvent>;\n\n public id: string;\n\n public states: StateNode<TContext, TEvent>['states'];\n public events: Array<EventDescriptor<TEvent>>;\n public internalEventDescriptors: ReadonlyArray<string>;\n /** @internal Skips eventless-selection scans for machines without `always`. */\n public _hasEventlessTransitions: boolean;\n constructor(\n /** The raw config used to create the machine. */\n public config: Next_MachineConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TEmitted\n > & {\n schemas?: AnyMachineSchemas;\n internalEvents?: readonly string[];\n },\n sources?: Sources,\n public validator?: ActorLogicValidator\n ) {\n this.id = config.id || '(machine)';\n this.sources = {\n actors: config.actors ?? {},\n actions: config.actions ?? {},\n delays: (config.delays ?? {}) as Sources['delays'],\n guards: config.guards ?? {},\n ...sources\n };\n if (isDevelopment) {\n // The `@xstate.` prefix is reserved for built-in serialized action and\n // guard descriptors — user source names must not collide.\n for (const kind of ['actions', 'guards', 'actors', 'delays'] as const) {\n for (const key of Object.keys(this.sources[kind])) {\n if (key.startsWith('@xstate.')) {\n throw new Error(\n `Invalid ${kind} name '${key}': the '@xstate.' prefix is reserved for built-in descriptors.`\n );\n }\n }\n }\n }\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.snapshotSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (value === null || typeof value !== 'object') {\n return { issues: [{ message: 'Expected a persisted snapshot.' }] };\n }\n const snapshot: Record<string, unknown> = {\n historyValue: {},\n timers: {},\n ...(value as Record<string, unknown>)\n };\n const contextSchema = this.schemas?.context;\n let context = snapshot.context;\n if (contextSchema) {\n const result = await contextSchema['~standard'].validate(context);\n if (result.issues) {\n return {\n issues: [\n {\n message: `Invalid context for machine '${this.id}' version '${this.version}': ${result.issues[0]?.message}`\n }\n ]\n };\n }\n context = result.value;\n }\n for (const key of ['value', 'children'] as const) {\n if (!(key in snapshot)) {\n return {\n issues: [{ message: `Persisted snapshot is missing '${key}'.` }]\n };\n }\n }\n if (\n !['active', 'done', 'error', 'stopped'].includes(\n snapshot.status as string\n )\n ) {\n return {\n issues: [{ message: 'Persisted snapshot has invalid status.' }]\n };\n }\n for (const key of ['children', 'historyValue', 'timers'] as const) {\n if (\n snapshot[key] === null ||\n typeof snapshot[key] !== 'object' ||\n Array.isArray(snapshot[key])\n ) {\n return {\n issues: [\n { message: `Persisted snapshot has invalid '${key}'.` }\n ]\n };\n }\n }\n try {\n this.resolveState({\n value: snapshot.value as StateValue,\n context\n } as any);\n } catch (error) {\n return {\n issues: [\n {\n message:\n error instanceof Error\n ? error.message\n : 'Persisted snapshot has invalid state value.'\n }\n ]\n };\n }\n return {\n value: { ...snapshot, context } as Snapshot<unknown> &\n PersistedMachineSnapshot & { context: TContext }\n };\n }\n }\n };\n this.eventSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (\n value === null ||\n typeof value !== 'object' ||\n typeof (value as EventObject).type !== 'string'\n ) {\n return { issues: [{ message: 'Expected an event object.' }] };\n }\n const event = value as EventObject;\n const eventSchemas = this.schemas?.events;\n const internalEventSchemas = this.schemas?.internalEvents;\n const isFrameworkEvent =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n const schema =\n findEventSchema(internalEventSchemas, event.type) ??\n findEventSchema(eventSchemas, event.type);\n if (\n (eventSchemas || internalEventSchemas) &&\n !schema &&\n !isFrameworkEvent\n ) {\n return {\n issues: [\n {\n message: `Unknown event '${event.type}' for machine '${this.id}' version '${this.version}'.`\n }\n ]\n };\n }\n if (!schema) {\n return { value: event as TEvent };\n }\n const { type, ...payload } = event;\n const result = await schema['~standard'].validate(payload);\n if (result.issues) {\n return result;\n }\n if (result.value === null || typeof result.value !== 'object') {\n return { issues: [{ message: 'Expected an event payload.' }] };\n }\n return { value: { ...result.value, type } as TEvent };\n }\n }\n };\n this.internalEventDescriptors = [\n ...Object.keys(this.schemas?.internalEvents ?? {}),\n ...(this.config.internalEvents ?? [])\n ];\n this.options = {\n maxIterations: Infinity,\n ...this.config.options\n };\n\n this.transition = this.transition.bind(this);\n this.initialTransition = this.initialTransition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.restoreSnapshot = this.restoreSnapshot.bind(this);\n this.start = this.start.bind(this);\n\n this.root = new StateNode(config as any, {\n _key: this.id,\n _machine: this as any\n });\n\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.root._refreshEventMetadata();\n this._hasEventlessTransitions = Array.from(this.idMap.values()).some(\n (stateNode) => !!stateNode.always?.length\n );\n\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided sources.\n *\n * @param sources Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided sources.\n */\n public provide<\n const TProvidedActorMap extends Partial<\n Record<keyof TActorMap & string, AnyActorLogic>\n > = {}\n >(sources: {\n actions?: Partial<TActionMap>;\n actors?: TProvidedActorMap & ProvidedActors<TActorMap, TProvidedActorMap>;\n // Mapped over the known names (not an index signature) so unknown source\n // names are still rejected, while entries keep typed args/return values.\n guards?: Partial<TGuardMap> & {\n [K in keyof TGuardMap]?: GuardSourceMap<TContext, TEvent>[string];\n };\n // Delays are widened to `number | fn` per entry (not Partial<TDelayMap>)\n // so a fixed delay can be swapped for a computed one and vice versa.\n delays?: {\n [K in keyof TDelayMap]?: DelaySourceMap<TContext, TEvent>[string];\n };\n }): this {\n const { actions, guards, actors, delays } = this.sources;\n\n const provided = new StateMachine(\n this.config,\n {\n actions: {\n ...actions,\n ...sources.actions\n } as Sources['actions'],\n guards: {\n ...guards,\n ...sources.guards\n } as Sources['guards'],\n actors: {\n ...actors,\n ...sources.actors\n } as Sources['actors'],\n delays: {\n ...delays,\n ...sources.delays\n } as Sources['delays']\n },\n this.validator\n ) as unknown as this;\n // Providing sources does not change the serializable definition.\n provided._json = this._json;\n return provided;\n }\n\n public resolveState(\n config: {\n value: StateValue;\n context?: TContext;\n historyValue?: HistoryValue;\n status?: SnapshotStatus;\n output?: TOutput;\n error?: unknown;\n } & ([TContext] extends [never]\n ? {}\n : Equals<TContext, MachineContext> extends false\n ? { context: unknown }\n : {})\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(\n getStateNodes(this.root, resolvedStateValue)\n );\n const nodes = [...nodeSet];\n\n return createMachineSnapshot(\n {\n _nodes: nodes,\n value: resolvedStateValue,\n context: config.context || ({} as TContext),\n children: {},\n status: isInFinalState(nodeSet, this.root)\n ? 'done'\n : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n },\n this\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n public transition(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope?: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(\n this,\n snapshot as SnapshotFrom<this>\n )) as NonNullable<typeof actorScope>;\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'event',\n logic: this,\n event,\n eventOrigin:\n actorScope && (actorScope.self as any)._lastSourceRef\n ? 'actor'\n : 'external'\n });\n }\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);\n }\n beginSpawnAllocation(resolvedActorScope);\n const fastSnapshot = this._transitionFast(\n snapshot,\n event,\n resolvedActorScope\n );\n if (fastSnapshot) {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);\n }\n const returnedSnapshot =\n usesInertScope && fastSnapshot !== snapshot\n ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot)\n : this._attachPureActorRef(fastSnapshot, resolvedActorScope);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects: []\n });\n }\n return [returnedSnapshot, []];\n }\n\n const { snapshot: nextSnapshot, microsteps } = macrostep(\n snapshot,\n event,\n resolvedActorScope,\n []\n );\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);\n }\n const returnedSnapshot = usesInertScope\n ? nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(resolvedActorScope, nextSnapshot)\n : this._attachPureActorRef(nextSnapshot, resolvedActorScope);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [\n returnedSnapshot as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n effects\n ];\n }\n\n private _collectEffects(\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ExecutableActionObjectFromLogic<this>[] {\n return microsteps.flatMap(\n ([, actions]) => actions\n ) as ExecutableActionObjectFromLogic<this>[];\n }\n\n private _attachPureActorRef<TSnapshot extends AnyMachineSnapshot>(\n snapshot: TSnapshot,\n actorScope: AnyActorScope,\n skipInitializingActor = false\n ): TSnapshot {\n if (isInertActorScope(actorScope)) {\n return snapshot;\n }\n if (\n skipInitializingActor &&\n (\n actorScope.self as AnyActor & {\n _actorScope?: AnyActorScope;\n _snapshot?: unknown;\n }\n )._actorScope === actorScope &&\n (actorScope.self as AnyActor & { _snapshot?: unknown })._snapshot ===\n undefined\n ) {\n return snapshot;\n }\n setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);\n return snapshot;\n }\n\n private _transitionFast(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ):\n | MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | undefined {\n if (\n snapshot.status !== 'active' ||\n typeof snapshot.value !== 'string' ||\n this.root.always?.length\n ) {\n return undefined;\n }\n\n const sourceNode = this.root.states[snapshot.value];\n if (\n !sourceNode ||\n sourceNode.type !== 'atomic' ||\n sourceNode.exit ||\n sourceNode.invoke.length ||\n sourceNode.always?.length ||\n sourceNode.after?.length\n ) {\n return undefined;\n }\n\n const transitions = sourceNode.transitions.get(event.type);\n if (transitions?.length !== 1) {\n return undefined;\n }\n\n const selected = transitions[0];\n if (\n selected.guard ||\n selected.actions ||\n selected.to ||\n selected.reenter ||\n selected.input ||\n typeof selected.context === 'function' ||\n (selected.target && selected.target.length !== 1)\n ) {\n return undefined;\n }\n\n const targetNode = selected.target?.[0] ?? sourceNode;\n const stateChanged = targetNode !== sourceNode;\n if (\n targetNode.parent !== this.root ||\n targetNode.type !== 'atomic' ||\n (stateChanged &&\n (targetNode.entry ||\n targetNode.invoke.length ||\n targetNode.always?.length ||\n targetNode.after?.length))\n ) {\n return undefined;\n }\n\n const context =\n selected.context !== undefined\n ? ({ ...snapshot.context, ...selected.context } as TContext)\n : snapshot.context;\n\n if (\n !isInertActorScope(actorScope) &&\n (actorScope.system._hasInspectionObservers?.() ?? true)\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(selected);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n\n return cloneMachineSnapshot(snapshot, {\n ...(context !== snapshot.context ? { context } : {}),\n ...(stateChanged ? { _nodes: [this.root, targetNode] } : {})\n });\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n public microstep(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope\n ): Array<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n > {\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n const snapshots = new Array(microsteps.length);\n\n for (let i = 0; i < microsteps.length; i++) {\n snapshots[i] = microsteps[i][0];\n }\n\n return snapshots;\n }\n\n public getTransitionData(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> {\n return (\n transitionNode(\n this.root,\n snapshot.value,\n snapshot,\n event,\n actorScope,\n selectionResults\n ) || []\n );\n }\n\n public isInternalEventType(eventType: string): boolean {\n if (eventType === XSTATE_TIMER) {\n return true;\n }\n for (const descriptor of this.internalEventDescriptors) {\n if (matchesEventDescriptor(eventType, descriptor)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines whether sending the `event` to the given snapshot would select a\n * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that\n * non-machine bundles don't pay for the transition-resolution machinery.\n *\n * @internal\n */\n public _canTransition(snapshot: AnyMachineSnapshot, event: TEvent): boolean {\n const emptyActorScope = getEmptyCanActorScope();\n const transitionData = this.getTransitionData(\n snapshot as any,\n event,\n emptyActorScope\n );\n\n if (!transitionData?.length) {\n return false;\n }\n\n // Check that at least one transition is not forbidden\n for (const transition of transitionData) {\n if (transition.target !== undefined) {\n return true;\n }\n\n const res = getTransitionResult(\n transition,\n snapshot,\n event,\n emptyActorScope,\n { resolveActions: false }\n );\n if (\n res.targets?.length ||\n res.context ||\n hasEffect(\n transition,\n snapshot.context,\n event,\n snapshot,\n emptyActorScope\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns the error event that the actor should transition with to recover\n * from an execution error, if any active state node declares `onError`.\n *\n * @internal\n */\n public getExecutionErrorEvent(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n error: unknown\n ): TEvent | undefined {\n if (\n (snapshot as any)?.status !== 'active' ||\n !snapshot.nodes?.some((stateNode) => stateNode.config.onError)\n ) {\n return undefined;\n }\n return createErrorPlatformEvent('execution', error) as unknown as TEvent;\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(\n actorScope: AnyActorScope,\n initEvent: any\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const { context } = this.config;\n\n const preInitial = createMachineSnapshot(\n {\n context:\n typeof context !== 'function' && context ? context : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n );\n\n if (typeof context === 'function') {\n const children = {};\n const spawn = createSpawner(actorScope, this.sources.actors, children);\n const resolvedContext = context(\n withActorSelf(\n {\n spawn,\n input: initEvent.input,\n actors: this.sources.actors\n },\n actorScope\n )\n );\n const [nextState] = resolveActionsWithContext(\n preInitial,\n initEvent,\n actorScope,\n []\n ) as any;\n if (resolvedContext) {\n nextState.context = resolvedContext;\n }\n if (Object.keys(children).length > 0) {\n nextState.children = {\n ...nextState.children,\n ...children\n };\n // Commit the transaction counters so context-factory allocations\n // persist with the snapshot: a freed id is never handed out again\n // after a restore or in a fresh replay process. (The spawner already\n // registered each child for string-id resolution.)\n const counters = takeSpawnAllocationCounters(actorScope);\n if (counters) {\n nextState._nextActorIds = mergeActorIdCounters(\n nextState._nextActorIds,\n counters\n );\n }\n }\n return nextState as SnapshotFrom<this>;\n }\n\n return preInitial as SnapshotFrom<this>;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n public getInitialSnapshot(\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >,\n input?: TInput\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n return this.initialTransition(input, actorScope)[0];\n }\n\n public initialTransition(\n input: TInput | undefined,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'input',\n logic: this,\n input\n });\n }\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n beginSpawnAllocation(resolvedActorScope);\n const initEvent = createInitEvent(input) as unknown as TEvent; // TODO: fix;\n const internalQueue: AnyEventObject[] = [];\n const preInitialState = this._getPreInitialState(\n resolvedActorScope,\n initEvent\n );\n const contextSpawnEffects = Object.values(preInitialState.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n const finalizeInitialResult = (\n macroState: AnyMachineSnapshot,\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ActorLogicTransitionResult<\n SnapshotFrom<this>,\n ExecutableActionObjectFromLogic<this>\n > => {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, macroState, false);\n }\n const returnedSnapshot = usesInertScope\n ? attachSnapshotActorRef(resolvedActorScope, macroState)\n : this._attachPureActorRef(macroState, resolvedActorScope, true);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [returnedSnapshot as SnapshotFrom<this>, effects];\n };\n\n try {\n const [nextState, initialActions] = initialMicrostep(\n this.root,\n preInitialState,\n resolvedActorScope,\n initEvent,\n internalQueue\n );\n\n const { snapshot: macroState, microsteps } = macrostep(\n nextState,\n initEvent as AnyEventObject,\n resolvedActorScope,\n internalQueue,\n [\n [nextState, [...contextSpawnEffects, ...initialActions]] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(macroState, microsteps);\n } catch (err) {\n if (!this.root.config.onError) {\n throw err;\n }\n const errorEvent = createErrorPlatformEvent('execution', err);\n const errorMacrostep = macrostep(\n preInitialState,\n errorEvent,\n resolvedActorScope,\n [],\n [\n [preInitialState, contextSpawnEffects] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(\n errorMacrostep.snapshot,\n errorMacrostep.microsteps\n );\n }\n }\n\n public start(\n snapshot?: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n ): void {\n // Start rehydrated children that were active when persisted. Freshly\n // invoked/spawned children are NOT started here — they start via deferred\n // `@xstate.start` actions so sync start errors route to `onError`.\n if (!snapshot?.children) {\n return;\n }\n const children = snapshot.children as unknown as Record<string, AnyActor>;\n for (const childId in children) {\n if (!Object.hasOwn(children, childId)) {\n continue;\n }\n const child = children[childId];\n if (\n (child as any)._rehydrated &&\n (child as any).getSnapshot?.().status === 'active'\n ) {\n (child as any).start();\n }\n }\n }\n\n public getStateNodeById(stateId: string): StateNode<TContext, TEvent> {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0])\n ? fullPath[0].slice(STATE_IDENTIFIER.length)\n : fullPath[0];\n\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(\n `Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`\n );\n }\n return getStateNodeByPath(stateNode, relativePath) as StateNode<\n TContext,\n TEvent\n >;\n }\n\n public getPersistedSnapshot(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n options?: unknown\n ) {\n return getPersistedSnapshot(snapshot, options);\n }\n\n /**\n * The original JSON definition this machine was created from (set by\n * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless\n * round-trips.\n *\n * @internal\n */\n public _json?: Record<string, unknown>;\n\n public restoreSnapshot(\n snapshot: Snapshot<unknown>,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n const snapshotMachine = (snapshot as any).machine;\n // A live machine snapshot carries its producing machine so helpers such as\n // `matches()` can resolve state nodes. That runtime association is not the\n // persisted `{ id, version }` identity written by getPersistedSnapshot().\n const persistedMachine =\n snapshotMachine &&\n typeof snapshotMachine === 'object' &&\n typeof snapshotMachine.transition === 'function' &&\n 'root' in snapshotMachine\n ? undefined\n : snapshotMachine;\n const legacyPersistedVersion: string | undefined = (snapshot as any)\n .version;\n const persistedVersion: string | undefined =\n typeof persistedMachine?.version === 'string'\n ? persistedMachine.version\n : legacyPersistedVersion;\n if (\n legacyPersistedVersion !== undefined &&\n persistedMachine?.version !== undefined &&\n persistedMachine.version !== legacyPersistedVersion\n ) {\n throw new Error(\n `Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`\n );\n }\n if (\n persistedMachine &&\n typeof persistedMachine.id === 'string' &&\n persistedMachine.id !== this.id\n ) {\n throw new Error(\n isDevelopment\n ? `Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${this.id}' was provided.`\n : `Machine ID mismatch: persisted snapshot machine '${persistedMachine.id}' does not match '${this.id}'.`\n );\n }\n if (persistedVersion !== this.version) {\n const migrate = (this.config as any).migrate;\n if (typeof migrate !== 'function') {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}' for machine '${this.id}'. Provide a \\`migrate(persistedSnapshot, fromVersion)\\` function in the machine config to migrate old snapshots.`\n : `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`\n );\n }\n snapshot = migrate(snapshot, persistedVersion);\n }\n\n const snapshotData = snapshot as any;\n const children: Record<string, AnyActor> = {};\n const snapshotChildren: Record<\n string,\n {\n src: string | AnyActorLogic;\n snapshot?: Snapshot<unknown>;\n address?: string;\n remote?: boolean;\n incarnation?: string;\n syncSnapshot?: boolean;\n registryKey?: string;\n }\n > = snapshotData.children;\n\n for (const actorId of Object.keys(snapshotChildren)) {\n const actorData = snapshotChildren[actorId];\n\n if (actorData.remote === true && actorData.address !== undefined) {\n if (typeof actorData.src !== 'string') {\n // Fail loudly instead of fabricating a source key that hosts would\n // route by.\n throw new Error(\n `Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`\n );\n }\n // The child's state lives with another runtime; restore a\n // location-transparent handle constructed from its identity alone.\n // The handle keeps its persisted address verbatim: the owning\n // runtime's identity for the child wins over the local parent chain.\n const handle = createRemoteActorRef(resolvedActorScope.system, {\n id: actorId,\n address: actorData.address,\n src: actorData.src,\n parent: resolvedActorScope.self,\n registryKey: actorData.registryKey,\n syncSnapshot: actorData.syncSnapshot,\n incarnation: actorData.incarnation\n });\n if (actorData.registryKey) {\n resolvedActorScope.system._set(actorData.registryKey, handle);\n }\n children[actorId] = handle;\n continue;\n }\n\n const childState = actorData.snapshot;\n const src = actorData.src;\n\n const logic =\n typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n\n if (!logic) {\n const sourceId = typeof src === 'string' ? src : '<unknown>';\n throw new Error(\n `Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`\n );\n }\n\n const actor = resolvedActorScope.system.createActorRef(logic, {\n id: actorId,\n parent: resolvedActorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n registryKey: actorData.registryKey\n });\n // Mark so `start()` knows to start this child (freshly invoked/spawned\n // children are started via deferred `@xstate.start` actions instead).\n (actor as any)._rehydrated = true;\n\n children[actorId] = actor;\n }\n\n const timers: Record<string, LogicalTimer> = {};\n const persistedTimers: Record<\n string,\n {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n target: string | { type: 'parent' };\n }\n > = snapshotData.timers ?? {};\n for (const [id, timer] of Object.entries(persistedTimers)) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n const actorId = (event as AnyEventObject).actorId as string;\n const child = children[actorId];\n if (child) {\n event = createInvokeTimeoutEvent(actorId, child.sessionId);\n }\n }\n const target =\n typeof timer.target === 'string'\n ? timer.target === 'self'\n ? 'self'\n : children[timer.target]\n : resolvedActorScope.self._parent;\n if (!target) {\n const targetDescription =\n typeof timer.target === 'string' ? timer.target : timer.target.type;\n throw new Error(\n `Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`\n );\n }\n timers[id] = { ...timer, event, target };\n }\n\n const reviveHistoryValue = (\n historyValue: Record<\n string,\n ({ id: string } | StateNode<TContext, TEvent>)[]\n >\n ): HistoryValue => {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived: HistoryValue = {};\n for (const key of Object.keys(historyValue)) {\n const arr = historyValue[key];\n\n for (const item of arr) {\n let resolved: StateNode<TContext, TEvent> | undefined;\n\n if (item instanceof StateNode) {\n resolved = item;\n } else {\n try {\n resolved = this.root.machine.getStateNodeById(item.id);\n } catch {\n if (isDevelopment) {\n console.warn(`Could not resolve StateNode for id: ${item.id}`);\n }\n }\n }\n\n if (!resolved) {\n continue;\n }\n\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n };\n\n const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);\n\n const validateStateValue = (\n stateValue: StateValue,\n node: AnyStateNode,\n path: string[]\n ): void => {\n const missingStateError = (statePath: string[]) =>\n new Error(\n `Persisted snapshot references state '${statePath.join('.')}' which does not exist on machine '${this.id}'.`\n );\n if (typeof stateValue === 'string') {\n if (!node.states[stateValue]) {\n throw missingStateError(path.concat(stateValue));\n }\n return;\n }\n if (!stateValue || typeof stateValue !== 'object') {\n return;\n }\n for (const key of Object.keys(stateValue)) {\n const childNode = node.states[key];\n if (!childNode) {\n throw missingStateError(path.concat(key));\n }\n validateStateValue(stateValue[key]!, childNode, path.concat(key));\n }\n };\n validateStateValue(snapshotData.value, this.root, []);\n\n const nodes = Array.from(\n getAllStateNodes(getStateNodes(this.root, snapshotData.value))\n );\n\n const {\n version: _persistedSnapshotVersion,\n // The legacy system-wide counter: superseded by per-snapshot\n // `_nextActorIds` plus the child-id fold below; dropped so old and new\n // snapshots round-trip to the same shape.\n _nextActorId: _legacyNextActorId,\n ...persistedRest\n } = snapshot as any;\n // Fold generated-shaped child ids into the counters as a floor: snapshots\n // persisted before per-actor counters (or hand-crafted ones) still must\n // never reuse a live child's id.\n let restoredCounters: Record<string, number> | undefined =\n persistedRest._nextActorIds;\n for (const childId of Object.keys(snapshotChildren)) {\n const generated = parseGeneratedActorId(childId);\n if (\n generated &&\n (restoredCounters?.[generated.prefix] ?? 0) <= generated.index\n ) {\n restoredCounters = {\n ...restoredCounters,\n [generated.prefix]: generated.index + 1\n };\n }\n }\n const restoredSnapshot = createMachineSnapshot(\n {\n ...persistedRest,\n children,\n timers,\n _nextActorIds: restoredCounters,\n _nodes: nodes,\n value: snapshotData.value,\n historyValue: revivedHistoryValue,\n _stateInputs: snapshotData.stateInputs ?? {}\n },\n this,\n resolvedActorScope.self\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n\n const seen = new WeakSet<Record<string, unknown>>();\n\n function reviveContext(contextPart: Record<string, unknown>) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (const key of Object.keys(contextPart)) {\n const value: unknown = contextPart[key];\n\n if (value && typeof value === 'object') {\n if ('xstate$type' in value && value.xstate$type === ACTOR_REF_TYPE) {\n contextPart[key] = children[(value as any).id];\n continue;\n }\n reviveContext(value as typeof contextPart);\n }\n }\n }\n\n reviveContext(restoredSnapshot.context);\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);\n return attachSnapshotActorRef(resolvedActorScope, restoredSnapshot);\n }\n\n return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);\n }\n}\n","import {\n allocateChildId,\n assertChildIdFree,\n reserveChildId\n} from './transitionActions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport {\n ActorFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n ConditionalRequired,\n InputFrom,\n IsNotNever,\n RegistryKeyForLogic,\n SystemRegistry,\n type RequiredLogicInput\n} from './types.ts';\n\nexport type Spawner<TSystemRegistry extends SystemRegistry = SystemRegistry> = <\n TLogic extends AnyActorLogic\n>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: unknown }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n) => ActorFromLogic<TLogic>;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n actors: Record<string, AnyActorLogic>,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner {\n return ((src, options) => {\n const referencedSrc = resolveRegisteredActorSource(actors, src);\n // Generated ids come from the same transaction allocator as `enq.spawn`,\n // so context-factory allocations persist with the snapshot and never\n // collide with later spawns.\n const id =\n options?.id ?? allocateChildId(actorScope, referencedSrc ?? src).id;\n if (options?.id !== undefined) {\n assertChildIdFree(actorScope, options.id);\n reserveChildId(actorScope, options.id);\n }\n const actor = actorScope.system.createActorRef(src, {\n id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src: referencedSrc ?? src,\n registryKey: options?.registryKey\n });\n spawnedChildren[actor.id] = actor;\n return actor;\n }) as Spawner;\n}\n","import { StandardSchemaV1 } from './schema.types.ts';\nimport { StateMachine } from './StateMachine.ts';\nimport {\n AnyActorRef,\n EventObject,\n AnyEventObject,\n Cast,\n MachineContext,\n ProvidedActor,\n StateValueFromStateSchema,\n ToChildren,\n MetaObject,\n StateSchema,\n DoNotInfer,\n RoutableStateId,\n Compute\n} from './types.ts';\nimport {\n Sources,\n DelayMapFromNames,\n InferChildren,\n InferOutput,\n SchemaOrConfigOutput,\n InferEvents,\n InferInternalEvents,\n Next_MachineConfig,\n Next_StateNodeConfig,\n ValidateDelayReferences,\n ValidateHistoryDefaults,\n ValidateStateTargets,\n ValidateTopLevelFinalOutputs,\n WidenLiterals,\n WithDefault\n} from './types.v6.ts';\n\ntype MergeChildren<\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActor extends ProvidedActor\n> = [keyof TChildren] extends [never]\n ? Compute<ToChildren<TActor>>\n : Compute<TChildren>;\n\ntype MachineIdentity<TConfig> = {\n readonly id: TConfig extends { id: infer TId extends string }\n ? TId\n : '(machine)';\n readonly version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n};\n\ntype TestValue =\n | string\n | {\n [k: string]: TestValue | undefined;\n };\n\ntype _GroupTestValues<TTestValue extends string | TestValue> =\n TTestValue extends string\n ? TTestValue extends `${string}.${string}`\n ? [never, never]\n : [TTestValue, never]\n : [never, TTestValue];\n\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n * id: 'light',\n * initial: 'green',\n * states: {\n * green: {\n * on: {\n * TIMER: { target: 'yellow' }\n * }\n * },\n * yellow: {\n * on: {\n * TIMER: { target: 'red' }\n * }\n * },\n * red: {\n * on: {\n * TIMER: { target: 'green' }\n * }\n * }\n * }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n * to provide machine sources instead.\n */\n// Overload 1: With schemas.context — context type inferred from schema\nexport function createMachine<\n TContextSchema extends StandardSchemaV1,\n const TEventSchemaMap extends Record<string, StandardSchemaV1>,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1>,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>,\n TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1>,\n _TEvent extends EventObject,\n TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & {\n schemas: { context: TContextSchema; children?: TChildrenSchemaMap };\n } & ValidateTopLevelFinalOutputs<\n TSS,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n InferOutput<TContextSchema, MachineContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Overload 2: Without schemas.context — context type inferred from config.context\nexport function createMachine<\n TContext extends MachineContext = never,\n const TEventSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1 = StandardSchemaV1,\n TTagSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {},\n _TEvent extends EventObject = EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TActionMap extends Sources['actions'] = Sources['actions'],\n TActorMap extends Sources['actors'] = Sources['actors'],\n TGuardMap extends Sources['guards'] = Sources['guards'],\n TDelayMap extends Sources['delays'] = Sources['delays'],\n TDelays extends string = string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string =\n StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput = unknown,\n const TSS extends StateSchema = StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n StandardSchemaV1,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n false\n > & {\n schemas?: { context?: never };\n // TContext inference site: the `const` state-schema inference above\n // suppresses literal widening, so context is widened explicitly via\n // WidenLiterals before being consumed by handlers and the snapshot.\n context?:\n | TContext\n | ((_: {\n spawn: any;\n actors: TActorMap;\n input: InferOutput<TInputSchema, unknown>;\n self: any;\n }) => TContext);\n } & ValidateTopLevelFinalOutputs<\n TSS,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n WidenLiterals<TContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Implementation\nexport function createMachine(config: any): any {\n return new StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any, // TMeta\n any, // TStateSchema\n any,\n any,\n any,\n any\n >(config) as any;\n}\n\nexport function createStateConfig<\n TContextSchema extends StandardSchemaV1,\n TEventSchema extends StandardSchemaV1,\n TEmittedSchema extends StandardSchemaV1,\n _TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n // TContext extends MachineContext,\n _TEvent extends StandardSchemaV1.InferOutput<TEventSchema> & EventObject, // TODO: consider using a stricter `EventObject` here\n _TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n _TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n _TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n Next_StateNodeConfig<\n InferOutput<TContextSchema, MachineContext>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEventSchema> & EventObject>,\n DoNotInfer<TDelays>,\n DoNotInfer<StandardSchemaV1.InferOutput<TTagSchema> & string>,\n DoNotInfer<StandardSchemaV1.InferOutput<TOutputSchema>>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEmittedSchema> & EventObject>,\n DoNotInfer<InferOutput<TMetaSchema, MetaObject>>,\n DoNotInfer<Record<string, AnyActorRef | undefined>>,\n DoNotInfer<TActionMap>,\n DoNotInfer<TActorMap>,\n DoNotInfer<TGuardMap>,\n DoNotInfer<TDelayMap>\n >\n): typeof config {\n return config;\n}\n","import { listenerLogic } from '../actors/listener.ts';\nimport { subscriptionLogic } from '../actors/subscription.ts';\nimport type {\n ActorOptions,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n LogicalTimer,\n Snapshot\n} from '../types.ts';\n\ntype ChildUpdate =\n | { type: 'add'; actor: AnyActor; id: string; prefix?: string; next?: number }\n | { type: 'remove'; actor: AnyActor };\n\nexport type FSMEffect = ExecutableActionObject & {\n childUpdate?: ChildUpdate;\n};\n\ntype Allocation = {\n ids: Set<string>;\n counters: Record<string, number>;\n};\n\nconst allocations = new WeakMap<object, Allocation>();\n\nexport function beginFSMEffects(\n scope: ActorScope<any, any, any, any>,\n snapshot: {\n children: Record<string, AnyActor>;\n _nextActorIds?: Record<string, number>;\n }\n) {\n allocations.set(scope, {\n ids: new Set(Object.keys(snapshot.children)),\n counters: { ...snapshot._nextActorIds }\n });\n}\n\nfunction execute(\n this: any,\n runtime = this.source?.system ?? this.actor?.system\n) {\n switch (this.type) {\n case '@xstate.spawn':\n return runtime.spawnActor(this.source, this.actor);\n case '@xstate.start':\n return runtime.startActor(this.actor);\n case '@xstate.stop':\n return runtime.stopActor(this.actor);\n case '@xstate.terminate':\n return runtime.terminateActor(this.actor, this);\n case '@xstate.raise':\n case '@xstate.sendTo': {\n if (this.delay === undefined) {\n return runtime.sendEvent(this.source, this.target, this.event);\n }\n const timer = this.source.getSnapshot().timers[this.id];\n if (timer && !runtime._clock.now) {\n timer.startedAt = Date.now();\n }\n return runtime.scheduleTimer(this.source, this.id, this.delay);\n }\n case '@xstate.cancel':\n return runtime.cancelTimer(this.source, this.id);\n case '@xstate.emit':\n return runtime.emitEvent(this.source, this.event);\n default:\n return this.action?.(...this.args);\n }\n}\n\nfunction effect(type: string, fields: object = {}): FSMEffect {\n return {\n kind: 'builtin',\n type,\n params: undefined,\n args: [],\n exec: execute,\n ...fields\n } as unknown as FSMEffect;\n}\n\nexport function createFSMEnqueue<TEvent extends EventObject>(\n scope: ActorScope<any, any, any, any>,\n effects: FSMEffect[],\n internalEvents: EventObject[]\n): EnqueueObject<TEvent, EventObject> {\n const enqueue = ((action: (...args: any[]) => any, ...args: any[]) => {\n effects.push(\n effect(action.name || '(anonymous)', {\n kind: 'action',\n action,\n args\n })\n );\n }) as EnqueueObject<TEvent, EventObject>;\n\n enqueue.cancel = (id) => {\n effects.push(effect('@xstate.cancel', { source: scope.self, id }));\n };\n enqueue.emit = (event) => {\n effects.push(\n effect('@xstate.emit', {\n kind: 'emit',\n type: '@xstate.emit',\n source: scope.self,\n event\n })\n );\n };\n enqueue.log = (...args) => {\n enqueue(scope.logger, ...args);\n };\n enqueue.raise = (event, options) => {\n if (typeof event === 'string') {\n throw new Error('Only event objects may be used with raise');\n }\n if (options?.delay === undefined) {\n internalEvents.push(event);\n } else {\n effects.push(\n effect('@xstate.raise', {\n source: scope.self,\n event,\n id: options.id,\n delay: options.delay\n })\n );\n }\n };\n enqueue.sendTo = (target, event, options) => {\n if (!target) {\n internalEvents.push({\n type: 'xstate.error.communication',\n error: { message: 'Unable to send event to an undefined actor', event }\n } as EventObject);\n return;\n }\n effects.push(\n effect('@xstate.sendTo', {\n source: scope.self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n })\n );\n };\n\n const spawn = (\n logic: string | AnyActorLogic,\n options: ActorOptions<any> = {}\n ) => {\n if (typeof logic === 'string') {\n throw new Error(`Actor source \"${logic}\" not found`);\n }\n const allocation = allocations.get(scope)!;\n let id = options.id;\n let prefix: string | undefined;\n let next: number | undefined;\n if (id === undefined) {\n prefix = (logic as { id?: string }).id ?? 'x';\n if (prefix === '(machine)') {\n prefix = 'x';\n }\n next = allocation.counters[prefix] ?? 0;\n do {\n id = `${prefix}:${next++}`;\n } while (allocation.ids.has(id));\n allocation.counters[prefix] = next;\n }\n if (allocation.ids.has(id)) {\n throw new Error(`Actor with id \"${id}\" already exists`);\n }\n allocation.ids.add(id);\n const actor = scope.system.createActorRef(logic, {\n ...options,\n id,\n parent: scope.self\n });\n effects.push(\n effect('@xstate.spawn', {\n source: scope.self,\n actor,\n id,\n logic,\n src: logic,\n input: options.input,\n childUpdate: { type: 'add', actor, id, prefix, next }\n })\n );\n return actor;\n };\n enqueue.spawn = spawn as EnqueueObject<TEvent, EventObject>['spawn'];\n enqueue.stop = (actor) => {\n if (actor) {\n allocations.get(scope)?.ids.delete((actor as AnyActor).id);\n effects.push(\n effect('@xstate.stop', {\n source: scope.self,\n actor,\n id: (actor as AnyActor).id,\n childUpdate: { type: 'remove', actor: actor as AnyActor }\n })\n );\n }\n };\n\n const attach = (logic: AnyActorLogic, input: unknown) => {\n const actor = scope.system.createActorRef(logic, {\n input,\n parent: scope.self\n });\n effects.push(\n effect('@xstate.spawn', {\n source: scope.self,\n actor,\n id: actor.id,\n logic,\n src: logic,\n input\n })\n );\n return actor;\n };\n enqueue.listen = (actor: any, eventType: string, mapper: any) =>\n attach(listenerLogic, { actor, eventType, mapper });\n enqueue.subscribeTo = (actor: any, mappers: any) =>\n attach(subscriptionLogic, {\n actor,\n mappers: typeof mappers === 'function' ? { snapshot: mappers } : mappers\n });\n\n return enqueue;\n}\n\nexport function resolveFSMEffects<\n TSnapshot extends Snapshot<unknown> & {\n children: Record<string, AnyActor>;\n timers: Record<string, LogicalTimer>;\n _nextTimerId: number;\n _nextActorIds?: Record<string, number>;\n }\n>(\n snapshot: TSnapshot,\n effects: FSMEffect[],\n scope: ActorScope<any, any, any, any>\n): [TSnapshot, ExecutableActionObject[]] {\n let nextSnapshot = snapshot;\n for (const current of effects) {\n const update = current.childUpdate;\n if (update?.type === 'add') {\n nextSnapshot = {\n ...nextSnapshot,\n children: { ...nextSnapshot.children, [update.id]: update.actor },\n ...(update.prefix && {\n _nextActorIds: {\n ...nextSnapshot._nextActorIds,\n [update.prefix]: Math.max(\n nextSnapshot._nextActorIds?.[update.prefix] ?? 0,\n update.next!\n )\n }\n })\n };\n } else if (update?.type === 'remove') {\n const children = { ...nextSnapshot.children };\n let owned = update.actor._parent === scope.self;\n for (const id of Object.keys(children)) {\n if (children[id] === update.actor) {\n owned = true;\n delete children[id];\n }\n }\n if (!owned) {\n throw new Error(`Cannot stop non-child actor ${update.actor.id}`);\n }\n nextSnapshot = { ...nextSnapshot, children };\n }\n\n if (current.type === '@xstate.cancel') {\n if (nextSnapshot.timers[(current as any).id]) {\n const timers = { ...nextSnapshot.timers };\n delete timers[(current as any).id];\n nextSnapshot = { ...nextSnapshot, timers };\n }\n } else if (\n (current.type === '@xstate.raise' || current.type === '@xstate.sendTo') &&\n (current as any).delay !== undefined\n ) {\n const timer = current as any;\n const generated = timer.id === undefined;\n const id = timer.id ?? `xstate.timer.auto.${nextSnapshot._nextTimerId}`;\n timer.id = id;\n nextSnapshot = {\n ...nextSnapshot,\n timers: {\n ...nextSnapshot.timers,\n [id]: {\n id,\n delay: timer.delay,\n type: timer.type,\n event: timer.event,\n target:\n timer.type === '@xstate.raise' || timer.target === scope.self\n ? 'self'\n : timer.target\n }\n },\n _nextTimerId: generated\n ? nextSnapshot._nextTimerId + 1\n : nextSnapshot._nextTimerId\n };\n }\n }\n return [nextSnapshot, effects];\n}\n\nexport function appendFSMStarts(effects: ExecutableActionObject[]) {\n const ordered: ExecutableActionObject[] = [];\n const attached: ExecutableActionObject[] = [];\n const children: ExecutableActionObject[] = [];\n for (const current of effects as FSMEffect[]) {\n if (current.type === '@xstate.stop') {\n for (const starts of [attached, children]) {\n const index = starts.findIndex(\n (start) => (start as any).actor === (current as any).actor\n );\n if (index !== -1) {\n ordered.push(starts.splice(index, 1)[0]);\n }\n }\n }\n ordered.push(current);\n if (current.type !== '@xstate.spawn') {\n continue;\n }\n const start = effect('@xstate.start', {\n actor: (current as any).actor,\n id: (current as any).id,\n source: (current as any).source\n });\n ((current as any).logic === listenerLogic ||\n (current as any).logic === subscriptionLogic\n ? attached\n : children\n ).push(start);\n }\n return ordered.concat(attached, children);\n}\n\nexport function createFSMSendEffect(\n scope: ActorScope<any, any, any, any>,\n target: AnyActor,\n event: EventObject\n) {\n return effect('@xstate.sendTo', {\n source: scope.self,\n target,\n event\n });\n}\n\nexport function finalizeFSMEffects<TSnapshot extends Snapshot<unknown>>(\n scope: ActorScope<any, any, any, any>,\n previous: TSnapshot | undefined,\n result: [TSnapshot, ExecutableActionObject[]]\n): [TSnapshot, ExecutableActionObject[]] {\n const [snapshot, effects] = result;\n if (\n (snapshot.status === 'done' || snapshot.status === 'error') &&\n previous?.status !== 'done' &&\n previous?.status !== 'error'\n ) {\n effects.push(\n effect('@xstate.terminate', {\n source: scope.self,\n actor: scope.self,\n id: scope.self.id,\n status: snapshot.status,\n output: snapshot.output,\n error: snapshot.error\n })\n );\n }\n return [snapshot, effects];\n}\n","import { XSTATE_INIT, XSTATE_STOP, XSTATE_TIMER } from './constants.ts';\nimport {\n appendFSMStarts,\n beginFSMEffects,\n createFSMEnqueue,\n createFSMSendEffect,\n finalizeFSMEffects,\n resolveFSMEffects,\n type FSMEffect\n} from './fsm/effects.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport type {\n ActorLogic,\n ActorScope,\n AnyActor,\n AnyActorScope,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n LogicalTimer,\n NonReducibleUnknown,\n Snapshot\n} from './types.ts';\n\nexport type FSMSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput = unknown\n> = Snapshot<undefined> & {\n value: TState;\n context: TContext;\n input: TInput | undefined;\n children: {};\n timers: Record<string, LogicalTimer>;\n _nextTimerId: number;\n _nextActorIds?: Record<string, number>;\n _stateInput: Record<string, unknown> | undefined;\n machine: {\n id: string;\n sources: {\n actions: {};\n actors: {};\n guards: {};\n delays: {};\n };\n };\n};\n\ntype FSMArgs<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = {\n context: TContext;\n event: TEvent;\n input: TInput | undefined;\n value: TState;\n self: any;\n system: any;\n parent: any;\n children: {};\n};\n\ntype FSMAction<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (\n args: FSMArgs<TContext, TEvent, TState, TInput> & {\n input: Record<string, unknown> | undefined;\n },\n enq: EnqueueObject<TEvent, EventObject>\n) => void | { context?: FSMContextPatch<TContext> };\n\ntype FSMGuard<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (args: FSMArgs<TContext, TEvent, TState, TInput>) => boolean;\n\ntype FSMContextPatch<TContext extends MachineContext> = Partial<TContext> & {\n call?: never;\n apply?: never;\n bind?: never;\n};\n\ntype FSMContextMapper<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (\n args: FSMArgs<TContext, TEvent, TState, TInput>\n) => FSMContextPatch<TContext>;\n\ntype FSMTarget<TContext extends MachineContext> = {\n target?: string;\n context?: FSMContextPatch<TContext>;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: TContext;\n event: EventObject;\n }) => Record<string, unknown>);\n};\n\ntype FSMObjectTarget<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = Omit<FSMTarget<TContext>, 'context'> & {\n context?:\n | FSMContextPatch<TContext>\n | FSMContextMapper<TContext, TEvent, TState, TInput>;\n};\n\ntype FSMTransitionFunction<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = (\n args: FSMArgs<TContext, TEvent, TState, TInput>,\n enq: EnqueueObject<TEvent, EventObject>\n) => void | false | FSMTarget<TContext>;\n\ntype FSMTransition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> =\n | FSMObjectTarget<TContext, TEvent, TState, TInput>\n | (FSMObjectTarget<TContext, TEvent, TState, TInput> & {\n guard?: FSMGuard<TContext, TEvent, TState, TInput>;\n actions?:\n | FSMAction<TContext, TEvent, TState, TInput>\n | Array<FSMAction<TContext, TEvent, TState, TInput>>;\n })\n | FSMTransitionFunction<TContext, TEvent, TState, TInput>;\n\ntype FSMStateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = {\n type?: 'final';\n entry?:\n | FSMAction<TContext, TEvent, TState, TInput>\n | Array<FSMAction<TContext, TEvent, TState, TInput>>;\n exit?:\n | FSMAction<TContext, TEvent, TState, TInput>\n | Array<FSMAction<TContext, TEvent, TState, TInput>>;\n always?:\n | FSMTransition<TContext, TEvent, TState, TInput>\n | Array<FSMTransition<TContext, TEvent, TState, TInput>>;\n on?: Record<\n string,\n | FSMTransition<TContext, TEvent, TState, TInput>\n | Array<FSMTransition<TContext, TEvent, TState, TInput>>\n >;\n};\n\nexport type FSMConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput = NonReducibleUnknown\n> = {\n id?: string;\n initial: TState;\n context?: TContext | ((args: { input: TInput }) => TContext);\n states: Record<TState, FSMStateConfig<TContext, TEvent, TState, TInput>>;\n};\n\nexport type FSMActorLogic<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n> = ActorLogic<\n FSMSnapshot<TContext, TState, TInput>,\n TEvent,\n TInput,\n any,\n EventObject\n> & {\n id?: string;\n};\n\nconst emptySources = {\n actions: {},\n actors: {},\n guards: {},\n delays: {}\n};\n\nconst emptyExecutableActions: ExecutableActionObject[] = [];\nconst emptyFSMActions: FSMAction<any, any, any, any>[] = [];\n\nfunction assertPersistableFSM(\n children: Record<string, unknown>,\n timers: Record<string, LogicalTimer>\n) {\n if (Object.keys(children).length) {\n throw new Error('FSM child persistence requires registered sources.');\n }\n for (const id in timers) {\n if (timers[id].target !== 'self') {\n throw new Error(`FSM timer '${id}' must target self to be persisted.`);\n }\n }\n}\n\nfunction toArray<T>(value: T | T[] | undefined): T[] {\n return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\nfunction resolveContext<TContext extends MachineContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext) | undefined,\n input: TInput\n): TContext {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : (context ?? ({} as TContext));\n}\n\nfunction resolveTransitionContext<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TInput\n>(\n context:\n | FSMContextPatch<TContext>\n | FSMContextMapper<TContext, TEvent, TState, TInput>\n | undefined,\n args: FSMArgs<TContext, TEvent, TState, TInput>\n): FSMContextPatch<TContext> | undefined {\n return typeof context === 'function' ? context(args) : context;\n}\n\nfunction resolveInput(\n input: FSMTarget<any>['input'],\n context: MachineContext,\n event: EventObject\n) {\n return typeof input === 'function' ? input({ context, event }) : input;\n}\n\nfunction mergeContextPatch<TContext extends MachineContext>(\n context: TContext,\n patch: FSMContextPatch<TContext>\n): TContext {\n for (const key of Object.keys(patch) as Array<keyof TContext>) {\n if (\n !Object.prototype.hasOwnProperty.call(context, key) ||\n !Object.is(context[key], patch[key])\n ) {\n return { ...context, ...patch };\n }\n }\n\n return context;\n}\n\nfunction createSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput\n>(\n value: TState,\n context: TContext,\n input: TInput | undefined,\n machine: FSMSnapshot<TContext, TState, TInput>['machine'],\n stateInput?: Record<string, unknown>\n): FSMSnapshot<TContext, TState, TInput> {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n value,\n context,\n input,\n children: {},\n timers: {},\n _nextTimerId: 0,\n _stateInput: stateInput,\n machine\n };\n}\n\nfunction cloneSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput\n>(\n snapshot: FSMSnapshot<TContext, TState, TInput>,\n value: TState,\n context: TContext,\n stateInput: Record<string, unknown> | undefined\n): FSMSnapshot<TContext, TState, TInput> {\n return {\n status: snapshot.status,\n output: snapshot.output,\n error: snapshot.error,\n value,\n context,\n input: snapshot.input,\n children: snapshot.children,\n timers: snapshot.timers,\n _nextTimerId: snapshot._nextTimerId,\n // Carried across state changes: dropping these would let a later spawn\n // reuse the id of a still-running child.\n _nextActorIds: snapshot._nextActorIds,\n _stateInput: stateInput,\n machine: snapshot.machine\n } as FSMSnapshot<TContext, TState, TInput>;\n}\n\nfunction stopSnapshot<\n TContext extends MachineContext,\n TState extends string,\n TInput\n>(\n snapshot: FSMSnapshot<TContext, TState, TInput>\n): FSMSnapshot<TContext, TState, TInput> {\n return {\n status: 'stopped',\n output: undefined,\n error: undefined,\n value: snapshot.value,\n context: snapshot.context,\n input: undefined,\n children: snapshot.children,\n timers: snapshot.timers,\n _nextTimerId: snapshot._nextTimerId,\n _nextActorIds: snapshot._nextActorIds,\n _stateInput: snapshot._stateInput,\n machine: snapshot.machine\n } as FSMSnapshot<TContext, TState, TInput>;\n}\n\nfunction cleanupFSM(\n snapshot: FSMSnapshot<any, string, any>,\n actorScope: AnyActorScope\n): [FSMSnapshot<any, string, any>, ExecutableActionObject[]] {\n const effects: FSMEffect[] = [];\n const enqueue = createFSMEnqueue(actorScope, effects, []);\n for (const child of Object.values(snapshot.children) as AnyActor[]) {\n enqueue.stop(child);\n }\n for (const id of Object.keys(snapshot.timers)) {\n enqueue.cancel(id);\n }\n return resolveFSMEffects(snapshot, effects, actorScope);\n}\n\nfunction completeFinalState(\n snapshot: FSMSnapshot<any, string, any>,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: EventObject[],\n states: Record<string, FSMStateConfig<any, any, string, any>>,\n runStateActions: (\n snapshot: FSMSnapshot<any, string, any>,\n event: EventObject,\n actorScope: AnyActorScope,\n actions: FSMStateConfig<any, any, string, any>['entry'],\n input: Record<string, unknown> | undefined,\n queue: EventObject[]\n ) => [FSMSnapshot<any, string, any>, ExecutableActionObject[]]\n): [FSMSnapshot<any, string, any>, ExecutableActionObject[]] {\n const completed = {\n ...snapshot,\n status: 'done',\n output: undefined,\n error: undefined\n } as FSMSnapshot<any, string, any>;\n const [exited, exitEffects] = runStateActions(\n completed,\n event,\n actorScope,\n states[completed.value]?.exit,\n completed._stateInput,\n internalQueue\n );\n const [cleaned, cleanupEffects] = cleanupFSM(exited, actorScope);\n return [cleaned, [...exitEffects, ...cleanupEffects]];\n}\n\nfunction invalidStringTarget(path: string, target: string): never {\n throw new Error(\n `Invalid transition for \"${path}\": use { target: \"${target}\" } instead of a string target.`\n );\n}\n\nfunction assertNoStringTransitions(\n config: FSMConfig<any, any, string, any>\n): void {\n for (const [stateKey, stateConfig] of Object.entries(config.states)) {\n for (const [eventType, transitionConfig] of Object.entries(\n stateConfig.on ?? {}\n )) {\n for (const transition of toArray(transitionConfig)) {\n if (typeof transition === 'string') {\n invalidStringTarget(`${stateKey}.${eventType}`, transition as string);\n }\n }\n }\n if (stateConfig.always) {\n for (const transition of toArray(stateConfig.always)) {\n if (typeof transition === 'string') {\n invalidStringTarget(`${stateKey}.always`, transition as string);\n }\n }\n }\n }\n}\n\nexport function createFSM<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n>(\n config: FSMConfig<TContext, TEvent, string, TInput>\n): FSMActorLogic<TContext, TEvent, string, TInput> {\n const machine = {\n id: config.id ?? '(fsm)',\n sources: emptySources\n };\n assertNoStringTransitions(config);\n\n const runActions = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: EventObject,\n actorScope: AnyActorScope,\n actionsConfig:\n | FSMAction<TContext, TEvent, string, TInput>\n | Array<FSMAction<TContext, TEvent, string, TInput>>\n | undefined,\n internalQueue: EventObject[]\n ): [FSMSnapshot<TContext, string, TInput>, ExecutableActionObject[]] => {\n if (!actionsConfig) {\n return [snapshot, emptyExecutableActions];\n }\n const effects: FSMEffect[] = [];\n const enqueue = createFSMEnqueue<TEvent>(\n actorScope,\n effects,\n internalQueue\n );\n let context = snapshot.context;\n for (const action of toArray(actionsConfig)) {\n const result = action(\n withActorScope(\n {\n context,\n event: event as TEvent,\n input: snapshot._stateInput,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n ) as any,\n enqueue\n );\n if (result?.context) {\n context = mergeContextPatch(context, result.context);\n }\n }\n return resolveFSMEffects(\n context === snapshot.context\n ? snapshot\n : cloneSnapshot(\n snapshot,\n snapshot.value,\n context,\n snapshot._stateInput\n ),\n effects,\n actorScope\n ) as any;\n };\n\n const runStateActions = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: EventObject,\n actorScope: AnyActorScope,\n actionsConfig: FSMStateConfig<TContext, TEvent, string, TInput>['entry'],\n stateInput: Record<string, unknown> | undefined,\n internalQueue: EventObject[]\n ): [FSMSnapshot<TContext, string, TInput>, ExecutableActionObject[]] => {\n if (!actionsConfig) {\n return [snapshot, emptyExecutableActions];\n }\n\n const actions: FSMEffect[] = [];\n const enq = createFSMEnqueue<TEvent>(actorScope, actions, internalQueue);\n let context: TContext | undefined;\n const actionCount = Array.isArray(actionsConfig) ? actionsConfig.length : 1;\n\n for (let i = 0; i < actionCount; i++) {\n const action = Array.isArray(actionsConfig)\n ? actionsConfig[i]\n : actionsConfig;\n const result = action(\n withActorScope(\n {\n context: context ?? snapshot.context,\n event: event as TEvent,\n input: stateInput as any,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n ),\n enq\n );\n if (result?.context !== undefined) {\n const currentContext = context ?? snapshot.context;\n const nextContext = mergeContextPatch(currentContext, result.context);\n if (nextContext !== currentContext) {\n context = nextContext;\n }\n }\n }\n\n const nextSnapshot =\n context !== undefined\n ? cloneSnapshot(snapshot, snapshot.value, context, snapshot._stateInput)\n : snapshot;\n return resolveFSMEffects(nextSnapshot, actions, actorScope) as any;\n };\n\n const selectTransition = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: TEvent,\n actorScope: AnyActorScope,\n internalQueue: EventObject[]\n ) => {\n const state = config.states[snapshot.value];\n const transitionsConfig:\n | FSMTransition<TContext, TEvent, string, TInput>\n | Array<FSMTransition<TContext, TEvent, string, TInput>>\n | undefined = event.type === '' ? state?.always : state?.on?.[event.type];\n\n if (!transitionsConfig) {\n return undefined;\n }\n\n const transitionCount = Array.isArray(transitionsConfig)\n ? transitionsConfig.length\n : 1;\n\n for (let i = 0; i < transitionCount; i++) {\n const transition = Array.isArray(transitionsConfig)\n ? transitionsConfig[i]\n : transitionsConfig;\n const args = withActorScope(\n {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n );\n\n if (typeof transition === 'function') {\n const actions: FSMEffect[] = [];\n const enq = createFSMEnqueue<TEvent>(\n actorScope,\n actions,\n internalQueue\n );\n const result = transition(args, enq);\n if (!result) {\n if (actions.length) {\n return { effects: actions };\n }\n continue;\n }\n return {\n target: result.target,\n context: result.context,\n input: result.input,\n effects: actions\n };\n }\n\n if (\n 'guard' in transition &&\n transition.guard &&\n !transition.guard(args)\n ) {\n continue;\n }\n\n return {\n target: transition.target,\n context: resolveTransitionContext(transition.context, args),\n input: transition.input,\n actions:\n 'actions' in transition && transition.actions\n ? toArray(transition.actions as any)\n : emptyFSMActions\n };\n }\n\n return undefined;\n };\n\n const transitionCore = (\n snapshot: FSMSnapshot<TContext, string, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n FSMSnapshot<TContext, string, TInput>,\n TEvent,\n any,\n EventObject\n >\n ): [FSMSnapshot<TContext, string, TInput>, ExecutableActionObject[]] => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n if (event.type === XSTATE_STOP) {\n const [cleaned, cleanupEffects] = cleanupFSM(snapshot, actorScope);\n return [stopSnapshot(cleaned), cleanupEffects] as any;\n }\n if (event.type === XSTATE_TIMER) {\n const timer = snapshot.timers[(event as any).id];\n if (!timer) {\n return [snapshot, emptyExecutableActions];\n }\n const timers = { ...snapshot.timers };\n delete timers[timer.id];\n const nextSnapshot = { ...snapshot, timers };\n if (timer.type === '@xstate.raise') {\n return transitionCore(nextSnapshot, timer.event as TEvent, actorScope);\n }\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n return [\n nextSnapshot,\n [createFSMSendEffect(actorScope, target, timer.event)]\n ];\n }\n\n const stateConfig = config.states[snapshot.value];\n const directTransition =\n event.type === '' ? stateConfig?.always : stateConfig?.on?.[event.type];\n if (!directTransition) {\n return [snapshot, emptyExecutableActions];\n }\n\n if (\n !Array.isArray(directTransition) &&\n typeof directTransition !== 'function' &&\n !('guard' in directTransition) &&\n !('actions' in directTransition && directTransition.actions) &&\n typeof directTransition.input !== 'function'\n ) {\n const target = directTransition.target ?? snapshot.value;\n const targetState = config.states[target];\n const stateChanged = target !== snapshot.value;\n if (\n targetState?.always ||\n (stateChanged &&\n (stateConfig.exit ||\n targetState?.entry ||\n targetState?.type === 'final'))\n ) {\n // Exit/entry actions need the general path.\n } else {\n const hasContext = directTransition.context !== undefined;\n const hasInput = directTransition.input !== undefined;\n const resolvedContext = !isLazyActorScope(actorScope)\n ? resolveTransitionContext(directTransition.context, {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: snapshot.children\n })\n : typeof directTransition.context === 'function'\n ? directTransition.context(\n withActorScope(\n {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n )\n )\n : directTransition.context;\n const context =\n hasContext && resolvedContext\n ? mergeContextPatch(snapshot.context, resolvedContext)\n : snapshot.context;\n if (\n !stateChanged &&\n context === snapshot.context &&\n !hasInput &&\n snapshot._stateInput === undefined\n ) {\n return [snapshot, emptyExecutableActions];\n }\n return [\n cloneSnapshot(\n snapshot,\n target,\n context,\n hasInput\n ? resolveInput(directTransition.input, context, event)\n : undefined\n ),\n emptyExecutableActions\n ];\n }\n }\n let selectedTransition:\n | Exclude<ReturnType<typeof selectTransition>, undefined>\n | undefined;\n if (\n typeof directTransition === 'function' &&\n directTransition.length < 2 &&\n !stateConfig?.exit\n ) {\n const result = directTransition(\n withActorScope(\n {\n context: snapshot.context,\n event,\n input: snapshot.input,\n value: snapshot.value,\n children: snapshot.children\n },\n actorScope\n ),\n undefined as any\n );\n if (!result) {\n return [snapshot, emptyExecutableActions];\n }\n const target = result.target ?? snapshot.value;\n const targetState = config.states[target];\n if (\n !targetState?.entry &&\n !targetState?.always &&\n targetState?.type !== 'final'\n ) {\n const hasContext = result.context !== undefined;\n const hasInput = result.input !== undefined;\n const context =\n hasContext && result.context\n ? mergeContextPatch(snapshot.context, result.context)\n : snapshot.context;\n if (\n target === snapshot.value &&\n context === snapshot.context &&\n !hasInput &&\n snapshot._stateInput === undefined\n ) {\n return [snapshot, emptyExecutableActions];\n }\n return [\n cloneSnapshot(\n snapshot,\n target,\n context,\n hasInput ? resolveInput(result.input, context, event) : undefined\n ),\n emptyExecutableActions\n ];\n }\n selectedTransition = {\n target: result.target,\n context: result.context,\n input: result.input,\n actions: emptyFSMActions\n };\n }\n\n let nextSnapshot: FSMSnapshot<TContext, string, TInput> = snapshot;\n const executableActions: ExecutableActionObject[] = [];\n const internalQueue: EventObject[] = [event];\n let iterations = 0;\n\n while (internalQueue.length) {\n if (++iterations > 1000) {\n throw new Error('FSM microstep count exceeded 1000');\n }\n const nextEvent = internalQueue.shift() as TEvent;\n const selected =\n selectedTransition ??\n selectTransition(nextSnapshot, nextEvent, actorScope, internalQueue);\n selectedTransition = undefined;\n if (!selected) {\n continue;\n }\n\n const nextValue = selected.target ?? nextSnapshot.value;\n const nextState = config.states[nextValue];\n const stateChanged = nextValue !== nextSnapshot.value;\n\n if (stateChanged) {\n const [exited, exitActions] = runStateActions(\n nextSnapshot,\n nextEvent,\n actorScope,\n config.states[nextSnapshot.value]?.exit,\n nextSnapshot._stateInput,\n internalQueue\n );\n nextSnapshot = exited;\n executableActions.push(...exitActions);\n }\n\n let context = nextSnapshot.context;\n if (selected.context !== undefined) {\n context = mergeContextPatch(context, selected.context);\n }\n const hasInput = selected.input !== undefined;\n const stateInput = hasInput\n ? resolveInput(selected.input, context, nextEvent)\n : undefined;\n if (\n stateChanged ||\n context !== nextSnapshot.context ||\n hasInput ||\n nextSnapshot._stateInput !== undefined\n ) {\n nextSnapshot = cloneSnapshot(\n nextSnapshot,\n nextValue,\n context,\n stateInput\n );\n }\n\n const transitionResult: [\n FSMSnapshot<TContext, string, TInput>,\n ExecutableActionObject[]\n ] = selected.effects\n ? resolveFSMEffects(nextSnapshot, selected.effects, actorScope)\n : runActions(\n nextSnapshot,\n nextEvent,\n actorScope,\n selected.actions,\n internalQueue\n );\n const [afterTransition, transitionActions] = transitionResult;\n nextSnapshot = afterTransition;\n executableActions.push(...transitionActions);\n\n if (stateChanged) {\n const [entered, entryActions] = runStateActions(\n nextSnapshot,\n nextEvent,\n actorScope,\n nextState?.entry,\n stateInput,\n internalQueue\n );\n nextSnapshot = entered;\n executableActions.push(...entryActions);\n }\n\n if (nextState?.type === 'final') {\n const [completed, completionEffects] = completeFinalState(\n nextSnapshot,\n nextEvent,\n actorScope,\n internalQueue,\n config.states,\n runStateActions as any\n );\n nextSnapshot = completed;\n executableActions.push(...completionEffects);\n break;\n }\n if (nextState?.always) {\n internalQueue.unshift({ type: '' });\n }\n }\n\n return [nextSnapshot, executableActions];\n };\n\n const transition = ((...args: Parameters<typeof transitionCore>) => {\n beginFSMEffects(args[2], args[0]);\n const [nextSnapshot, effects] = transitionCore(...args);\n return finalizeFSMEffects(args[2], args[0], [\n nextSnapshot,\n appendFSMStarts(effects)\n ]);\n }) as FSMActorLogic<TContext, TEvent, string, TInput>['transition'];\n\n const logic: FSMActorLogic<TContext, TEvent, string, TInput> = {\n id: config.id,\n config,\n transition,\n initialTransition: (input, actorScope) => {\n const initialState = config.states[config.initial];\n const context = resolveContext(config.context, input);\n const snapshot = createSnapshot(\n config.initial,\n context,\n input,\n machine as any\n );\n beginFSMEffects(actorScope, snapshot);\n const internalQueue: EventObject[] = [];\n let [nextSnapshot, actions] = runStateActions(\n snapshot,\n { type: XSTATE_INIT },\n actorScope,\n initialState?.entry,\n undefined,\n internalQueue\n );\n if (!actions.length) {\n actions = [];\n }\n if (initialState?.type === 'final') {\n const [completed, completionEffects] = completeFinalState(\n nextSnapshot,\n { type: XSTATE_INIT },\n actorScope,\n internalQueue,\n config.states,\n runStateActions as any\n );\n nextSnapshot = completed;\n actions.push(...completionEffects);\n } else {\n if (initialState?.always) {\n internalQueue.unshift({ type: '' });\n }\n while (internalQueue.length) {\n const [raisedSnapshot, raisedActions] = transitionCore(\n nextSnapshot,\n internalQueue.shift()! as TEvent,\n actorScope\n );\n nextSnapshot = raisedSnapshot;\n actions.push(...raisedActions);\n }\n }\n return finalizeFSMEffects(actorScope, undefined, [\n nextSnapshot,\n appendFSMStarts(actions)\n ]);\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (currentSnapshot) => {\n const { machine: _, children, ...snapshot } = currentSnapshot;\n assertPersistableFSM(children, snapshot.timers);\n return { ...snapshot, children: {} };\n },\n restoreSnapshot: (snapshot) => {\n const persisted = snapshot as FSMSnapshot<TContext, string, TInput>;\n const children = persisted.children ?? {};\n const timers = persisted.timers ?? {};\n assertPersistableFSM(children, timers);\n const restored = {\n ...persisted,\n children: {},\n timers,\n machine: machine as any\n };\n return restored;\n }\n };\n\n return logic;\n}\n","import {\n Action,\n AnyActorLogic,\n AnyEventObject,\n AnyStateMachine,\n EventObject,\n MachineContext,\n MetaObject\n} from './types';\nimport { createMachine } from './createMachine';\nimport { parseDelayToMilliseconds } from './delay';\n\nfunction delayToMs(delay: string | number): number {\n const parsedDelay = parseDelayToMilliseconds(delay);\n if (parsedDelay !== undefined) return parsedDelay;\n return typeof delay === 'string' ? parseFloat(delay) || 0 : delay;\n}\n\ninterface RaiseJSON {\n type: '@xstate.raise';\n event: EventObject;\n id?: string;\n delay?: number;\n}\n\ninterface CancelJSON {\n type: '@xstate.cancel';\n id: string;\n}\n\ninterface LogJSON {\n type: '@xstate.log';\n args: any[];\n}\n\ninterface EmitJSON {\n type: '@xstate.emit';\n event: AnyEventObject;\n}\n\ninterface AssignJSON {\n type: '@xstate.assign';\n context: MachineContext;\n}\n\ntype BuiltInActionJSON =\n | RaiseJSON\n | CancelJSON\n | LogJSON\n | EmitJSON\n | AssignJSON;\n\ninterface CustomActionJSON {\n type: string;\n params?: unknown;\n}\n\nexport type ActionJSON =\n | CustomActionJSON\n | BuiltInActionJSON\n | ExpressionJSON\n | CodeJSON;\n\nexport interface GuardJSON {\n type: string;\n params?: unknown;\n}\n\ninterface ExpressionJSON {\n '@expr': string;\n '@lang'?: string;\n}\n\ninterface CodeJSON {\n '@code': string;\n '@lang'?: string;\n}\n\ntype ResolvableJSON = ExpressionJSON | CodeJSON;\ntype ConditionJSON = GuardJSON | ResolvableJSON;\n\ninterface ChoiceBranchJSON {\n when?: ConditionJSON;\n target: string | string[];\n context?: MachineContext;\n input?: unknown;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n}\n\nexport interface InvokeJSON {\n id?: string;\n registryKey?: string;\n src: string;\n input?: unknown;\n onDone?: TransitionConfigJSON | TransitionConfigJSON[];\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n onSnapshot?: TransitionConfigJSON | TransitionConfigJSON[];\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n}\n\nexport interface TransitionJSON {\n target?: string | string[];\n matches?: Record<string, unknown>;\n context?: MachineContext;\n actions?: ActionJSON[];\n guard?: ConditionJSON;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n input?: unknown;\n}\n\ntype TransitionConfigJSON = TransitionJSON | ResolvableJSON;\n\nexport interface StateNodeJSON {\n id?: string;\n key?: string;\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history' | 'choice';\n initial?: string;\n states?: Record<string, StateNodeJSON>;\n on?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n after?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n always?: TransitionConfigJSON | TransitionConfigJSON[];\n choice?: ChoiceBranchJSON[] | ResolvableJSON;\n route?:\n | {\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n guard?: string;\n input?: Record<string, unknown>;\n }\n | ResolvableJSON;\n invoke?: InvokeJSON | InvokeJSON[];\n entry?: ActionJSON | ActionJSON[];\n exit?: ActionJSON | ActionJSON[];\n meta?: MetaObject;\n description?: string;\n tags?: string[];\n input?: unknown;\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n history?: 'shallow' | 'deep';\n target?: string | [string, ...string[]];\n output?: unknown;\n context?: Record<string, unknown>;\n}\n\nexport interface MachineJSON extends StateNodeJSON {\n '@exprLang'?: string;\n version?: string;\n actions?: Record<string, ActionJSON | ActionJSON[]>;\n guards?: Record<string, { when: ConditionJSON }>;\n actors?: Record<string, unknown>;\n delays?: Record<\n string,\n number | string | { duration: number | string | ResolvableJSON }\n >;\n schemas?: Record<string, unknown>;\n}\n\ntype EvaluatorSlot =\n | 'context'\n | 'guard'\n | 'choice'\n | 'action'\n | 'actionParams'\n | 'transition'\n | 'input'\n | 'output'\n | 'delay'\n | 'transitionContext'\n | 'unknown';\n\ntype EvaluatorKind = 'expr' | 'code';\n\ninterface EvaluatorArgs {\n source: string;\n kind: EvaluatorKind;\n slot: EvaluatorSlot;\n scope: Record<string, unknown>;\n path: string;\n}\n\ninterface MachineSources {\n actions?: Record<string, (...args: any[]) => unknown>;\n guards?: Record<string, (...args: any[]) => boolean>;\n actors?: Record<string, AnyActorLogic>;\n delays?: Record<string, number | ((...args: any[]) => number)>;\n evaluators?: Record<string, (args: EvaluatorArgs) => unknown>;\n}\n\ntype ProvidedSources = Required<MachineSources>;\n\nfunction isExpression(value: unknown): value is ExpressionJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@expr'] === 'string'\n );\n}\n\nfunction isCode(value: unknown): value is CodeJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@code'] === 'string'\n );\n}\n\nfunction isResolvable(value: unknown): value is ResolvableJSON {\n return isExpression(value) || isCode(value);\n}\n\nfunction isBuiltInActionType(type: string): boolean {\n return type.startsWith('@xstate.');\n}\n\nfunction toPath(parent: string, key: string | number): string {\n return typeof key === 'number' ? `${parent}[${key}]` : `${parent}.${key}`;\n}\n\nfunction extractSerializableDelays(\n delays: MachineJSON['delays'] | undefined\n): Record<string, number> {\n const result: Record<string, number> = {};\n if (!delays) {\n return result;\n }\n for (const key of Object.keys(delays)) {\n const value = delays[key];\n if (typeof value === 'number') {\n result[key] = value;\n } else if (\n value &&\n typeof value === 'object' &&\n typeof value.duration === 'number'\n ) {\n result[key] = value.duration;\n }\n }\n return result;\n}\n\nfunction mergeSources(\n json: MachineJSON,\n sources: MachineSources\n): ProvidedSources {\n return {\n actions: sources.actions ?? {},\n guards: sources.guards ?? {},\n actors: sources.actors ?? {},\n delays: {\n ...extractSerializableDelays(json.delays),\n ...(sources.delays ?? {})\n },\n evaluators: sources.evaluators ?? {}\n };\n}\n\ninterface ExpressionResolver {\n evaluateResolvable: (\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n resolveValue: (\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n makeScope: (\n x: any,\n extra?: Record<string, unknown>\n ) => Record<string, unknown>;\n getDurationConfig: (value: unknown, path: string) => unknown;\n assertResolvable: (value: unknown, path: string) => void;\n}\n\nfunction createExpressionResolver(\n expressionLanguage: string | undefined,\n sources: ProvidedSources\n): ExpressionResolver {\n function getEvaluator(value: ResolvableJSON, path: string) {\n const lang = value['@lang'] ?? expressionLanguage;\n if (!lang) {\n throw new Error(`Missing @exprLang for expression at ${path}`);\n }\n const evaluator = sources.evaluators[lang];\n if (!evaluator) {\n throw new Error(`Missing evaluator for @lang '${lang}' at ${path}`);\n }\n return evaluator;\n }\n\n function evaluateResolvable(\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) {\n const kind = isExpression(value) ? 'expr' : 'code';\n const source = isExpression(value) ? value['@expr'] : value['@code'];\n return getEvaluator(\n value,\n path\n )({\n source,\n kind,\n slot,\n scope,\n path\n });\n }\n\n function resolveValue(\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ): unknown {\n if (isResolvable(value)) {\n return evaluateResolvable(value, slot, scope, path);\n }\n if (Array.isArray(value)) {\n return value.map((item, index) =>\n resolveValue(item, slot, scope, toPath(path, index))\n );\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = resolveValue(\n (value as Record<string, unknown>)[key],\n slot,\n scope,\n toPath(path, key)\n );\n }\n return result;\n }\n\n function makeScope(x: any, extra?: Record<string, unknown>) {\n return {\n context: x.context,\n event: x.event,\n input: x.input,\n self: x.self,\n children: x.children,\n params: x.params,\n ...extra\n };\n }\n\n function getDurationConfig(value: unknown, path: string) {\n if (!isResolvable(value)) {\n return value;\n }\n return (args: any) =>\n delayToMs(\n resolveValue(value, 'delay', makeScope(args), path) as string | number\n );\n }\n\n function assertResolvable(value: unknown, path: string) {\n if (isResolvable(value)) {\n getEvaluator(value, path);\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertResolvable(item, toPath(path, index))\n );\n return;\n }\n if (!value || typeof value !== 'object') {\n return;\n }\n for (const key of Object.keys(value)) {\n assertResolvable(\n (value as Record<string, unknown>)[key],\n toPath(path, key)\n );\n }\n }\n\n return {\n evaluateResolvable,\n resolveValue,\n makeScope,\n getDurationConfig,\n assertResolvable\n };\n}\n\nfunction toActionArray(\n actions: ActionJSON | ActionJSON[] | undefined\n): ActionJSON[] {\n return actions === undefined\n ? []\n : Array.isArray(actions)\n ? actions\n : [actions];\n}\n\nfunction validateChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!Array.isArray(choice)) {\n return;\n }\n choice.forEach((branch, index) => {\n if (branch.when === undefined && index !== choice.length - 1) {\n throw new Error(\n `Choice fallback branch at ${path}[${index}] must be last.`\n );\n }\n });\n}\n\nfunction assertMachineJSON(\n json: MachineJSON,\n resolvedSources: ProvidedSources,\n expressionResolver: ExpressionResolver\n) {\n const { assertResolvable } = expressionResolver;\n\n function assertCondition(condition: ConditionJSON | undefined, path: string) {\n if (!condition) {\n return;\n }\n if (isResolvable(condition)) {\n assertResolvable(condition, path);\n return;\n }\n assertResolvable(condition.params, `${path}.params`);\n if (json.guards?.[condition.type]) {\n assertCondition(\n json.guards[condition.type].when,\n `$.guards.${condition.type}.when`\n );\n return;\n }\n if (\n !resolvedSources.guards[condition.type] &&\n !['xstate.stateIn', 'xstate.not'].includes(condition.type)\n ) {\n throw new Error(`Missing guard source \"${condition.type}\"`);\n }\n }\n\n function assertAction(\n action: ActionJSON,\n path: string,\n stack: string[] = []\n ) {\n if (isResolvable(action)) {\n assertResolvable(action, path);\n return;\n }\n if (!action || typeof action.type !== 'string') {\n throw new Error(`Invalid action at ${path}`);\n }\n assertResolvable((action as CustomActionJSON).params, `${path}.params`);\n if (isBuiltInActionType(action.type)) {\n assertResolvable(action, path);\n return;\n }\n const definition = json.actions?.[action.type];\n if (definition) {\n if (stack.includes(action.type)) {\n throw new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n );\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n definitions.forEach((item, index) =>\n assertAction(\n item,\n `${path}.actions.${action.type}${definitions.length > 1 ? `[${index}]` : ''}`,\n stack.concat(action.type)\n )\n );\n return;\n }\n if (!resolvedSources.actions[action.type]) {\n throw new Error(`Missing action source \"${action.type}\"`);\n }\n }\n\n function assertActions(\n actions: ActionJSON | ActionJSON[] | undefined,\n path: string\n ) {\n toActionArray(actions).forEach((action, index) =>\n assertAction(action, `${path}[${index}]`)\n );\n }\n\n function assertTransition(\n transition: TransitionConfigJSON | TransitionConfigJSON[] | undefined,\n path: string\n ) {\n const transitions = Array.isArray(transition)\n ? transition\n : transition\n ? [transition]\n : [];\n transitions.forEach((t, index) => {\n const transitionPath = Array.isArray(transition)\n ? `${path}[${index}]`\n : path;\n if (isResolvable(t)) {\n assertResolvable(t, transitionPath);\n return;\n }\n assertCondition(t.guard, `${transitionPath}.guard`);\n assertActions(t.actions, `${transitionPath}.actions`);\n assertResolvable(t.context, `${transitionPath}.context`);\n assertResolvable(t.input, `${transitionPath}.input`);\n });\n }\n\n function assertStateNode(node: StateNodeJSON, path: string) {\n if (\n (node.type === 'history' || node.history !== undefined) &&\n !(\n (typeof node.target === 'string' && node.target.trim().length > 0) ||\n (Array.isArray(node.target) &&\n node.target.length > 0 &&\n node.target.every((target) => target.trim().length > 0))\n )\n ) {\n throw new Error(\n `History state at ${path} must declare a non-empty target.`\n );\n }\n assertResolvable(node.context, `${path}.context`);\n assertResolvable(node.input, `${path}.input`);\n assertResolvable(node.output, `${path}.output`);\n assertResolvable(node.timeout, `${path}.timeout`);\n assertActions(node.entry, `${path}.entry`);\n assertActions(node.exit, `${path}.exit`);\n if (node.type === 'choice') {\n if (!node.choice) {\n throw new Error(`Choice state at ${path} must declare choice.`);\n }\n if (Array.isArray(node.choice)) {\n validateChoiceConfig(node.choice, `${path}.choice`);\n node.choice.forEach((branch, index) => {\n assertCondition(branch.when, `${path}.choice[${index}].when`);\n assertResolvable(branch.context, `${path}.choice[${index}].context`);\n assertResolvable(branch.input, `${path}.choice[${index}].input`);\n });\n } else {\n assertResolvable(node.choice, `${path}.choice`);\n }\n }\n if (isResolvable(node.route)) {\n assertResolvable(node.route, `${path}.route`);\n }\n if (node.invoke) {\n const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];\n invokes.forEach((invoke, index) => {\n const invokePath = `${path}.invoke${Array.isArray(node.invoke) ? `[${index}]` : ''}`;\n if (!resolvedSources.actors[invoke.src]) {\n throw new Error(`Missing actor source \"${invoke.src}\"`);\n }\n assertResolvable(invoke.input, `${invokePath}.input`);\n assertResolvable(invoke.timeout, `${invokePath}.timeout`);\n assertTransition(invoke.onDone, `${invokePath}.onDone`);\n assertTransition(invoke.onError, `${invokePath}.onError`);\n assertTransition(invoke.onSnapshot, `${invokePath}.onSnapshot`);\n assertTransition(invoke.onTimeout, `${invokePath}.onTimeout`);\n });\n }\n if (node.on) {\n for (const descriptor of Object.keys(node.on)) {\n assertTransition(node.on[descriptor], `${path}.on.${descriptor}`);\n }\n }\n if (node.after) {\n for (const delay of Object.keys(node.after)) {\n if (\n Number.isNaN(Number(delay)) &&\n parseDelayToMilliseconds(delay) === undefined &&\n !json.delays?.[delay] &&\n !resolvedSources.delays[delay]\n ) {\n throw new Error(`Missing delay source \"${delay}\"`);\n }\n assertTransition(node.after[delay], `${path}.after.${delay}`);\n }\n }\n assertTransition(node.always, `${path}.always`);\n assertTransition(node.onError, `${path}.onError`);\n assertTransition(node.onTimeout, `${path}.onTimeout`);\n if (node.states) {\n for (const key of Object.keys(node.states)) {\n assertStateNode(node.states[key], `${path}.states.${key}`);\n }\n }\n }\n\n if (json.actions) {\n for (const key of Object.keys(json.actions)) {\n const actions = Array.isArray(json.actions[key])\n ? json.actions[key]\n : [json.actions[key]];\n actions.forEach((action, index) =>\n assertAction(\n action,\n `$.actions.${key}${actions.length > 1 ? `[${index}]` : ''}`,\n [key]\n )\n );\n }\n }\n if (json.guards) {\n for (const key of Object.keys(json.guards)) {\n assertCondition(json.guards[key].when, `$.guards.${key}.when`);\n }\n }\n if (json.delays) {\n for (const key of Object.keys(json.delays)) {\n const delay = json.delays[key];\n assertResolvable(\n delay && typeof delay === 'object' && 'duration' in delay\n ? delay.duration\n : delay,\n `$.delays.${key}`\n );\n }\n }\n assertStateNode(json, '$');\n}\n\nexport function createMachineFromConfig(\n json: MachineJSON,\n sources: MachineSources = {}\n): AnyStateMachine {\n const resolvedSources = mergeSources(json, sources);\n const expressionResolver = createExpressionResolver(\n json['@exprLang'],\n resolvedSources\n );\n const { evaluateResolvable, resolveValue, makeScope, getDurationConfig } =\n expressionResolver;\n\n type ResolvedCondition = ((args: any) => boolean) | undefined;\n\n function resolveCondition(\n condition: ConditionJSON | undefined,\n slot: 'guard' | 'choice',\n path: string\n ): ResolvedCondition {\n if (!condition) return undefined;\n if (isResolvable(condition)) {\n return (args: any) =>\n !!evaluateResolvable(condition, slot, makeScope(args), path);\n }\n return (args: any) => {\n const params = resolveValue(\n condition.params,\n slot,\n makeScope(args),\n `${path}.params`\n );\n const declarativeGuard = json.guards?.[condition.type];\n if (declarativeGuard) {\n const guard = resolveCondition(\n declarativeGuard.when,\n 'guard',\n `$.guards.${condition.type}.when`\n );\n return !!guard?.({ ...args, params });\n }\n const guardImpl = args.guards?.[condition.type];\n if (!guardImpl) {\n throw new Error(\n getMissingGuardMessage(condition.type, args.guards ?? {})\n );\n }\n return guardImpl(args, params);\n };\n }\n\n function getMissingGuardMessage(type: string, guards: Record<string, any>) {\n return `Guard '${type}' is not implemented in machine '${json.id ?? '(machine)'}'. Available guards: ${\n Object.keys(guards)\n .map((key) => `'${key}'`)\n .join(', ') || '(none)'\n }.`;\n }\n\n function makeChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!choice) return undefined;\n if (isResolvable(choice)) {\n return (args: any) =>\n evaluateResolvable(choice, 'choice', makeScope(args), path);\n }\n validateChoiceConfig(choice, path);\n return (args: any) => {\n for (let index = 0; index < choice.length; index++) {\n const branch = choice[index];\n const guard = resolveCondition(\n branch.when,\n 'choice',\n `${path}[${index}].when`\n );\n if (!guard || guard(args)) {\n return {\n target: branch.target,\n context: branch.context\n ? resolveValue(\n branch.context,\n 'transitionContext',\n makeScope(args),\n `${path}[${index}].context`\n )\n : undefined,\n input:\n branch.input !== undefined\n ? resolveValue(\n branch.input,\n 'input',\n makeScope(args),\n `${path}[${index}].input`\n )\n : undefined,\n description: branch.description,\n reenter: branch.reenter,\n meta: branch.meta\n };\n }\n }\n throw new Error(`Choice state at ${path} did not match any branch.`);\n };\n }\n\n function resolveRouteConfig(route: StateNodeJSON['route'], path: string) {\n if (!route || typeof route === 'function') return route;\n if (isResolvable(route)) {\n return (args: any) =>\n evaluateResolvable(route, 'transition', makeScope(args), path);\n }\n const { guard, ...routeConfig } = route;\n if (!guard) return routeConfig;\n const resolvedGuard = resolveCondition({ type: guard }, 'guard', path);\n return (args: any) => (resolvedGuard!(args) ? routeConfig : undefined);\n }\n\n function executeActions(\n actions: ActionJSON[],\n x: any,\n enq: any,\n stack: string[] = []\n ) {\n let context: MachineContext | undefined;\n for (const action of actions) {\n if (isResolvable(action)) {\n const result = evaluateResolvable(\n action,\n 'action',\n makeScope(x, { params: x.params, enq }),\n '$.actions'\n );\n if (\n result &&\n typeof result === 'object' &&\n 'context' in result &&\n (result as any).context\n ) {\n context ??= {};\n Object.assign(context, (result as any).context);\n }\n continue;\n }\n if (isBuiltInActionJSON(action)) {\n switch (action.type) {\n case '@xstate.raise':\n enq.raise(\n resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n ),\n { id: action.id, delay: action.delay }\n );\n break;\n case '@xstate.cancel':\n enq.cancel(action.id);\n break;\n case '@xstate.log':\n enq.log(...action.args);\n break;\n case '@xstate.emit':\n enq.emit(\n resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n )\n );\n break;\n case '@xstate.assign':\n context ??= {};\n Object.assign(\n context,\n resolveValue(\n action.context,\n 'transitionContext',\n makeScope(x, { params: x.params }),\n '$.actions.context'\n )\n );\n break;\n }\n continue;\n }\n const params = resolveValue(\n action.params,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.params'\n );\n const definition = json.actions?.[action.type];\n if (!definition) {\n enq(x.actions[action.type], params);\n continue;\n }\n if (stack.includes(action.type)) {\n throw new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n );\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n const result = executeActions(\n definitions,\n { ...x, context: { ...x.context, ...context }, params },\n enq,\n stack.concat(action.type)\n );\n if (result.context) context = result.context;\n }\n return { context: context ? { ...x.context, ...context } : undefined };\n }\n\n function iterActions(actions: ActionJSON | ActionJSON[]) {\n const actionArray = toActionArray(actions);\n return ((x: any, enq: any) =>\n executeActions(actionArray, x, enq)) as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n }\n\n function getTransitionConfig(\n transition: TransitionConfigJSON | TransitionConfigJSON[]\n ): any {\n const transitions = Array.isArray(transition) ? transition : [transition];\n return transitions.map((item, index) => {\n if (isResolvable(item)) {\n return (x: any, enq: any) =>\n evaluateResolvable(\n item,\n 'transition',\n makeScope(x, { enq }),\n `$.transition${transitions.length > 1 ? `[${index}]` : ''}`\n );\n }\n const context = item.context\n ? (x: any) =>\n resolveValue(\n item.context,\n 'transitionContext',\n makeScope(x),\n '$.transition.context'\n ) as MachineContext\n : undefined;\n const input =\n item.input !== undefined\n ? (x: any) =>\n resolveValue(\n item.input,\n 'input',\n makeScope(x),\n '$.transition.input'\n )\n : undefined;\n const dynamic = !!context || !!item.actions?.length;\n return {\n matches: item.matches,\n target: dynamic ? undefined : item.target,\n to: dynamic\n ? (x: any, enq: any) => {\n const resolvedContext = context?.(x);\n const result = item.actions?.length\n ? executeActions(\n item.actions,\n resolvedContext\n ? { ...x, context: { ...x.context, ...resolvedContext } }\n : x,\n enq\n )\n : undefined;\n return {\n target: item.target,\n context: result?.context ?? resolvedContext,\n reenter: item.reenter\n };\n }\n : undefined,\n guard: resolveCondition(item.guard, 'guard', '$.transition.guard'),\n description: item.description,\n reenter: item.reenter,\n meta: item.meta,\n input\n };\n });\n }\n\n function iterInvokeConfigs(invokes: InvokeJSON | InvokeJSON[]): any {\n return (Array.isArray(invokes) ? invokes : [invokes]).map((inv) => ({\n src: resolvedSources.actors[inv.src] ?? inv.src,\n id: inv.id,\n registryKey: inv.registryKey,\n input:\n inv.input !== undefined\n ? (args: any) =>\n resolveValue(\n inv.input,\n 'input',\n makeScope(args),\n '$.invoke.input'\n )\n : undefined,\n onDone: inv.onDone ? getTransitionConfig(inv.onDone) : undefined,\n onError: inv.onError ? getTransitionConfig(inv.onError) : undefined,\n onSnapshot: inv.onSnapshot\n ? getTransitionConfig(inv.onSnapshot)\n : undefined,\n timeout: getDurationConfig(inv.timeout, '$.invoke.timeout'),\n onTimeout: inv.onTimeout ? getTransitionConfig(inv.onTimeout) : undefined\n }));\n }\n\n function iterNode(node: StateNodeJSON, nodeKey?: string): any {\n return {\n id: node.id,\n initial: node.initial,\n type: node.type,\n history: node.history,\n target: node.target,\n description: node.description,\n tags: node.tags,\n input: node.input,\n timeout: getDurationConfig(node.timeout, `$.states.${nodeKey}.timeout`),\n states: node.states\n ? Object.fromEntries(\n Object.entries(node.states).map(([key, value]) => [\n key,\n iterNode(value, key)\n ])\n )\n : undefined,\n on: node.on\n ? Object.fromEntries(\n Object.entries(node.on).map(([key, value]) => [\n key,\n getTransitionConfig(value)\n ])\n )\n : undefined,\n always: node.always ? getTransitionConfig(node.always) : undefined,\n onError: node.onError ? getTransitionConfig(node.onError) : undefined,\n choice: makeChoiceConfig(node.choice, `$.states.${nodeKey}.choice`),\n route: resolveRouteConfig(node.route, `$.states.${nodeKey}.route`),\n after: node.after\n ? Object.fromEntries(\n Object.entries(node.after).map(([key, value]) => [\n key,\n getTransitionConfig(value)\n ])\n )\n : undefined,\n onTimeout: node.onTimeout\n ? getTransitionConfig(node.onTimeout)\n : undefined,\n entry: node.entry ? iterActions(node.entry) : undefined,\n exit: node.exit ? iterActions(node.exit) : undefined,\n invoke: node.invoke ? iterInvokeConfigs(node.invoke) : undefined,\n meta: node.meta,\n output: isResolvable(node.output)\n ? ({ context, event, self }: any) =>\n evaluateResolvable(\n node.output as ResolvableJSON,\n 'output',\n { context, event, self },\n `$.states.${nodeKey}.output`\n )\n : node.output\n };\n }\n\n if (json.delays) {\n for (const [key, delay] of Object.entries(json.delays)) {\n if (typeof delay === 'number') resolvedSources.delays[key] = delay;\n else if (typeof delay === 'string')\n resolvedSources.delays[key] = delayToMs(delay);\n else if (delay && typeof delay === 'object') {\n resolvedSources.delays[key] = (args: any) =>\n delayToMs(\n resolveValue(\n delay.duration,\n 'delay',\n makeScope(args),\n `$.delays.${key}.duration`\n ) as string | number\n );\n }\n }\n }\n\n assertMachineJSON(json, resolvedSources, expressionResolver);\n const contextConfig = json.context\n ? {\n context: (args: any) =>\n resolveValue(\n json.context,\n 'context',\n args,\n '$.context'\n ) as MachineContext\n }\n : {};\n const machine = createMachine({\n ...iterNode(json),\n ...contextConfig,\n version: json.version\n }) as unknown as AnyStateMachine;\n const provided = machine.provide({\n actions: resolvedSources.actions,\n actors: resolvedSources.actors,\n guards: {\n 'xstate.stateIn': (args: any, params: any) => {\n const stateId = params?.stateId as string;\n const snapshot = args._snapshot;\n return (\n !!stateId &&\n !!snapshot?.nodes?.some(\n (node: any) => node.id === stateId.replace(/^#/, '')\n )\n );\n },\n 'xstate.not': (args: any, params: any) => {\n const inner = params?.guard;\n const impl = inner && args.guards?.[inner.type];\n if (!impl)\n throw new Error(\n `Guard '${inner?.type}' referenced by 'xstate.not' is not implemented.`\n );\n return !impl(args, inner.params);\n },\n ...resolvedSources.guards\n },\n delays: resolvedSources.delays\n });\n (provided as any)._json = json;\n return provided;\n}\n\nfunction isBuiltInActionJSON(action: ActionJSON): action is BuiltInActionJSON {\n return !isResolvable(action) && action.type.startsWith('@xstate.');\n}\n","/**\n * Machine-definition serialization.\n *\n * `machineConfigToJSON` converts a machine config into a JSON-safe structure\n * (the `MachineJSON` shape accepted by `createMachineFromConfig`). The boundary\n * between serializable structure and runtime sources is explicit: functions are\n * represented as `@code` source objects, while actor logic, runtime schemas,\n * and other non-data runtime values are omitted.\n */\n\nimport type { AnyStateMachine } from './types.ts';\n\nexport interface CodeExpression {\n '@code': string;\n '@lang': 'ts';\n}\n\n/**\n * Returns the JSON-serializable definition of a machine.\n *\n * Inline functions are represented as `{ \"@code\": string, \"@lang\": \"ts\" }`. A\n * machine created via `createMachineFromConfig` returns its original JSON\n * config (lossless round-trip):\n *\n * ```ts\n * import { serializeMachine, createMachineFromConfig } from 'xstate';\n *\n * const json = serializeMachine(machine);\n * const revived = createMachineFromConfig(\n * JSON.parse(JSON.stringify(json))\n * );\n * ```\n */\nexport function serializeMachine(\n machine: AnyStateMachine\n): Record<string, unknown> {\n return (machine as any)._json ?? machineConfigToJSON(machine.config);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction codeExpression(fn: Function): CodeExpression {\n return {\n '@code': fn.toString(),\n '@lang': 'ts'\n };\n}\n\nfunction isActorLogic(value: unknown): value is { id?: string } {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any).transition === 'function' &&\n typeof (value as any).getInitialSnapshot === 'function'\n );\n}\n\nfunction isRuntimeSchema(value: unknown): boolean {\n return !!value && typeof value === 'object' && '~standard' in value;\n}\n\n/** JSON-safe deep copy of a plain value; functions become code expressions. */\nfunction valueToJSON(value: unknown): unknown {\n if (typeof value === 'function') {\n return codeExpression(value);\n }\n if (value === null || typeof value !== 'object') {\n return typeof value === 'bigint' || typeof value === 'symbol'\n ? undefined\n : value;\n }\n if (isActorLogic(value)) {\n return undefined;\n }\n if (isRuntimeSchema(value)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map(valueToJSON).filter((item) => item !== undefined);\n }\n if (value.constructor !== Object && value.constructor !== undefined) {\n // Class instances (actor logic, schemas, dates, ...) are not portable.\n return undefined;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const v = (value as Record<string, unknown>)[key];\n if (v !== undefined) {\n const jsonValue = valueToJSON(v);\n if (jsonValue !== undefined) {\n result[key] = jsonValue;\n }\n }\n }\n return result;\n}\n\nfunction invokeToJSON(invoke: unknown): unknown {\n if (Array.isArray(invoke)) {\n const values = invoke\n .map(invokeToJSON)\n .filter((value) => value !== undefined);\n return values.length ? values : undefined;\n }\n const def = invoke as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(def)) {\n const value = def[key];\n if (value === undefined) {\n continue;\n }\n result[key] =\n key === 'src' && typeof value !== 'string'\n ? (value as { id?: string }).id\n : valueToJSON(value);\n if (result[key] === undefined) {\n delete result[key];\n }\n }\n return result.src === undefined ? undefined : result;\n}\n\nfunction sourcesToJSON(\n map: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (!map) {\n return undefined;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(map)) {\n const value = map[key];\n if (typeof value === 'function') {\n result[key] = undefined;\n } else {\n result[key] = valueToJSON(value);\n }\n if (result[key] === undefined) {\n delete result[key];\n }\n }\n return result;\n}\n\nfunction stateNodeConfigToJSON(\n config: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const key of Object.keys(config)) {\n if (key === 'states' || key === 'invoke') {\n continue;\n }\n const value = config[key];\n if (value !== undefined) {\n result[key] = valueToJSON(value);\n }\n }\n if (config.invoke !== undefined) {\n const invoke = invokeToJSON(config.invoke);\n if (invoke !== undefined) {\n result.invoke = invoke;\n }\n }\n if (config.states) {\n const states: Record<string, unknown> = {};\n for (const key of Object.keys(config.states as object)) {\n states[key] = stateNodeConfigToJSON(\n (config.states as Record<string, Record<string, unknown>>)[key]\n );\n }\n result.states = states;\n }\n\n return result;\n}\n\n/**\n * Converts a machine config (as passed to `createMachine`) to its JSON-safe\n * definition.\n */\nexport function machineConfigToJSON(\n config: Record<string, unknown>\n): Record<string, unknown> {\n const result = stateNodeConfigToJSON(config);\n\n if (config.internalEvents !== undefined) {\n result.internalEvents = valueToJSON(config.internalEvents);\n }\n if (config.schemas) {\n const schemas: Record<string, unknown> = {};\n for (const key of Object.keys(config.schemas as object)) {\n const value = (config.schemas as Record<string, unknown>)[key];\n if (value && typeof value === 'object' && !('~standard' in value)) {\n // Map-form schemas (events/emitted): preserve event-type keys.\n schemas[key] = sourcesToJSON(value as Record<string, unknown>);\n } else {\n schemas[key] = valueToJSON(value);\n }\n if (schemas[key] === undefined) {\n delete schemas[key];\n }\n }\n result.schemas = schemas;\n }\n for (const key of ['actions', 'guards', 'actors', 'delays'] as const) {\n if (config[key]) {\n const value = sourcesToJSON(config[key] as Record<string, unknown>);\n if (value && Object.keys(value).length) {\n result[key] = value;\n } else {\n delete result[key];\n }\n }\n }\n\n return result;\n}\n","import type { StandardSchemaV1 } from './schema.types.ts';\nimport type {\n MachineEventSchema,\n MachineSnapshotSchema,\n MachineVersionDescriptor\n} from './machineVersion.types.ts';\nexport type {\n MachineEventSchema,\n MachineSnapshotSchema,\n MachineVersionDescriptor,\n PersistedMachineSnapshot\n} from './machineVersion.types.ts';\nimport type {\n AnyStateMachine,\n ContextFrom,\n EventFrom,\n EventObject,\n PersistedSnapshotFor,\n Snapshot\n} from './types.ts';\n\nexport type PersistedMachineIdentity<\n TMachine extends AnyStateMachine = AnyStateMachine\n> = {\n id: TMachine['id'];\n version: NonNullable<TMachine['version']>;\n};\n\ntype VersionedStateMachine = AnyStateMachine & {\n version: string;\n snapshotSchema: MachineSnapshotSchema;\n eventSchema: MachineEventSchema;\n};\n\ntype VersionEntry = MachineVersionDescriptor;\n\nexport type PersistedSnapshotFrom<TMachine extends AnyStateMachine> =\n Snapshot<unknown> &\n PersistedSnapshotFor<TMachine> & {\n context: ContextFrom<TMachine>;\n machine: PersistedMachineIdentity<TMachine>;\n [key: string]: unknown;\n };\n\nexport type PersistedSnapshotDataFrom<TMachine extends AnyStateMachine> =\n Snapshot<unknown> & {\n context: ContextFrom<TMachine>;\n [key: string]: unknown;\n };\n\nexport type ParsedPersistedSnapshot<TEntries extends readonly VersionEntry[]> =\n {\n [K in keyof TEntries]: TEntries[K] extends VersionEntry\n ? TEntries[K] extends VersionedStateMachine\n ? {\n source: TEntries[K];\n machine: TEntries[K];\n snapshot: PersistedSnapshotFromEntry<TEntries[K]>;\n }\n : {\n source: TEntries[K];\n snapshot: PersistedSnapshotFromEntry<TEntries[K]>;\n }\n : never;\n }[number];\n\nexport type MachineVersionsOptions<TEntries extends readonly VersionEntry[]> = {\n unversioned?: SnapshotSourceVersion<TEntries>;\n};\n\ntype MaybePromise<T> = T | PromiseLike<T>;\n\ntype MachineVersion<TEntries extends readonly VersionEntry[]> = Extract<\n TEntries[number],\n VersionedStateMachine\n>['version'];\n\ntype SnapshotSourceVersion<TEntries extends readonly VersionEntry[]> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { snapshotSchema: MachineSnapshotSchema }\n ? TEntries[K]['version']\n : never;\n}[number];\n\ntype EventSourceVersion<TEntries extends readonly VersionEntry[]> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { eventSchema: MachineEventSchema }\n ? TEntries[K]['version']\n : never;\n}[number];\n\ntype MachineForVersion<\n TEntries extends readonly VersionEntry[],\n TVersion extends string\n> = {\n [K in keyof TEntries]: TEntries[K] extends VersionedStateMachine\n ? TEntries[K]['version'] extends TVersion\n ? TEntries[K]\n : never\n : never;\n}[number];\n\ntype SnapshotEntryForVersion<\n TEntries extends readonly VersionEntry[],\n TVersion extends string\n> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { snapshotSchema: MachineSnapshotSchema }\n ? TEntries[K]['version'] extends TVersion\n ? TEntries[K]\n : never\n : never;\n}[number];\n\ntype EventEntryForVersion<\n TEntries extends readonly VersionEntry[],\n TVersion extends string\n> = {\n [K in keyof TEntries]: TEntries[K] extends\n | VersionedStateMachine\n | { eventSchema: MachineEventSchema }\n ? TEntries[K]['version'] extends TVersion\n ? TEntries[K]\n : never\n : never;\n}[number];\n\ntype PersistedSnapshotFromEntry<TEntry extends VersionEntry> = TEntry extends {\n snapshotSchema: infer TSchema extends MachineSnapshotSchema;\n}\n ? StandardSchemaV1.InferOutput<TSchema>\n : TEntry extends VersionedStateMachine\n ? PersistedSnapshotFrom<TEntry>\n : never;\n\ntype EventFromEntry<TEntry extends VersionEntry> = TEntry extends {\n eventSchema: infer TSchema extends MachineEventSchema;\n}\n ? StandardSchemaV1.InferOutput<TSchema>\n : TEntry extends VersionedStateMachine\n ? EventFrom<TEntry>\n : never;\n\nexport type PersistedSnapshotSource = {\n id?: string;\n version?: string;\n};\n\nexport type SnapshotMigrationHandlers<\n TEntries extends readonly VersionEntry[],\n TTarget extends VersionedStateMachine\n> = {\n [TVersion in Exclude<SnapshotSourceVersion<TEntries>, TTarget['version']>]?: (\n snapshot: PersistedSnapshotFromEntry<\n SnapshotEntryForVersion<TEntries, TVersion>\n >\n ) => MaybePromise<PersistedSnapshotDataFrom<TTarget>>;\n} & {\n '*'?: (\n snapshot: unknown,\n source: PersistedSnapshotSource\n ) => MaybePromise<PersistedSnapshotDataFrom<TTarget>>;\n};\n\nexport type MigrateSnapshotOptions<\n TEntries extends readonly VersionEntry[],\n TTargetVersion extends MachineVersion<TEntries>\n> = {\n to: TTargetVersion;\n migrations: SnapshotMigrationHandlers<\n TEntries,\n MachineForVersion<TEntries, TTargetVersion>\n >;\n};\n\nexport type EventHistorySource = {\n id?: string;\n version?: string;\n};\n\nexport type EventAdapterHandlers<\n TEntries extends readonly VersionEntry[],\n TTarget extends VersionedStateMachine\n> = {\n [TVersion in Exclude<EventSourceVersion<TEntries>, TTarget['version']>]?: (\n events: readonly EventFromEntry<EventEntryForVersion<TEntries, TVersion>>[]\n ) => MaybePromise<readonly EventFrom<TTarget>[]>;\n} & {\n '*'?: (\n events: readonly unknown[],\n source: EventHistorySource\n ) => MaybePromise<readonly EventFrom<TTarget>[]>;\n};\n\nexport type AdaptEventsOptions<\n TEntries extends readonly VersionEntry[],\n TTargetVersion extends MachineVersion<TEntries>\n> = {\n from: EventHistorySource;\n to: TTargetVersion;\n adapters: EventAdapterHandlers<\n TEntries,\n MachineForVersion<TEntries, TTargetVersion>\n >;\n};\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nfunction isVersionedStateMachine(\n entry: VersionEntry\n): entry is VersionedStateMachine {\n return (\n 'transition' in entry &&\n typeof (entry as VersionedStateMachine).transition === 'function'\n );\n}\n\nfunction hasSnapshotSchema(\n entry: VersionEntry\n): entry is MachineVersionDescriptor & {\n snapshotSchema: MachineSnapshotSchema;\n} {\n return 'snapshotSchema' in entry && entry.snapshotSchema !== undefined;\n}\n\nfunction hasEventSchema(\n entry: VersionEntry\n): entry is MachineVersionDescriptor & { eventSchema: MachineEventSchema } {\n return 'eventSchema' in entry && entry.eventSchema !== undefined;\n}\n\nfunction getSnapshotSource(\n raw: unknown,\n defaultId: string\n): PersistedSnapshotSource {\n if (!isObject(raw)) {\n return {};\n }\n if (isObject(raw.machine)) {\n return {\n id: typeof raw.machine.id === 'string' ? raw.machine.id : undefined,\n version:\n typeof raw.machine.version === 'string'\n ? raw.machine.version\n : undefined\n };\n }\n return {\n id: typeof raw.version === 'string' ? defaultId : undefined,\n version: typeof raw.version === 'string' ? raw.version : undefined\n };\n}\n\nasync function validate(\n schema: StandardSchemaV1 | undefined,\n value: unknown,\n description: string\n): Promise<unknown> {\n if (!schema) {\n return value;\n }\n const result = await schema['~standard'].validate(value);\n if (result.issues) {\n throw new Error(`Invalid ${description}: ${result.issues[0]?.message}`);\n }\n return result.value;\n}\n\nasync function finalizeSnapshot<TTarget extends VersionedStateMachine>(\n snapshot: PersistedSnapshotDataFrom<TTarget>,\n target: TTarget\n): Promise<PersistedSnapshotFrom<TTarget>> {\n return (await validate(\n target.snapshotSchema,\n {\n ...snapshot,\n machine: { id: target.id, version: target.version },\n version: target.version\n },\n `snapshot for machine '${target.id}' version '${target.version}'`\n )) as PersistedSnapshotFrom<TTarget>;\n}\n\nasync function validateEvents<\n TSource extends MachineVersionDescriptor & {\n eventSchema: MachineEventSchema;\n }\n>(\n events: readonly unknown[],\n source: TSource\n): Promise<EventFromEntry<TSource>[]> {\n return Promise.all(\n events.map(async (event, index) => {\n const result = await source.eventSchema['~standard'].validate(event);\n if (result.issues) {\n const message = result.issues[0]?.message;\n if (message?.startsWith('Unknown event ')) {\n throw new Error(message);\n }\n const type = isObject(event) ? event.type : undefined;\n throw new Error(\n typeof type === 'string'\n ? `Invalid event '${type}' at index ${index}${message ? `: ${message}` : '.'}`\n : `Invalid event at index ${index}${message ? `: ${message}` : '.'}`\n );\n }\n const validated = result.value;\n if (!isObject(validated) || typeof validated.type !== 'string') {\n throw new Error(`Invalid event at index ${index}.`);\n }\n return validated as EventFromEntry<TSource>;\n })\n );\n}\n\n/** Creates migration and adaptation utilities for versions of one machine. */\nexport function machineVersions<\n const TEntries extends readonly [VersionEntry, ...VersionEntry[]]\n>(entries: TEntries, options?: MachineVersionsOptions<TEntries>) {\n const byIdentity = new Map<string, VersionEntry>();\n const machinesByIdentity = new Map<string, VersionedStateMachine>();\n const machineId = entries[0].id;\n\n for (const entry of entries) {\n if (entry.version === undefined) {\n throw new Error(`Machine '${entry.id}' must define a version.`);\n }\n if (entry.version === '*') {\n throw new Error(\n \"Machine version '*' is reserved for wildcard migrations.\"\n );\n }\n if (entry.id !== machineId) {\n throw new Error(\n `Machine '${entry.id}' does not match machine ID '${machineId}'.`\n );\n }\n const key = `${entry.id}\\0${entry.version}`;\n if (byIdentity.has(key)) {\n throw new Error(\n `Duplicate machine identity '${entry.id}' version '${entry.version}'.`\n );\n }\n byIdentity.set(key, entry);\n if (isVersionedStateMachine(entry)) {\n machinesByIdentity.set(key, entry);\n }\n }\n\n if (\n options?.unversioned !== undefined &&\n !byIdentity.has(`${machineId}\\0${options.unversioned}`)\n ) {\n throw new Error(\n `Unversioned snapshot version '${options.unversioned}' is not retained for machine '${machineId}'.`\n );\n }\n\n const parseSnapshot = async (\n raw: unknown\n ): Promise<ParsedPersistedSnapshot<TEntries>> => {\n if (!isObject(raw)) {\n throw new Error('Persisted snapshot is missing machine identity.');\n }\n\n let id: string;\n let version: string;\n if (isObject(raw.machine)) {\n ({ id, version } = raw.machine as { id: string; version: string });\n if (typeof id !== 'string' || typeof version !== 'string') {\n throw new Error('Persisted snapshot has an invalid machine identity.');\n }\n } else if (typeof raw.version === 'string') {\n id = machineId;\n version = raw.version;\n } else if (\n raw.version === undefined &&\n options?.unversioned !== undefined\n ) {\n id = machineId;\n version = options.unversioned;\n } else {\n throw new Error('Persisted snapshot is missing machine identity.');\n }\n if (raw.version !== undefined && typeof raw.version !== 'string') {\n throw new Error('Persisted snapshot has an invalid version.');\n }\n if (raw.version !== undefined && raw.version !== version) {\n throw new Error(\n `Persisted snapshot version '${raw.version}' conflicts with machine version '${version}'.`\n );\n }\n\n const source = byIdentity.get(`${id}\\0${version}`);\n if (!source) {\n throw new Error(`Unknown machine identity '${id}' version '${version}'.`);\n }\n\n if (!hasSnapshotSchema(source)) {\n throw new Error(\n `Machine version '${version}' does not define a snapshot schema.`\n );\n }\n const snapshot = await validate(\n source.snapshotSchema,\n raw,\n `snapshot for machine '${id}' version '${version}'`\n );\n\n return {\n source,\n ...(isVersionedStateMachine(source) && { machine: source }),\n snapshot: {\n ...(snapshot as Record<string, unknown>),\n machine: { id, version }\n }\n } as ParsedPersistedSnapshot<TEntries>;\n };\n\n return {\n parseSnapshot,\n async adaptEvents<TTargetVersion extends MachineVersion<TEntries>>(\n events: readonly unknown[],\n adaptationOptions: AdaptEventsOptions<TEntries, TTargetVersion>\n ): Promise<EventFrom<MachineForVersion<TEntries, TTargetVersion>>[]> {\n type TargetMachine = MachineForVersion<TEntries, TTargetVersion>;\n const target = machinesByIdentity.get(\n `${machineId}\\0${adaptationOptions.to}`\n ) as TargetMachine | undefined;\n if (!target) {\n throw new Error(\n `Target version '${adaptationOptions.to}' is not backed by a machine for '${machineId}'.`\n );\n }\n\n const sourceId = adaptationOptions.from.id ?? machineId;\n const source = byIdentity.get(\n `${sourceId}\\0${adaptationOptions.from.version}`\n );\n let sourceError: unknown;\n let sourceValidationFailed = false;\n const hasTypedSource = source && hasEventSchema(source);\n if (hasTypedSource) {\n let sourceEvents: EventObject[] | undefined;\n try {\n sourceEvents = await validateEvents(events, source);\n } catch (error) {\n sourceError = error;\n sourceValidationFailed = true;\n }\n if (sourceEvents) {\n if (source === target) {\n return sourceEvents as EventFrom<TargetMachine>[];\n }\n const adapter = (\n adaptationOptions.adapters as Record<\n string,\n | ((\n events: readonly EventObject[]\n ) =>\n | readonly EventFrom<TargetMachine>[]\n | PromiseLike<readonly EventFrom<TargetMachine>[]>)\n | undefined\n >\n )[source.version];\n if (adapter) {\n return validateEvents(\n await adapter(sourceEvents),\n target\n ) as Promise<EventFrom<TargetMachine>[]>;\n }\n }\n }\n\n const wildcardAdapter = adaptationOptions.adapters['*'];\n if (wildcardAdapter) {\n return validateEvents(\n await wildcardAdapter(events, adaptationOptions.from),\n target\n ) as Promise<EventFrom<TargetMachine>[]>;\n }\n if (hasTypedSource) {\n if (sourceValidationFailed) {\n throw sourceError instanceof Error\n ? sourceError\n : new Error(\n `Unable to validate event history for machine '${source.id}' version '${source.version}'.`,\n { cause: sourceError }\n );\n }\n throw new Error(\n `No event adapter from version '${source.version}' to '${target.version}' for machine '${target.id}'.`\n );\n }\n if (source) {\n throw new Error(\n `Machine version '${source.version}' does not define an event schema; only the '*' adapter can handle its event history.`\n );\n }\n throw new Error(\n `Unknown event history source '${sourceId}' version '${adaptationOptions.from.version}'.`\n );\n },\n async migrateSnapshot<TTargetVersion extends MachineVersion<TEntries>>(\n raw: unknown,\n migrationOptions: MigrateSnapshotOptions<TEntries, TTargetVersion>\n ): Promise<\n PersistedSnapshotFrom<MachineForVersion<TEntries, TTargetVersion>>\n > {\n type TargetMachine = MachineForVersion<TEntries, TTargetVersion>;\n const target = machinesByIdentity.get(\n `${machineId}\\0${migrationOptions.to}`\n ) as TargetMachine | undefined;\n if (!target) {\n throw new Error(\n `Target version '${migrationOptions.to}' is not backed by a machine for '${machineId}'.`\n );\n }\n\n let source: ParsedPersistedSnapshot<TEntries> | undefined;\n let parseError: unknown;\n try {\n source = await parseSnapshot(raw);\n } catch (error) {\n parseError = error;\n }\n\n if (source) {\n if (source.source.version === target.version) {\n return finalizeSnapshot(\n source.snapshot as PersistedSnapshotDataFrom<TargetMachine>,\n target\n );\n }\n const exactMigration = (\n migrationOptions.migrations as unknown as Record<\n string,\n | ((\n snapshot: unknown\n ) => MaybePromise<PersistedSnapshotDataFrom<TargetMachine>>)\n | undefined\n >\n )[source.source.version];\n if (exactMigration) {\n return finalizeSnapshot(\n await exactMigration(source.snapshot),\n target\n );\n }\n }\n\n const wildcardMigration = migrationOptions.migrations['*'];\n if (!wildcardMigration) {\n if (source) {\n throw new Error(\n `No snapshot migration from version '${source.source.version}' to '${target.version}' for machine '${target.id}'.`\n );\n }\n throw parseError;\n }\n\n const snapshot = await wildcardMigration(\n raw,\n getSnapshotSource(raw, machineId)\n );\n return finalizeSnapshot(snapshot, target);\n }\n };\n}\n","import { SetupStateSchemas, StandardSchemaV1 } from './schema.types.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\nimport { StateMachine } from './StateMachine.ts';\nimport {\n createActor as createActorFromLogic,\n type Actor,\n type RequiredActorOptionsKeys\n} from './createActor.ts';\nimport {\n AnyActorRef,\n AnyActorLogic,\n ActorRefFromLogic,\n AnyStateNode,\n EventObject,\n AnyEventObject,\n EventDescriptor,\n ExtractEvent,\n MachineContext,\n ProvidedActor,\n RoutableStateId,\n StateSchema,\n StateValue,\n StateValueFromStateSchema,\n ToChildren,\n MetaObject,\n Cast,\n Compute,\n EnqueueObject,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n SystemRegistry,\n RegistryKeyForLogic,\n ActorOptions,\n Observer,\n Subscription,\n OutputArg,\n SnapshotEvent,\n SingleOrArray,\n AfterEvent,\n TimeoutEvent,\n ErrorEvent\n} from './types.ts';\nimport { AnyActorSystem } from './system.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport {\n ActionSchemas,\n DelayMapFromNames,\n DelaySourceMap,\n GuardSourceMap,\n GuardSchemas,\n InferChildren,\n InferActions,\n InferGuards,\n Sources,\n InferOutput,\n InferEvents,\n InferInternalEvents,\n Next_MachineConfig,\n Next_InvokeConfig,\n Next_StateNodeConfig,\n Next_TransitionConfigOrTarget,\n OutputFromConfig,\n ValidateHistoryDefaults,\n ValidateStateTargets,\n WithDefault\n} from './types.v6.ts';\n\nexport type SetupConfig<\n TSchemas extends SetupSchemas,\n TStates extends Record<string, SetupStateSchema>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TValidator extends ActorLogicValidator | undefined =\n | ActorLogicValidator\n | undefined\n> = {\n validator?: TValidator;\n schemas?: TSchemas;\n states?: TStates;\n actions?: TActionMap;\n actors?: TActorMap;\n guards?: TGuardMap & SetupGuardSources<NoInfer<TSchemas>>;\n delays?: TDelayMap & SetupDelaySources<NoInfer<TSchemas>>;\n};\n\n/**\n * Contextual types for guard/delay source maps passed to `setup()`, derived\n * from the same call's `schemas` (context/events). These intersect the\n * inferred source-map type parameters so inline functions get typed args\n * without hand-annotating.\n */\ntype SetupGuardSources<TSchemas> = GuardSourceMap<\n SetupContext<TSchemas, StandardSchemaV1>,\n SetupEvents<TSchemas, Record<string, StandardSchemaV1>>\n>;\n\ntype SetupDelaySources<TSchemas> = DelaySourceMap<\n SetupContext<TSchemas, StandardSchemaV1>,\n SetupEvents<TSchemas, Record<string, StandardSchemaV1>>\n>;\n\n/**\n * Contextual companion for the whole-config `setup()` overload: gives inline\n * `guards`/`delays` functions typed args from the config's own `schemas`.\n */\ntype SetupSourceCompanions<TSchemas> = {\n guards?: SetupGuardSources<TSchemas>;\n delays?: SetupDelaySources<TSchemas>;\n};\n\ntype MergeRecord<TBase, TExtend> = Omit<TBase, keyof TExtend> & TExtend;\n\n/**\n * Mirrors the runtime `mergeSchemas`: scalar schema keys (`context`, `input`,\n * ...) are overridden whole, while map-valued keys (`events`, `emitted`,\n * `children`, `actions`, `guards`) are merged entry-by-entry with extension\n * entries winning, so base-declared entries stay visible to extension sources.\n */\ntype MergedSetupSchemas<TBaseSchemas, TExtendSchemas> = {\n [K in keyof TBaseSchemas | keyof TExtendSchemas]: K extends\n | 'events'\n | 'emitted'\n | 'children'\n | 'actions'\n | 'guards'\n ? MergeRecord<\n K extends keyof TBaseSchemas ? NonNullable<TBaseSchemas[K]> : {},\n K extends keyof TExtendSchemas ? NonNullable<TExtendSchemas[K]> : {}\n >\n : K extends keyof TExtendSchemas\n ? TExtendSchemas[K]\n : K extends keyof TBaseSchemas\n ? TBaseSchemas[K]\n : never;\n};\n\nexport type AnySetupConfig = SetupConfig<\n SetupSchemas,\n Record<string, SetupStateSchema>,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays'],\n ActorLogicValidator | undefined\n>;\n\ninterface RuntimeValidationDoesNotSupportTransformingSchemas {\n readonly __xstate_error: 'Runtime validation does not support schemas with different input and output types';\n}\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n\ntype AssertNonTransformingSchema<TSchema extends StandardSchemaV1> =\n IsAny<StandardSchemaV1.InferInput<TSchema>> extends true\n ? TSchema\n : IsAny<StandardSchemaV1.InferOutput<TSchema>> extends true\n ? TSchema\n : [\n StandardSchemaV1.InferInput<TSchema>,\n StandardSchemaV1.InferOutput<TSchema>\n ] extends [\n StandardSchemaV1.InferOutput<TSchema>,\n StandardSchemaV1.InferInput<TSchema>\n ]\n ? TSchema\n : RuntimeValidationDoesNotSupportTransformingSchemas;\n\ntype ValidateSchemaMap<TMap> =\n TMap extends Record<string, StandardSchemaV1>\n ? {\n [K in keyof TMap]: TMap[K] extends StandardSchemaV1\n ? AssertNonTransformingSchema<TMap[K]>\n : TMap[K];\n }\n : TMap;\n\ntype ValidateSetupSchemas<TSchemas> = TSchemas extends SetupSchemas\n ? {\n [K in keyof TSchemas]: K extends\n | 'events'\n | 'internalEvents'\n | 'emitted'\n | 'children'\n ? ValidateSchemaMap<TSchemas[K]>\n : K extends 'context' | 'input' | 'output'\n ? TSchemas[K] extends StandardSchemaV1\n ? AssertNonTransformingSchema<TSchemas[K]>\n : TSchemas[K]\n : TSchemas[K];\n }\n : TSchemas;\n\ntype ValidateSetupStates<TStates> =\n TStates extends Record<string, SetupStateSchema>\n ? {\n [K in keyof TStates]: TStates[K] extends SetupStateSchema\n ? Omit<TStates[K], 'schemas' | 'states'> & {\n schemas?: TStates[K]['schemas'] extends SetupStateSchemas\n ? {\n [P in keyof TStates[K]['schemas']]: TStates[K]['schemas'][P] extends StandardSchemaV1\n ? AssertNonTransformingSchema<TStates[K]['schemas'][P]>\n : TStates[K]['schemas'][P];\n }\n : TStates[K]['schemas'];\n states?: TStates[K]['states'] extends Record<\n string,\n SetupStateSchema\n >\n ? ValidateSetupStates<TStates[K]['states']>\n : TStates[K]['states'];\n }\n : TStates[K];\n }\n : TStates;\n\ntype RuntimeValidationConstraint<TSchemas, TStates, TValidator> = [\n TValidator\n] extends [ActorLogicValidator]\n ? {\n schemas?: ValidateSetupSchemas<TSchemas>;\n states?: ValidateSetupStates<TStates>;\n }\n : unknown;\n\ntype RuntimeValidationCompatibility<TSchemas, TStates, TValidator> = [\n TValidator\n] extends [ActorLogicValidator]\n ? [TSchemas] extends [ValidateSetupSchemas<TSchemas>]\n ? [TStates] extends [ValidateSetupStates<TStates>]\n ? unknown\n : RuntimeValidationDoesNotSupportTransformingSchemas\n : RuntimeValidationDoesNotSupportTransformingSchemas\n : unknown;\n\ndeclare const inheritedValidator: unique symbol;\ntype InheritedValidator = typeof inheritedValidator;\n\ntype ResolveExtendedValidator<TBase, TExtension> = [TExtension] extends [\n InheritedValidator\n]\n ? TBase\n : Exclude<TExtension, InheritedValidator>;\n\ntype ExtendValidatorConfig<TExtension> = [TExtension] extends [\n InheritedValidator\n]\n ? { validator?: never }\n : { validator: TExtension };\n\ntype SetupExtensionConfig<\n TBaseSchemas,\n TBaseStates,\n TBaseValidator,\n TExtendSchemas extends SetupSchemas,\n TExtendStates extends Record<string, SetupStateSchema>,\n TExtendActionMap extends Sources['actions'],\n TExtendActorMap extends Sources['actors'],\n TExtendGuardMap extends Sources['guards'],\n TExtendDelayMap extends Sources['delays'],\n TExtendValidator extends ActorLogicValidator | undefined | InheritedValidator\n> = Omit<\n SetupConfig<\n TExtendSchemas,\n TExtendStates,\n TExtendActionMap,\n TExtendActorMap,\n TExtendGuardMap,\n TExtendDelayMap\n >,\n 'validator' | 'guards' | 'delays'\n> & {\n guards?: TExtendGuardMap &\n SetupGuardSources<\n NoInfer<MergedSetupSchemas<TBaseSchemas, TExtendSchemas>>\n >;\n delays?: TExtendDelayMap &\n SetupDelaySources<\n NoInfer<MergedSetupSchemas<TBaseSchemas, TExtendSchemas>>\n >;\n} & ExtendValidatorConfig<TExtendValidator> &\n RuntimeValidationCompatibility<\n NoInfer<TBaseSchemas>,\n NoInfer<TBaseStates>,\n ResolveExtendedValidator<TBaseValidator, TExtendValidator>\n > &\n RuntimeValidationConstraint<\n NoInfer<TExtendSchemas>,\n NoInfer<TExtendStates>,\n ResolveExtendedValidator<TBaseValidator, TExtendValidator>\n >;\n\ntype InlineMachineSchemas<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TActionSchemaMap,\n TGuardSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap\n> = {\n context?: TContextSchema;\n events?: TEventSchemaMap;\n internalEvents?: TInternalEventSchemaMap;\n emitted?: TEmittedSchemaMap;\n actions?: TActionSchemaMap;\n guards?: TGuardSchemaMap;\n input?: TInputSchema;\n output?: TOutputSchema;\n meta?: TMetaSchema;\n tags?: TTagSchema;\n children?: TChildrenSchemaMap;\n};\n\ntype MachineConfigStates<TConfig> = TConfig extends {\n states?: infer TStates;\n}\n ? TStates\n : {};\n\ntype MachineConfigSchemas<TConfig> = TConfig extends {\n schemas?: infer TSchemas;\n}\n ? TSchemas\n : {};\n\nexport type SystemConfig<TSystemRegistry extends SystemRegistry> = {\n registry?: TSystemRegistry;\n};\n\nexport type SystemActorMap<TSystemRegistry extends SystemRegistry> = {\n [K in keyof TSystemRegistry & string]: ActorRefFromLogic<TSystemRegistry[K]>;\n};\n\ntype MachineIdentity<TConfig> = {\n readonly id: TConfig extends { id: infer TId extends string }\n ? TId\n : '(machine)';\n readonly version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n};\n\nexport type SystemRuntime<TSystemRegistry extends SystemRegistry> = Omit<\n AnyActorSystem,\n 'get' | 'getAll'\n> & {\n get<K extends keyof SystemActorMap<TSystemRegistry> & string>(\n key: K\n ): SystemActorMap<TSystemRegistry>[K] | undefined;\n getAll(): Partial<SystemActorMap<TSystemRegistry>>;\n};\n\ntype LogicMatchesRegistryKey<TLogic, TSystemLogic> =\n TLogic extends AnyActorLogic\n ? TSystemLogic extends AnyActorLogic\n ? [TLogic] extends [TSystemLogic]\n ? true\n : [TSystemLogic] extends [TLogic]\n ? true\n : ActorRefFromLogic<TLogic> extends ActorRefFromLogic<TSystemLogic>\n ? true\n : false\n : false\n : false;\n\ntype RegistryKeyMatchesSrc<\n TKey extends string,\n TSrc,\n TSystemRegistry extends SystemRegistry,\n TActorMap extends Sources['actors']\n> = TKey extends keyof TSystemRegistry & string\n ? TSrc extends keyof TActorMap & string\n ? LogicMatchesRegistryKey<TActorMap[TSrc], TSystemRegistry[TKey]>\n : TSrc extends AnyActorLogic\n ? LogicMatchesRegistryKey<TSrc, TSystemRegistry[TKey]>\n : true\n : false;\n\ntype ValidateSystemInvoke<\n TInvoke,\n TSystemRegistry extends SystemRegistry,\n TActorMap extends Sources['actors']\n> = TInvoke extends readonly unknown[]\n ? {\n [K in keyof TInvoke]: TInvoke[K] &\n ValidateSystemInvoke<TInvoke[K], TSystemRegistry, TActorMap>;\n }\n : TInvoke extends { registryKey: infer TKey }\n ? TKey extends string\n ? TInvoke extends { src: infer TSrc }\n ? RegistryKeyMatchesSrc<\n TKey,\n TSrc,\n TSystemRegistry,\n TActorMap\n > extends true\n ? unknown\n : { registryKey: never }\n : TKey extends keyof TSystemRegistry & string\n ? unknown\n : { registryKey: never }\n : { registryKey: never }\n : unknown;\n\ntype ValidateRegistryKeys<\n TConfig,\n TSystemRegistry extends SystemRegistry,\n TActorMap extends Sources['actors']\n> = string extends keyof TSystemRegistry\n ? unknown\n : (TConfig extends { invoke: infer TInvoke }\n ? {\n invoke: TInvoke &\n ValidateSystemInvoke<TInvoke, TSystemRegistry, TActorMap>;\n }\n : unknown) &\n (TConfig extends { states: infer TStates }\n ? {\n states: {\n [K in keyof TStates]: TStates[K] &\n ValidateRegistryKeys<TStates[K], TSystemRegistry, TActorMap>;\n };\n }\n : unknown);\n\nexport type { SetupStateSchemas };\n\nexport type SetupSchemas = {\n context?: StandardSchemaV1;\n events?: Record<string, StandardSchemaV1>;\n internalEvents?: Record<string, StandardSchemaV1>;\n actions?: ActionSchemas;\n guards?: GuardSchemas;\n emitted?: Record<string, StandardSchemaV1>;\n input?: StandardSchemaV1;\n output?: StandardSchemaV1;\n meta?: StandardSchemaV1;\n tags?: StandardSchemaV1;\n children?: Record<string, StandardSchemaV1>;\n};\n\n/** State schema with optional input/output schemas and nested states */\nexport interface SetupStateSchema {\n schemas?: SetupStateSchemas;\n states?: Record<string, SetupStateSchema>;\n}\n\ntype SetupSchema<\n TSchemas,\n TKey extends keyof SetupSchemas\n> = TKey extends keyof TSchemas\n ? TSchemas[TKey] extends StandardSchemaV1\n ? TSchemas[TKey]\n : never\n : never;\n\ntype SetupSchemaMap<\n TSchemas,\n TKey extends 'events' | 'internalEvents' | 'emitted' | 'children'\n> = TKey extends keyof TSchemas\n ? TSchemas[TKey] extends Record<string, StandardSchemaV1>\n ? TSchemas[TKey]\n : never\n : never;\n\ntype SetupActionSchemaMap<TSchemas> = 'actions' extends keyof TSchemas\n ? TSchemas['actions'] extends ActionSchemas\n ? TSchemas['actions']\n : never\n : never;\n\ntype SetupGuardSchemaMap<TSchemas> = 'guards' extends keyof TSchemas\n ? TSchemas['guards'] extends GuardSchemas\n ? TSchemas['guards']\n : never\n : never;\n\ntype SetupOrConfigSchema<\n TSchemas,\n TKey extends Exclude<\n keyof SetupSchemas,\n 'events' | 'actions' | 'guards' | 'emitted' | 'children'\n >,\n TConfigSchema extends StandardSchemaV1\n> = [SetupSchema<TSchemas, TKey>] extends [never]\n ? TConfigSchema\n : SetupSchema<TSchemas, TKey>;\n\ntype SetupOrConfigSchemaMap<\n TSchemas,\n TKey extends 'events' | 'internalEvents' | 'emitted' | 'children',\n TConfigSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, TKey>] extends [never]\n ? TConfigSchemaMap\n : SetupSchemaMap<TSchemas, TKey>;\n\ntype SetupStateKeys<TStateSchemas extends Record<string, SetupStateSchema>> =\n keyof TStateSchemas & string;\n\ntype SetupStateKey<TStateSchemas extends Record<string, SetupStateSchema>> =\n string extends SetupStateKeys<TStateSchemas>\n ? string\n : [SetupStateKeys<TStateSchemas>] extends [never]\n ? string\n : SetupStateKeys<TStateSchemas>;\n\ntype SetupStateTarget<TStateSchemas extends Record<string, SetupStateSchema>> =\n string extends SetupStateKeys<TStateSchemas>\n ? string\n : [SetupStateKeys<TStateSchemas>] extends [never]\n ? string\n : SetupStateKeys<TStateSchemas> | `.${string}` | `#${string}`;\n\ntype StateSchemasWithKeys<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TStateKeys extends string\n> = TStateSchemas & {\n [K in Exclude<TStateKeys, keyof TStateSchemas>]: {};\n};\n\n/**\n * The sibling state schemas of a dotted path: the children of the path's\n * parent. A bare transition target resolves relative to the parent, so the\n * valid targets for a path's config are its siblings. For a dotless (top-level)\n * path the siblings are the root states.\n */\ntype ResolveStateSiblings<\n TStates extends Record<string, SetupStateSchema>,\n TPath extends string\n> = TPath extends `${infer Head}.${infer Rest}`\n ? Head extends keyof TStates\n ? TStates[Head]['states'] extends Record<string, SetupStateSchema>\n ? ResolveStateSiblings<TStates[Head]['states'], Rest>\n : never\n : never\n : TStates; // dotless path: siblings are the current level's states\n\n/**\n * Resolves a dotted state path (e.g. `'parent.child'`) into the leaf\n * `SetupStateSchema` it addresses, or `never` if any segment is missing.\n */\ntype ResolveStatePath<\n TStates extends Record<string, SetupStateSchema>,\n TPath extends string\n> = TPath extends `${infer Head}.${infer Rest}`\n ? Head extends keyof TStates\n ? TStates[Head]['states'] extends Record<string, SetupStateSchema>\n ? ResolveStatePath<TStates[Head]['states'], Rest>\n : never\n : never\n : TPath extends keyof TStates\n ? TStates[TPath]\n : never;\n\n/** Union of every addressable dotted path into a setup states tree */\ntype StatePathsInner<TStates extends Record<string, SetupStateSchema>> = {\n [K in SetupStateKeys<TStates>]:\n | K\n | (TStates[K]['states'] extends Record<string, SetupStateSchema>\n ? `${K}.${StatePathsInner<TStates[K]['states']>}`\n : never);\n}[SetupStateKeys<TStates>];\n\ntype StatePaths<TStates extends Record<string, SetupStateSchema>> =\n string extends SetupStateKeys<TStates>\n ? string\n : [SetupStateKeys<TStates>] extends [never]\n ? string\n : StatePathsInner<TStates>;\n\n/**\n * Shared body of both `createStateConfig` overloads: the\n * `StateNodeConfigWithNestedInput` instantiation whose only varying parts are\n * the leading sibling-schemas and state-schema arguments.\n */\ntype SetupStateNodeConfig<\n TStates extends Record<string, SetupStateSchema>,\n TStateSchema extends SetupStateSchema,\n TSchemas extends SetupSchemas,\n TSetupActionMap extends Sources['actions'],\n TSetupActorMap extends Sources['actors'],\n TSetupGuardMap extends Sources['guards'],\n TSetupDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = StateNodeConfigWithNestedInput<\n TStates,\n TStateSchema,\n SetupContext<TSchemas, StandardSchemaV1>,\n SetupContextShape<\n TSchemas,\n StandardSchemaV1,\n SetupContext<TSchemas, StandardSchemaV1>\n >,\n SetupEvents<TSchemas, Record<string, StandardSchemaV1>>,\n Cast<\n SetupChildren<TSchemas, Record<string, StandardSchemaV1>>,\n Record<string, AnyActorRef | undefined>\n >,\n string,\n SetupTags<TSchemas, StandardSchemaV1>,\n SetupOutput<TSchemas, StandardSchemaV1>,\n SetupEmitted<TSchemas, Record<string, StandardSchemaV1>>,\n SetupMeta<TSchemas, StandardSchemaV1>,\n SetupActions<TSchemas, TSetupActionMap>,\n TSetupActorMap,\n SetupGuards<TSchemas, TSetupGuardMap>,\n TSetupDelayMap,\n TSystemRegistry\n>;\n\ntype SetupContext<TSchemas, TContextSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'context'>\n] extends [never]\n ? unknown extends StandardSchemaV1.InferOutput<TContextSchema>\n ? MachineContext\n : StandardSchemaV1.InferOutput<TContextSchema> & MachineContext\n : StandardSchemaV1.InferOutput<SetupSchema<TSchemas, 'context'>> &\n MachineContext;\n\ntype SetupContextShape<\n TSchemas,\n TContextSchema extends StandardSchemaV1,\n TFallbackContext\n> = [SetupSchema<TSchemas, 'context'>] extends [never]\n ? unknown extends StandardSchemaV1.InferOutput<TContextSchema>\n ? TFallbackContext\n : StandardSchemaV1.InferOutput<TContextSchema>\n : StandardSchemaV1.InferOutput<SetupSchema<TSchemas, 'context'>>;\n\ntype SetupContextRequired<TSchemas, TContextSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'context'>\n] extends [never]\n ? unknown extends StandardSchemaV1.InferOutput<TContextSchema>\n ? false\n : true\n : true;\n\ntype SetupPublicEvents<\n TSchemas,\n TEventSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'events'>] extends [never]\n ? InferEvents<TEventSchemaMap>\n : InferEvents<SetupSchemaMap<TSchemas, 'events'>>;\n\ntype SetupInternalEvents<\n TSchemas,\n TInternalEventSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'internalEvents'>] extends [never]\n ? InferInternalEvents<TInternalEventSchemaMap>\n : InferInternalEvents<SetupSchemaMap<TSchemas, 'internalEvents'>>;\n\ntype SetupEvents<\n TSchemas,\n TEventSchemaMap extends Record<string, StandardSchemaV1>,\n TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {}\n> =\n | SetupPublicEvents<TSchemas, TEventSchemaMap>\n | SetupInternalEvents<TSchemas, TInternalEventSchemaMap>;\n\ntype SetupTags<TSchemas, TTagSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'tags'>\n] extends [never]\n ? StandardSchemaV1.InferOutput<TTagSchema> & string\n : StandardSchemaV1.InferOutput<SetupSchema<TSchemas, 'tags'>> & string;\n\ntype SetupInput<TSchemas, TInputSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'input'>\n] extends [never]\n ? InferOutput<TInputSchema, unknown>\n : InferOutput<SetupSchema<TSchemas, 'input'>, unknown>;\n\ntype SetupOutput<TSchemas, TOutputSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'output'>\n] extends [never]\n ? InferOutput<TOutputSchema, unknown>\n : InferOutput<SetupSchema<TSchemas, 'output'>, unknown>;\n\n/**\n * Whether an output schema was declared, either in `setup({ schemas })` or in\n * the machine config's own `schemas.output`. A declared schema is always\n * authoritative for the machine's output type.\n */\ntype HasOutputSchema<TSchemas, TOutputSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'output'>\n] extends [never]\n ? StandardSchemaV1 extends TOutputSchema\n ? false\n : true\n : true;\n\n/**\n * The machine's output type. A declared output schema wins; otherwise the type\n * is inferred from the config's `output` property (a mapper's return type, or\n * the static value's type).\n */\ntype SetupOrConfigOutput<\n TSchemas,\n TOutputSchema extends StandardSchemaV1,\n TConfig\n> =\n HasOutputSchema<TSchemas, TOutputSchema> extends true\n ? SetupOutput<TSchemas, TOutputSchema>\n : OutputFromConfig<TConfig, SetupOutput<TSchemas, TOutputSchema>>;\n\ntype SetupEmitted<\n TSchemas,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'emitted'>] extends [never]\n ? WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>\n : WithDefault<\n InferEvents<SetupSchemaMap<TSchemas, 'emitted'>>,\n AnyEventObject\n >;\n\ntype SetupMeta<TSchemas, TMetaSchema extends StandardSchemaV1> = [\n SetupSchema<TSchemas, 'meta'>\n] extends [never]\n ? InferOutput<TMetaSchema, MetaObject>\n : InferOutput<SetupSchema<TSchemas, 'meta'>, MetaObject>;\n\ntype SetupChildren<\n TSchemas,\n TChildrenSchemaMap extends Record<string, StandardSchemaV1>\n> = [SetupSchemaMap<TSchemas, 'children'>] extends [never]\n ? InferChildren<TChildrenSchemaMap>\n : InferChildren<SetupSchemaMap<TSchemas, 'children'>>;\n\ntype SetupActions<TSchemas, TActionMap extends Sources['actions']> = [\n SetupActionSchemaMap<TSchemas>\n] extends [never]\n ? TActionMap\n : MergeSourceMaps<InferActions<SetupActionSchemaMap<TSchemas>>, TActionMap>;\n\ntype SetupGuards<TSchemas, TGuardMap extends Sources['guards']> = [\n SetupGuardSchemaMap<TSchemas>\n] extends [never]\n ? TGuardMap\n : MergeSourceMaps<InferGuards<SetupGuardSchemaMap<TSchemas>>, TGuardMap>;\n\ntype MergeChildren<\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActor extends ProvidedActor\n> = [keyof TChildren] extends [never]\n ? Compute<ToChildren<TActor>>\n : Compute<TChildren>;\n\ntype MergeSourceMaps<\n TBase extends Record<string, unknown>,\n TExtension extends Record<string, unknown>\n> = Compute<TBase & TExtension>;\n\ntype DelayNamesFromConfigOrString<TConfig> = TConfig extends {\n delays: infer TDelays;\n}\n ? Extract<keyof TDelays, string>\n : string;\n\ntype DelayNamesFromConfig<TConfig> = TConfig extends { delays: infer TDelays }\n ? Extract<keyof TDelays, string>\n : never;\n\ntype InvalidDelayReferences<TConfig, TDelays extends string> =\n | (TConfig extends { after: infer TAfter }\n ? Exclude<Extract<keyof TAfter, string>, TDelays>\n : never)\n | (TConfig extends { timeout: infer TTimeout }\n ? TTimeout extends string\n ? TTimeout extends TDelays\n ? never\n : TTimeout\n : never\n : never)\n | (TConfig extends { states: infer TStates }\n ? TStates extends Record<string, unknown>\n ? {\n [K in keyof TStates]: InvalidDelayReferences<TStates[K], TDelays>;\n }[keyof TStates]\n : never\n : never);\n\ntype ValidateSetupDelayReferences<\n TConfig,\n TSetupDelays extends string\n> = string extends (\n [TSetupDelays] extends [never]\n ? DelayNamesFromConfigOrString<TConfig>\n : TSetupDelays | DelayNamesFromConfig<TConfig>\n)\n ? unknown\n : InvalidDelayReferences<\n TConfig,\n [TSetupDelays] extends [never]\n ? DelayNamesFromConfigOrString<TConfig>\n : TSetupDelays | DelayNamesFromConfig<TConfig>\n > extends never\n ? unknown\n : never;\n\n/** Extracts input type from a state schema */\ntype StateInput<TStateSchema extends SetupStateSchema> =\n TStateSchema['schemas'] extends { input: infer TInputSchema }\n ? TInputSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : undefined\n : undefined;\n\n/** Extracts the completion output type from a state schema. */\ntype StateOutput<\n TStateSchema extends SetupStateSchema,\n TFallback\n> = TStateSchema['schemas'] extends { output: infer TOutputSchema }\n ? TOutputSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TOutputSchema>\n : TFallback\n : TFallback;\n\ntype StateCompletionOutput<TStateSchema extends SetupStateSchema> = StateOutput<\n TStateSchema,\n unknown\n>;\n\ntype StateContext<\n TStateSchema extends SetupStateSchema,\n TFallbackContext extends MachineContext\n> = TStateSchema['schemas'] extends { context: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TContextSchema> &\n MachineContext &\n RootContextMarker<TFallbackContext>\n : RootContext<TFallbackContext>\n : RootContext<TFallbackContext>;\n\ndeclare const rootContext: unique symbol;\n\ntype RootContextMarker<TContext> = {\n readonly [rootContext]?: RootContext<TContext>;\n};\n\ntype RootContext<TContext> = typeof rootContext extends keyof TContext\n ? TContext[typeof rootContext]\n : TContext;\n\ntype StateContextShape<\n TStateSchema extends SetupStateSchema,\n TFallbackContext\n> = TStateSchema['schemas'] extends { context: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TContextSchema> &\n RootContextMarker<TFallbackContext>\n : RootContext<TFallbackContext>\n : RootContext<TFallbackContext>;\n\ntype WithNestedStates<TConfig, TNestedStates> = TConfig extends {\n type: 'choice';\n}\n ? TConfig\n : Omit<TConfig, 'states'> & { states?: TNestedStates };\n\ntype DistributiveOmit<T, K extends keyof any> = T extends any\n ? Omit<T, K>\n : never;\n\n/**\n * Converts SetupStateSchema to StateSchema with input types included. This\n * allows getInputs() to be strongly typed.\n */\ntype SetupStateSchemaToStateSchema<TSetupSchema extends SetupStateSchema> = {\n input: StateInput<TSetupSchema>;\n contextSchema: TSetupSchema['schemas'] extends {\n context: infer TContextSchema;\n }\n ? TContextSchema extends StandardSchemaV1\n ? TContextSchema\n : undefined\n : undefined;\n outputSchema: TSetupSchema['schemas'] extends {\n output: infer TOutputSchema;\n }\n ? TOutputSchema extends StandardSchemaV1\n ? TOutputSchema\n : undefined\n : undefined;\n states: TSetupSchema['states'] extends Record<string, SetupStateSchema>\n ? {\n [K in keyof TSetupSchema['states'] &\n string]: SetupStateSchemaToStateSchema<TSetupSchema['states'][K]>;\n }\n : undefined;\n};\n\n/** Converts the root setup states config to a StateSchema. */\ntype SetupStatesToStateSchema<\n TStates extends Record<string, SetupStateSchema>\n> = {\n states: {\n [K in keyof TStates & string]: SetupStateSchemaToStateSchema<TStates[K]>;\n };\n};\n\ntype EmptyStateSchema = {\n input: undefined;\n states: undefined;\n};\n\ntype StateSchemaInput<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = TSetup extends { input: infer TInput }\n ? TInput\n : TConfig extends { input: infer TInput }\n ? TInput\n : undefined;\n\ntype StateSchemaContextSchema<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = TSetup extends { contextSchema: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? TContextSchema\n : undefined\n : TConfig extends { contextSchema: infer TContextSchema }\n ? TContextSchema extends StandardSchemaV1\n ? TContextSchema\n : undefined\n : undefined;\n\ntype StateSchemaOutputSchema<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = TSetup extends { outputSchema: infer TOutputSchema }\n ? TOutputSchema extends StandardSchemaV1\n ? TOutputSchema\n : undefined\n : TConfig extends { outputSchema: infer TOutputSchema }\n ? TOutputSchema extends StandardSchemaV1\n ? TOutputSchema\n : undefined\n : undefined;\n\ntype StateSchemaChild<\n TSetup extends StateSchema,\n K extends string\n> = TSetup extends { states: infer TStates }\n ? K extends keyof TStates\n ? Cast<TStates[K], StateSchema>\n : EmptyStateSchema\n : EmptyStateSchema;\n\ntype MergeStateSchema<\n TConfig extends StateSchema,\n TSetup extends StateSchema\n> = Omit<TConfig, 'contextSchema' | 'input' | 'states'> & {\n contextSchema: StateSchemaContextSchema<TConfig, TSetup>;\n outputSchema: StateSchemaOutputSchema<TConfig, TSetup>;\n input: StateSchemaInput<TConfig, TSetup>;\n states: TConfig extends { states: infer TStates }\n ? TStates extends Record<string, StateSchema>\n ? {\n [K in keyof TStates & string]: MergeStateSchema<\n TStates[K],\n StateSchemaChild<TSetup, K>\n >;\n }\n : undefined\n : undefined;\n};\n\n/** Machine config with typed state input */\ntype SetupMachineConfig<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TStateKeys extends string,\n TSchemas extends SetupSchemas,\n TContextSchema extends StandardSchemaV1,\n TEventSchemaMap extends Record<string, StandardSchemaV1>,\n TInternalEventSchemaMap extends Record<string, StandardSchemaV1>,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>,\n TInputSchema extends StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n TChildrenSchemaMap extends Record<string, StandardSchemaV1>,\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TDelays extends string,\n TTag extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TContextRequired extends boolean,\n TRootDelays extends string = TDelays,\n TRootActionMap extends Sources['actions'] = TActionMap,\n TRootActorMap extends Sources['actors'] = TActorMap,\n TRootGuardMap extends Sources['guards'] = TGuardMap\n> = Omit<\n Next_MachineConfig<\n SetupOrConfigSchema<TSchemas, 'context', TContextSchema>,\n SetupOrConfigSchemaMap<TSchemas, 'events', TEventSchemaMap>,\n SetupOrConfigSchemaMap<TSchemas, 'internalEvents', TInternalEventSchemaMap>,\n SetupOrConfigSchemaMap<TSchemas, 'emitted', TEmittedSchemaMap>,\n SetupOrConfigSchema<TSchemas, 'input', TInputSchema>,\n SetupOrConfigSchema<TSchemas, 'output', TOutputSchema>,\n SetupOrConfigSchema<TSchemas, 'meta', TMetaSchema>,\n SetupOrConfigSchema<TSchemas, 'tags', TTagSchema>,\n SetupOrConfigSchemaMap<TSchemas, 'children', TChildrenSchemaMap>,\n TContext,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TContextRequired,\n TSystemRegistry\n >,\n | 'states'\n | 'initial'\n | 'on'\n | 'always'\n | 'invoke'\n | 'actions'\n | 'actors'\n | 'guards'\n | 'delays'\n> & {\n actions?: TRootActionMap;\n actors?: TRootActorMap;\n guards?: TRootGuardMap & GuardSourceMap<TContext, TEvent>;\n delays?: {\n [K in TRootDelays | number]?:\n | number\n | (({\n context,\n event,\n stateNode\n }: {\n context: TContext;\n event: TEvent;\n stateNode: AnyStateNode;\n }) => number);\n };\n initial?:\n | TStateKeys\n | InitialTransitionWithInput<TStateSchemas, TContext, TEvent>\n | undefined;\n on?: StateTransitions<\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n always?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n invoke?: SingleOrArray<\n SetupInvokeConfig<\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n >;\n states?: StatesWithInput<\n TStateSchemas,\n TStateSchemas,\n TContext,\n SetupContextShape<TSchemas, TContextSchema, TContext>,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n SetupOutput<TSchemas, TOutputSchema>,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TStateKeys\n >;\n};\n\n/** States config type that provides typed input for known states */\ntype StatesWithInput<\n TRootStateSchemas extends Record<string, SetupStateSchema>,\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TDelays extends string,\n TTag extends string,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TStateKeys extends string = SetupStateKey<TStateSchemas>\n> = {\n [K in TStateKeys]?: StateNodeConfigWithNestedInput<\n StateSchemasWithKeys<TRootStateSchemas, TStateKeys>,\n K extends keyof TStateSchemas ? TStateSchemas[K] : {},\n TContext,\n TContextShape,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n TOutput,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n};\n\n/** State node config that recursively applies typed input for nested states */\ntype StateNodeConfigWithNestedInput<\n TSiblingStateSchemas extends Record<string, SetupStateSchema>,\n TStateSchema extends SetupStateSchema,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TDelays extends string,\n TTag extends string,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = WithNestedStates<\n Omit<\n Next_StateNodeConfig<\n StateContext<TStateSchema, TContext>,\n TEvent,\n TDelays,\n TTag,\n StateOutput<TStateSchema, TOutput>,\n TEmitted,\n TMeta,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n StateInput<TStateSchema>,\n Record<string, unknown>,\n TSystemRegistry,\n StateCompletionOutput<TStateSchema>\n >,\n | 'on'\n | 'always'\n | 'initial'\n | 'invoke'\n | 'onDone'\n | 'onError'\n | 'onTimeout'\n | 'after'\n > & {\n initial?: TStateSchema['states'] extends Record<string, SetupStateSchema>\n ?\n | SetupStateKey<TStateSchema['states']>\n | (string & {})\n | InitialTransitionWithInput<\n TStateSchema['states'],\n StateContext<TStateSchema, TContext>,\n TEvent\n >\n :\n | string\n | {\n target: string;\n input?: Record<string, unknown>;\n }\n | undefined;\n on?: StateTransitions<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n always?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n invoke?: SingleOrArray<\n SetupInvokeConfig<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n >;\n onDone?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n DoneStateEvent<StateCompletionOutput<TStateSchema>>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n onError?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n ErrorEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n onTimeout?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n TimeoutEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n after?: {\n [K in NoInfer<TDelays> | number]?: StateTransitionConfigOrTarget<\n TSiblingStateSchemas,\n StateContext<TStateSchema, TContext>,\n StateContextShape<TStateSchema, TContextShape>,\n AfterEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n StateInput<TStateSchema>\n >;\n };\n },\n TStateSchema['states'] extends Record<string, SetupStateSchema>\n ? StatesWithInput<\n TStateSchema['states'],\n TStateSchema['states'],\n TContext,\n StateContextShape<TStateSchema, TContextShape>,\n TEvent,\n TChildren,\n TDelays,\n TTag,\n TOutput,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n : {\n [K in string]?: Next_StateNodeConfig<\n TContext,\n TEvent,\n TDelays,\n TTag,\n TOutput,\n TEmitted,\n TMeta,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n undefined,\n Record<string, unknown>,\n TSystemRegistry\n >;\n }\n>;\n\ntype StateTransitions<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TInput = undefined\n> = {\n [K in EventDescriptor<TEvent>]?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n ExtractEvent<TEvent, K>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TInput\n >;\n};\n\ntype InvokeDoneEvent<TInvoke> = TInvoke extends {\n onDone?: Next_TransitionConfigOrTarget<\n infer _TContext,\n infer TDoneEvent,\n infer _TEvent,\n infer _TEmitted,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer _TMeta\n >;\n}\n ? Cast<TDoneEvent, EventObject>\n : DoneActorEvent;\n\ntype SetupInvokeConfig<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> =\n Next_InvokeConfig<\n TContext,\n TEvent,\n TEmitted,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta,\n TSystemRegistry\n > extends infer TInvoke\n ? TInvoke extends any\n ? DistributiveOmit<\n TInvoke,\n 'onDone' | 'onError' | 'onSnapshot' | 'onTimeout'\n > & {\n // Inline (unregistered-logic) invoke branches have no function-form\n // `onDone` when actors are registered (see InlineInvokeOnDone), and\n // that must be preserved when rebuilding `onDone` here: when a\n // registered logic value is passed as `src`, TypeScript narrows the\n // invoke union to the matching registered branch plus the inline\n // branch, and contextual typing of `onDone` callbacks (and their\n // per-actor `event.output`) only works if the registered branch\n // provides the union's only call signature.\n onDone?: TInvoke extends {\n onDone?: infer TOnDone;\n }\n ? [\n Extract<NonNullable<TOnDone>, (...args: any[]) => unknown>\n ] extends [never]\n ?\n | undefined\n | StateTransitionObjectConfig<\n TStateSchemas,\n TContext,\n TContextShape,\n DoneActorEvent,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n false\n >\n : StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n InvokeDoneEvent<TInvoke>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n : never;\n onError?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n onSnapshot?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n SnapshotEvent<any>,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n onTimeout?: StateTransitionConfigOrTarget<\n TStateSchemas,\n TContext,\n TContextShape,\n TEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n }\n : never\n : never;\n\ntype StateTransitionConfigOrTarget<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TInput = undefined\n> =\n | undefined\n | StateTransitionObjectConfig<\n TStateSchemas,\n TContext,\n TContextShape,\n TExpressionEvent,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n | StateTransitionFunction<\n TStateSchemas,\n TContext,\n TContextShape,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TChildren,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TInput\n >;\n\ntype StateTransitionObjectConfig<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TAllowContextMapper extends boolean = true\n> =\n | (StateTransitionResult<\n TStateSchemas,\n TContext,\n TContextShape,\n TMeta,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n TAllowContextMapper\n > & {\n description?: string;\n })\n | {\n target: SetupStateTarget<TStateSchemas>[];\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n TContextShape,\n TContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n description?: string;\n reenter?: boolean;\n meta?: TMeta;\n input?:\n | Record<string, unknown>\n | ((\n args: {\n context: TContext;\n event: TExpressionEvent;\n } & OutputArg<TExpressionEvent>\n ) => Record<string, unknown>);\n };\n\ntype StateTransitionContextMapper<\n TContext extends MachineContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = (\n args: {\n context: TContext;\n event: TExpressionEvent;\n self: AnyActorRef;\n parent: AnyActorRef | undefined;\n value: StateValue;\n children: TChildren;\n system: SystemRuntime<TSystemRegistry>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n } & OutputArg<TExpressionEvent>\n) => ContextPatch<TContextShape, TTargetContextShape, TResolvedTargetContext>;\n\ntype StateTransitionContextOrMapper<\n TContext extends MachineContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> =\n | ContextPatch<TContextShape, TTargetContextShape, TResolvedTargetContext>\n | StateTransitionContextMapper<\n TContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n\ntype StateTransitionContext<\n TAllowMapper extends boolean,\n TContext extends MachineContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry\n> = TAllowMapper extends true\n ? StateTransitionContextOrMapper<\n TContext,\n TContextShape,\n TTargetContextShape,\n TResolvedTargetContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >\n : ContextPatch<TContextShape, TTargetContextShape, TResolvedTargetContext>;\n\ntype StateTransitionFunction<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TInput = undefined\n> = (\n args: {\n context: TContext;\n event: TExpressionEvent;\n self: AnyActorRef;\n parent: AnyActorRef | undefined;\n value: StateValue;\n children: TChildren;\n system: SystemRuntime<TSystemRegistry>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n input: TInput;\n } & OutputArg<TExpressionEvent>,\n enq: EnqueueObject<TEvent, TEmitted, TSystemRegistry, TActorMap>\n) => StateTransitionResult<\n TStateSchemas,\n TContext,\n TContextShape,\n TMeta,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry,\n false\n> | void;\n\ntype StateTransitionResult<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TContextShape,\n TMeta extends MetaObject,\n TExpressionEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TSystemRegistry extends SystemRegistry,\n TAllowContextMapper extends boolean\n> =\n | {\n target?: never;\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n TContextShape,\n TContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n reenter?: boolean;\n meta?: TMeta;\n }\n | {\n [K in keyof TStateSchemas & string]: {\n target: K;\n reenter?: boolean;\n meta?: TMeta;\n input?:\n | StateInput<TStateSchemas[K]>\n | ((\n args: {\n context: TContext;\n event: EventObject;\n } & OutputArg<EventObject>\n ) => StateInput<TStateSchemas[K]>);\n } & ([TContextShape] extends [\n StateContextShape<TStateSchemas[K], TContextShape>\n ]\n ? {\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n StateContextShape<TStateSchemas[K], TContextShape>,\n StateContext<TStateSchemas[K], TContext>,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n }\n : {\n context: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n StateContextShape<TStateSchemas[K], TContextShape>,\n StateContext<TStateSchemas[K], TContext>,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n });\n }[keyof TStateSchemas & string]\n | {\n target: Exclude<\n SetupStateTarget<TStateSchemas>,\n keyof TStateSchemas & string\n >;\n context?: StateTransitionContext<\n TAllowContextMapper,\n TContext,\n TContextShape,\n TContextShape,\n TContext,\n TExpressionEvent,\n TChildren,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TSystemRegistry\n >;\n reenter?: boolean;\n meta?: TMeta;\n };\n\ntype ContextPatch<\n TCurrentContext,\n TTargetContext,\n TResolvedTargetContext extends MachineContext\n> = Compute<\n Partial<TResolvedTargetContext> &\n Pick<\n TResolvedTargetContext,\n Extract<RequiredContextKeys<TCurrentContext, TTargetContext>, string>\n > & {\n call?: never;\n apply?: never;\n bind?: never;\n }\n>;\n\ntype RequiredContextKeys<TCurrentContext, TTargetContext> = {\n [K in keyof TTargetContext]-?: K extends keyof TCurrentContext\n ? [TCurrentContext[K]] extends [TTargetContext[K]]\n ? never\n : K\n : K;\n}[keyof TTargetContext];\n\n/** Initial transition with typed input based on target state */\ntype InitialTransitionWithInput<\n TStateSchemas extends Record<string, SetupStateSchema>,\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in keyof TStateSchemas & string]: {\n target: K;\n input?:\n | StateInput<TStateSchemas[K]>\n | ((args: {\n context: TContext;\n event: TEvent;\n }) => StateInput<TStateSchemas[K]>);\n };\n}[keyof TStateSchemas & string];\n\n/** Return type of setup() */\nexport interface SetupReturn<\n TStates extends Record<string, SetupStateSchema> = Record<\n string,\n SetupStateSchema\n >,\n TSchemas extends SetupSchemas = {},\n TSetupActionMap extends Sources['actions'] = {},\n TSetupActorMap extends Sources['actors'] = {},\n TSetupGuardMap extends Sources['guards'] = {},\n TSetupDelayMap extends Sources['delays'] = {},\n TSetupDelays extends string = Extract<keyof TSetupDelayMap, string>,\n TSystemRegistry extends SystemRegistry = SystemRegistry,\n TValidator extends ActorLogicValidator | undefined = undefined\n> {\n /** Extends the setup configuration */\n extend<\n const TExtendSchemas extends SetupSchemas = {},\n const TExtendStates extends Record<string, SetupStateSchema> = {},\n TExtendActionMap extends Sources['actions'] = {},\n TExtendActorMap extends Sources['actors'] = {},\n TExtendGuardMap extends Sources['guards'] = {},\n TExtendDelayMap extends Sources['delays'] = {},\n const TExtendValidator extends\n | ActorLogicValidator\n | undefined\n | InheritedValidator = InheritedValidator\n >(\n config: SetupExtensionConfig<\n TSchemas,\n TStates,\n TValidator,\n TExtendSchemas,\n TExtendStates,\n TExtendActionMap,\n TExtendActorMap,\n TExtendGuardMap,\n TExtendDelayMap,\n TExtendValidator\n >\n ): SetupReturn<\n MergeSourceMaps<TStates, TExtendStates>,\n MergeSourceMaps<TSchemas, TExtendSchemas>,\n MergeSourceMaps<TSetupActionMap, TExtendActionMap>,\n MergeSourceMaps<TSetupActorMap, TExtendActorMap>,\n MergeSourceMaps<TSetupGuardMap, TExtendGuardMap>,\n MergeSourceMaps<TSetupDelayMap, TExtendDelayMap>,\n TSetupDelays | Extract<keyof TExtendDelayMap, string>,\n TSystemRegistry,\n ResolveExtendedValidator<TValidator, TExtendValidator>\n >;\n\n /** Creates a state machine with the setup configuration */\n createMachine<\n TContextSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TEventSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {},\n TEmittedSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1 = StandardSchemaV1,\n TTagSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TActionSchemaMap extends ActionSchemas = {},\n const TGuardSchemaMap extends GuardSchemas = {},\n _TEvent extends EventObject = EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TActionMap extends Sources['actions'] = {},\n TActorMap extends Sources['actors'] = {},\n TGuardMap extends Sources['guards'] = {},\n TDelayMap extends Sources['delays'] = {},\n TDelays extends string = Extract<keyof TDelayMap, string>,\n TTag extends SetupTags<TSchemas, TTagSchema> = SetupTags<\n TSchemas,\n TTagSchema\n >,\n TInput = unknown,\n const TStateKeys extends string = SetupStateKey<TStates>,\n TConfig extends SetupMachineConfig<\n TStates,\n TStateKeys,\n TSchemas,\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n SetupContext<TSchemas, TContextSchema>,\n SetupEvents<TSchemas, TEventSchemaMap, TInternalEventSchemaMap>,\n Cast<\n MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TSetupDelays | TDelays,\n TTag,\n SetupEmitted<TSchemas, TEmittedSchemaMap>,\n SetupMeta<TSchemas, TMetaSchema>,\n MergeSourceMaps<\n SetupActions<TSchemas, TSetupActionMap>,\n MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>\n >,\n MergeSourceMaps<TSetupActorMap, TActorMap>,\n MergeSourceMaps<\n SetupGuards<TSchemas, TSetupGuardMap>,\n MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>\n >,\n MergeSourceMaps<TSetupDelayMap, TDelayMap>,\n TSystemRegistry,\n SetupContextRequired<TSchemas, TContextSchema>,\n TDelays,\n TActionMap,\n TActorMap,\n TGuardMap\n > = SetupMachineConfig<\n TStates,\n TStateKeys,\n TSchemas,\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n SetupContext<TSchemas, TContextSchema>,\n SetupEvents<TSchemas, TEventSchemaMap, TInternalEventSchemaMap>,\n Cast<\n MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TSetupDelays | TDelays,\n TTag,\n SetupEmitted<TSchemas, TEmittedSchemaMap>,\n SetupMeta<TSchemas, TMetaSchema>,\n MergeSourceMaps<\n SetupActions<TSchemas, TSetupActionMap>,\n MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>\n >,\n MergeSourceMaps<TSetupActorMap, TActorMap>,\n MergeSourceMaps<\n SetupGuards<TSchemas, TSetupGuardMap>,\n MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>\n >,\n MergeSourceMaps<TSetupDelayMap, TDelayMap>,\n TSystemRegistry,\n SetupContextRequired<TSchemas, TContextSchema>,\n TDelays,\n TActionMap,\n TActorMap,\n TGuardMap\n >\n >(\n config: {\n schemas?: {\n events?: TEventSchemaMap;\n internalEvents?: TInternalEventSchemaMap;\n context?: TContextSchema;\n emitted?: TEmittedSchemaMap;\n actions?: TActionSchemaMap;\n guards?: TGuardSchemaMap;\n input?: TInputSchema;\n output?: TOutputSchema;\n meta?: TMetaSchema;\n tags?: TTagSchema;\n children?: TChildrenSchemaMap;\n } & ([TValidator] extends [ActorLogicValidator]\n ? ValidateSetupSchemas<\n InlineMachineSchemas<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TActionSchemaMap,\n TGuardSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap\n >\n >\n : unknown);\n actions?: TActionMap;\n actors?: TActorMap;\n guards?: TGuardMap;\n delays?: TDelayMap;\n states?: Record<TStateKeys, unknown>;\n } & TConfig &\n RuntimeValidationConstraint<\n NoInfer<MachineConfigSchemas<TConfig>>,\n NoInfer<MachineConfigStates<TConfig>>,\n TValidator\n > &\n ValidateSetupDelayReferences<TConfig, TSetupDelays> &\n ValidateHistoryDefaults<TConfig> &\n ValidateStateTargets<TConfig> &\n ValidateRegistryKeys<\n TConfig,\n TSystemRegistry,\n MergeSourceMaps<TSetupActorMap, TActorMap>\n >\n ): StateMachine<\n SetupContext<TSchemas, TContextSchema>,\n | SetupEvents<TSchemas, TEventSchemaMap, TInternalEventSchemaMap>\n | ([RoutableStateId<Cast<TConfig, StateSchema>>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<Cast<TConfig, StateSchema>>;\n }),\n Cast<\n MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<\n MergeStateSchema<\n Cast<TConfig, StateSchema>,\n SetupStatesToStateSchema<TStates>\n >\n >,\n TTag & string,\n [SetupSchema<TSchemas, 'input'>] extends [never]\n ? TInput\n : SetupInput<TSchemas, TInputSchema>,\n SetupOrConfigOutput<TSchemas, TOutputSchema, TConfig>,\n SetupEmitted<TSchemas, TEmittedSchemaMap>,\n SetupMeta<TSchemas, TMetaSchema>,\n MergeStateSchema<\n Cast<TConfig, StateSchema>,\n SetupStatesToStateSchema<TStates>\n >,\n MergeSourceMaps<\n SetupActions<TSchemas, TSetupActionMap>,\n MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>\n >,\n MergeSourceMaps<TSetupActorMap, TActorMap>,\n MergeSourceMaps<\n SetupGuards<TSchemas, TSetupGuardMap>,\n MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>\n >,\n DelayMapFromNames<\n TSetupDelays | TDelays,\n MergeSourceMaps<TSetupDelayMap, TDelayMap>\n >,\n SetupInternalEvents<TSchemas, TInternalEventSchemaMap>\n > &\n MachineIdentity<TConfig>;\n\n /**\n * Creates a state node config bound to a specific setup-declared state,\n * addressed by a dotted path (e.g. `'loading'` or `'parent.child'`). The\n * addressed state's own `input` schema is typed inside `entry`/`exit` args.\n */\n createStateConfig<\n const TPath extends StatePaths<TStates>,\n const TConfig extends SetupStateNodeConfig<\n ResolveStateSiblings<TStates, TPath>,\n ResolveStatePath<TStates, TPath>,\n TSchemas,\n TSetupActionMap,\n TSetupActorMap,\n TSetupGuardMap,\n TSetupDelayMap,\n TSystemRegistry\n >\n >(\n path: TPath,\n config: TConfig\n ): TConfig;\n\n /** Creates a state node config with the setup configuration */\n createStateConfig<\n const TConfig extends SetupStateNodeConfig<\n TStates,\n SetupStateSchema,\n TSchemas,\n TSetupActionMap,\n TSetupActorMap,\n TSetupGuardMap,\n TSetupDelayMap,\n TSystemRegistry\n >\n >(\n config: TConfig\n ): TConfig;\n\n /** State input schemas from setup config */\n states: TStates;\n\n /** Schemas from setup config */\n schemas: TSchemas;\n}\n\ntype SetupConfigSchemas<TConfig> = TConfig extends { schemas?: infer TSchemas }\n ? TSchemas extends SetupSchemas\n ? TSchemas\n : {}\n : {};\n\ntype SetupConfigStates<TConfig> = TConfig extends { states?: infer TStates }\n ? TStates extends Record<string, SetupStateSchema>\n ? TStates\n : Record<string, SetupStateSchema>\n : Record<string, SetupStateSchema>;\n\ntype SetupConfigActions<TConfig> = TConfig extends { actions?: infer TActions }\n ? TActions extends Sources['actions']\n ? MergeSourceMaps<SetupActions<SetupConfigSchemas<TConfig>, {}>, TActions>\n : SetupActions<SetupConfigSchemas<TConfig>, {}>\n : SetupActions<SetupConfigSchemas<TConfig>, {}>;\n\ntype SetupConfigActors<TConfig> = TConfig extends {\n actors?: infer TActors;\n}\n ? TActors extends Sources['actors']\n ? TActors\n : {}\n : {};\n\ntype SetupConfigGuards<TConfig> = TConfig extends { guards?: infer TGuards }\n ? TGuards extends Sources['guards']\n ? MergeSourceMaps<SetupGuards<SetupConfigSchemas<TConfig>, {}>, TGuards>\n : SetupGuards<SetupConfigSchemas<TConfig>, {}>\n : SetupGuards<SetupConfigSchemas<TConfig>, {}>;\n\ntype SetupConfigDelays<TConfig> = TConfig extends { delays?: infer TDelays }\n ? TDelays extends Sources['delays']\n ? TDelays\n : {}\n : {};\n\nexport type SetupReturnFromConfig<\n TConfig extends AnySetupConfig,\n TSystemRegistry extends SystemRegistry = SystemRegistry\n> = SetupReturn<\n SetupConfigStates<TConfig>,\n SetupConfigSchemas<TConfig>,\n SetupConfigActions<TConfig>,\n SetupConfigActors<TConfig>,\n SetupConfigGuards<TConfig>,\n SetupConfigDelays<TConfig>,\n Extract<keyof SetupConfigDelays<TConfig>, string>,\n TSystemRegistry,\n TConfig extends { validator: infer TValidator extends ActorLogicValidator }\n ? TValidator\n : undefined\n>;\n\ntype SetupFunction<TSystemRegistry extends SystemRegistry = SystemRegistry> = {\n (): SetupReturn<\n Record<string, SetupStateSchema>,\n {},\n {},\n {},\n {},\n {},\n never,\n TSystemRegistry\n >;\n <\n const TSchemas extends SetupSchemas = {},\n const TStates extends Record<string, SetupStateSchema> = Record<\n string,\n SetupStateSchema\n >,\n TActionMap extends Sources['actions'] = {},\n TActorMap extends Sources['actors'] = {},\n TGuardMap extends Sources['guards'] = {},\n TDelayMap extends Sources['delays'] = {},\n const TValidator extends ActorLogicValidator | undefined = undefined\n >(\n config: SetupConfig<\n TSchemas,\n TStates,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TValidator\n > &\n RuntimeValidationConstraint<\n NoInfer<TSchemas>,\n NoInfer<TStates>,\n TValidator\n >\n ): SetupReturn<\n TStates,\n TSchemas,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n Extract<keyof TDelayMap, string>,\n TSystemRegistry,\n TValidator\n >;\n <const TConfig extends AnySetupConfig>(\n config: TConfig &\n SetupSourceCompanions<SetupConfigSchemas<TConfig>> &\n RuntimeValidationConstraint<\n NoInfer<SetupConfigSchemas<TConfig>>,\n NoInfer<SetupConfigStates<TConfig>>,\n TConfig extends { validator: infer TValidator } ? TValidator : undefined\n >\n ): SetupReturnFromConfig<TConfig, TSystemRegistry>;\n};\n\n/**\n * Sets up a state machine with state input schemas and other configuration.\n *\n * @example\n *\n * ```ts\n * import { setup } from 'xstate';\n * import z from 'zod';\n *\n * const s = setup({\n * states: {\n * loading: {\n * schemas: {\n * input: z.object({\n * userId: z.string()\n * })\n * }\n * }\n * }\n * });\n *\n * const machine = s.createMachine({\n * initial: {\n * target: 'loading',\n * input: { userId: '123' }\n * },\n * states: {\n * loading: {\n * entry: ({ input }) => {\n * console.log(input.userId);\n * }\n * }\n * }\n * });\n * ```\n */\nexport const setup = function setupImplementation<\n const TSchemas extends SetupSchemas = {},\n const TStates extends Record<string, SetupStateSchema> = Record<\n string,\n SetupStateSchema\n >,\n TActionMap extends Sources['actions'] = {},\n TActorMap extends Sources['actors'] = {},\n TGuardMap extends Sources['guards'] = {},\n TDelayMap extends Sources['delays'] = {},\n TValidator extends ActorLogicValidator | undefined =\n | ActorLogicValidator\n | undefined\n>(\n config: SetupConfig<\n TSchemas,\n TStates,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TValidator\n > = {}\n): SetupReturn<\n TStates,\n TSchemas,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n Extract<keyof TDelayMap, string>,\n SystemRegistry,\n TValidator\n> {\n const {\n validator,\n states = {} as TStates,\n schemas,\n actions,\n actors,\n guards,\n delays\n } = config;\n\n return {\n extend<\n const TExtendSchemas extends SetupSchemas = {},\n const TExtendStates extends Record<string, SetupStateSchema> = {},\n TExtendActionMap extends Sources['actions'] = {},\n TExtendActorMap extends Sources['actors'] = {},\n TExtendGuardMap extends Sources['guards'] = {},\n TExtendDelayMap extends Sources['delays'] = {},\n const TExtendValidator extends\n | ActorLogicValidator\n | undefined\n | InheritedValidator = InheritedValidator\n >(\n extension: SetupExtensionConfig<\n TSchemas,\n TStates,\n TValidator,\n TExtendSchemas,\n TExtendStates,\n TExtendActionMap,\n TExtendActorMap,\n TExtendGuardMap,\n TExtendDelayMap,\n TExtendValidator\n >\n ) {\n return setup(\n mergeSetupConfigs(config, extension as AnySetupConfig) as any\n ) as unknown as SetupReturn<\n MergeSourceMaps<TStates, TExtendStates>,\n MergeSourceMaps<TSchemas, TExtendSchemas>,\n MergeSourceMaps<TActionMap, TExtendActionMap>,\n MergeSourceMaps<TActorMap, TExtendActorMap>,\n MergeSourceMaps<TGuardMap, TExtendGuardMap>,\n MergeSourceMaps<TDelayMap, TExtendDelayMap>,\n | Extract<keyof TDelayMap, string>\n | Extract<keyof TExtendDelayMap, string>,\n SystemRegistry,\n ResolveExtendedValidator<TValidator, TExtendValidator>\n >;\n },\n createMachine(machineConfig) {\n const configSchemas = machineConfig.schemas;\n const mergedSchemas = mergeSchemas(configSchemas, schemas);\n const mergedStates = mergeStateSchemas(machineConfig.states, states);\n const mergedActions = mergeMaps(actions, machineConfig.actions);\n const mergedActors = mergeMaps(actors, machineConfig.actors);\n const mergedGuards = mergeMaps(guards, machineConfig.guards);\n const mergedDelays = mergeMaps(delays, machineConfig.delays);\n\n return new StateMachine(\n {\n ...machineConfig,\n ...(mergedSchemas ? { schemas: mergedSchemas } : undefined),\n ...(mergedStates ? { states: mergedStates } : undefined),\n ...(mergedActions ? { actions: mergedActions } : undefined),\n ...(mergedActors ? { actors: mergedActors } : undefined),\n ...(mergedGuards ? { guards: mergedGuards } : undefined),\n ...(mergedDelays ? { delays: mergedDelays } : undefined)\n } as any,\n undefined,\n validator\n ) as any;\n },\n createStateConfig(...args: unknown[]) {\n return args.length > 1 ? args[1] : args[0];\n },\n states,\n schemas: schemas ?? ({} as TSchemas)\n };\n} as SetupFunction;\n\ntype SystemBuilder<TSystemRegistry extends SystemRegistry> = {\n createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: Omit<ActorOptions<TLogic>, 'registryKey'> & {\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n } & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n ): Actor<TLogic>;\n get: SystemRuntime<TSystemRegistry>['get'];\n getAll: SystemRuntime<TSystemRegistry>['getAll'];\n inspect(\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription;\n setup: SetupFunction<TSystemRegistry>;\n};\n\nexport function createSystem<const TSystemRegistry extends SystemRegistry = {}>(\n _config: SystemConfig<TSystemRegistry> = {}\n): SystemBuilder<TSystemRegistry> {\n const runtimeRef: { current?: AnyActorSystem } = {};\n const pendingObservers: Array<{\n observer: Parameters<AnyActorSystem['inspect']>[0];\n subscription?: Subscription;\n active: boolean;\n }> = [];\n\n const flushObservers = () => {\n const runtime = runtimeRef.current;\n if (!runtime) {\n return;\n }\n\n for (const entry of pendingObservers) {\n if (entry.active && !entry.subscription) {\n entry.subscription = runtime.inspect(entry.observer);\n }\n }\n };\n\n return {\n createActor(logic, options) {\n const actor = createActorFromLogic(logic, {\n ...options,\n _systemRef: runtimeRef\n } as any);\n flushObservers();\n return actor as any;\n },\n get(key) {\n return runtimeRef.current?.get(key as any);\n },\n getAll() {\n return (runtimeRef.current?.getAll() ?? {}) as Partial<\n SystemActorMap<TSystemRegistry>\n >;\n },\n inspect(observer) {\n const runtime = runtimeRef.current;\n\n if (runtime) {\n return runtime.inspect(observer as any);\n }\n\n const entry: (typeof pendingObservers)[number] = {\n observer: observer as Parameters<AnyActorSystem['inspect']>[0],\n active: true\n };\n pendingObservers.push(entry);\n\n return {\n unsubscribe() {\n entry.active = false;\n entry.subscription?.unsubscribe();\n }\n };\n },\n setup: setup as SetupFunction<TSystemRegistry>\n };\n}\n\nfunction mergeMaps<TLeft, TRight>(\n left: TLeft | undefined,\n right: TRight | undefined\n): (TLeft & TRight) | undefined {\n return left || right ? ({ ...left, ...right } as TLeft & TRight) : undefined;\n}\n\nfunction mergeSchemas(\n left: SetupSchemas | undefined,\n right: SetupSchemas | undefined\n): SetupSchemas | undefined {\n if (!left && !right) {\n return undefined;\n }\n\n return {\n ...left,\n ...right,\n events: mergeMaps(left?.events, right?.events),\n internalEvents: mergeMaps(left?.internalEvents, right?.internalEvents),\n actions: mergeMaps(left?.actions, right?.actions),\n guards: mergeMaps(left?.guards, right?.guards),\n emitted: mergeMaps(left?.emitted, right?.emitted),\n children: mergeMaps(left?.children, right?.children)\n };\n}\n\n/**\n * Setup schemas win over inline config schemas (same precedence as root\n * `mergeSchemas`); setup states with no matching config state are skipped.\n */\nfunction mergeStateSchemas(\n configStates: Record<string, SetupStateSchema> | undefined,\n setupStates: Record<string, SetupStateSchema> | undefined\n): Record<string, SetupStateSchema> | undefined {\n if (!configStates || !setupStates) {\n return configStates;\n }\n\n return Object.fromEntries(\n Object.entries(configStates).map(([key, configState]) => {\n const setupState = setupStates[key];\n\n if (!setupState) {\n return [key, configState];\n }\n\n const schemas = mergeMaps(configState.schemas, setupState.schemas);\n const states = mergeStateSchemas(configState.states, setupState.states);\n\n return [\n key,\n {\n ...configState,\n ...(schemas ? { schemas } : undefined),\n ...(states ? { states } : undefined)\n }\n ];\n })\n );\n}\n\nfunction mergeSetupConfigs<\n TBase extends SetupConfig<any, any, any, any, any, any>,\n TExtension extends SetupConfig<any, any, any, any, any, any>\n>(base: TBase, extension: TExtension): TBase & TExtension {\n return {\n ...base,\n ...extension,\n schemas: mergeSchemas(base.schemas, extension.schemas),\n states: mergeMaps(base.states, extension.states),\n actions: mergeMaps(base.actions, extension.actions),\n actors: mergeMaps(base.actors, extension.actors),\n guards: mergeMaps(base.guards, extension.guards),\n delays: mergeMaps(base.delays, extension.delays)\n } as TBase & TExtension;\n}\n","import type { MachineSnapshot } from './State.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { AsyncActorLogic } from './actors/promise.ts';\nimport type { Actor, ProcessingStatus } from './createActor.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport { Spawner } from './spawn.ts';\nimport type { ActorSystemRuntime, AnyActorSystem, Clock } from './system.ts';\n\n// this is needed to make JSDoc `@link` work properly\n// oxlint-disable-next-line no-unused-vars\nimport type { SimulatedClock } from './SimulatedClock.ts';\nimport { Sources, Next_StateNodeConfig } from './types.v6.ts';\nimport { StandardSchemaV1 } from './schema.types.ts';\nimport { builtInActions } from './actions.ts';\n\nexport type Identity<T> = { [K in keyof T]: T[K] };\n\nexport type HomomorphicPick<T, K extends keyof any> = {\n [P in keyof T as P & K]: T[P];\n};\nexport type HomomorphicOmit<T, K extends keyof any> = {\n [P in keyof T as Exclude<P, K>]: T[P];\n};\n\nexport type Invert<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n\nexport type GetParameterizedParams<T extends ParameterizedObject | undefined> =\n T extends any ? ('params' extends keyof T ? T['params'] : undefined) : never;\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\nexport type NonReducibleUnknown = {} | null | undefined;\nexport type AnyFunction = (...args: any[]) => any;\n\ntype ReturnTypeOrValue<T> = T extends AnyFunction ? ReturnType<T> : T;\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNotNever<T> = [T] extends [never] ? false : true;\n\nexport type Compute<A> = { [K in keyof A]: A[K] } & unknown;\nexport type Prop<T, K> = K extends keyof T ? T[K] : never;\nexport type Values<T> = T[keyof T];\nexport type Elements<T> = T[keyof T & `${number}`];\nexport type Merge<M, N> = Omit<M, keyof N> & N;\nexport type IndexByProp<T extends Record<P, string>, P extends keyof T> = {\n [E in T as E[P]]: E;\n};\n\nexport type IndexByType<T extends { type: string }> = IndexByProp<T, 'type'>;\n\nexport type IsEmptyObject<T> = keyof T extends never ? true : false;\n\nexport type Equals<A1, A2> =\n (<A>() => A extends A2 ? true : false) extends <A>() => A extends A1\n ? true\n : false\n ? true\n : false;\nexport type IsAny<T> = Equals<T, any>;\nexport type Cast<A, B> = A extends B ? A : B;\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\nexport type DoNotInfer<T> = [T][T extends any ? 0 : any];\n/** @deprecated Use the built-in `NoInfer` type instead */\nexport type NoInfer<T> = DoNotInfer<T>;\nexport type LowInfer<T> = T & NonNullable<unknown>;\n\nexport type MetaObject = Record<string, any>;\n\nexport type Lazy<T> = () => T;\nexport type MaybeLazy<T> = T | Lazy<T>;\n\n/** The full definition of an event, with a string `type`. */\nexport type EventObject = {\n /** The type of event that is sent. */\n type: string;\n};\n\nexport type EventPayloadPattern<TEvent extends EventObject> = TEvent extends any\n ? Partial<Omit<TEvent, 'type'>>\n : never;\n\nexport interface AnyEventObject extends EventObject {\n [key: string]: any;\n}\n\nexport interface ParameterizedObject {\n type: string;\n params?: NonReducibleUnknown;\n}\n\nexport type UnifiedArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = {\n context: TContext;\n event: TExpressionEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n system: AnyActorSystem;\n} & OutputArg<TExpressionEvent>;\n\nexport type MachineContext = Record<string, any>;\n\ntype DoneEventType = 'xstate.done.actor' | 'xstate.done.state';\n\nexport type OutputArg<TEvent extends EventObject> = TEvent extends {\n type: DoneEventType;\n output: infer TOutput;\n}\n ? { output: TOutput }\n : { output: undefined };\n\nexport type ActionArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = UnifiedArg<TContext, TExpressionEvent, TEvent> & {\n children: Record<string, AnyActor>;\n};\n\nexport type InputFrom<T> =\n // Resolve the actor-logic contract first. Setup-created machines intersect\n // StateMachine with literal identity metadata; inferring StateMachine's\n // generic parameters through that intersection widens optional input.\n T extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TInput\n : T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TInput\n : never;\n\nexport type OutputFrom<T> =\n T extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? (TSnapshot & { status: 'done' })['output']\n : T extends ActorRef<infer TSnapshot, infer _TEvent, infer _TEmitted>\n ? (TSnapshot & { status: 'done' })['output']\n : never;\n\nexport type NoRequiredParams<T extends ParameterizedObject> = T extends any\n ? undefined extends T['params']\n ? T['type']\n : never\n : never;\n\nexport type ConditionalRequired<\n T,\n Condition extends boolean\n> = Condition extends true ? Required<T> : T;\n\nexport type WithDynamicParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n T extends ParameterizedObject\n> = T extends any\n ? ConditionalRequired<\n {\n type: T['type'];\n params?:\n | T['params']\n | (({\n context,\n event,\n output\n }: {\n context: TContext;\n event: TExpressionEvent;\n } & OutputArg<TExpressionEvent>) => T['params']);\n },\n undefined extends T['params'] ? false : true\n >\n : never;\n\nexport type StateKey = string | AnyMachineSnapshot;\n\nexport interface StateValueMap {\n [key: string]: StateValue | undefined;\n}\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\nexport type StateValue = string | StateValueMap;\n\nexport type TransitionTarget = SingleOrArray<string>;\n\nexport type TransitionContextPatch<TContext extends MachineContext> =\n Partial<TContext> & {\n call?: never;\n apply?: never;\n bind?: never;\n };\n\nexport type TransitionContextMapper<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n) => TransitionContextPatch<_TCtx>;\n\nexport interface TransitionConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n actions?: never;\n /** A shallow partial event pattern that must match before guards run. */\n matches?: EventPayloadPattern<TExpressionEvent>;\n guard?: unknown;\n reenter?: boolean;\n target?: TransitionTarget | undefined;\n context?:\n | TransitionContextPatch<TContext>\n | TransitionContextMapper<\n TContext,\n TExpressionEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n to?: TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >;\n meta?: TMeta;\n description?: string;\n /** @internal Overrides transition-domain selection for compiled formats. */\n _transitionDomain?: 'internal' | 'external';\n}\n\nexport interface InitialTransitionConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> extends TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n> {\n target: string;\n}\n\nexport type AnyTransitionConfig = TransitionConfig<\n any, // TContext\n any, // TExpressionEvent\n any, // TEvent\n any, // TEmitted\n any, // TMeta\n any, // TActionMap\n any, // TActorMap\n any, // TGuardMap\n any // TDelayMap\n>;\n\nexport interface InvokeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n id: string;\n\n registryKey: string | undefined;\n\n logic:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: TActorMap;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n /** The source of the actor logic to be invoked */\n src: AnyActorLogic | string;\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its final\n * top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an error\n * event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The duration (in ms) after which this invocation times out if it has not\n * completed.\n */\n timeout?: number | ((args: { context: TContext; event: TEvent }) => number);\n /** The transition to take when the invoke-level `timeout` expires. */\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n}\n\nexport type AnyInvokeDefinition = InvokeDefinition<\n MachineContext,\n EventObject,\n EventObject,\n MetaObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n>;\n\ntype Delay<TDelay extends string> = TDelay | number;\n\nexport type DelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in Delay<keyof TDelayMap & string>]?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >\n | TransitionConfigFunction<\n TContext,\n TEvent,\n TEvent,\n TODO,\n any,\n any,\n any,\n any,\n any\n >;\n};\n\nexport type StateTypes =\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'choice'\n | 'history'\n | ({} & string);\n\nexport type SingleOrArray<T> = readonly T[] | T;\n\nexport type StateNodesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNode<TContext, TEvent>;\n};\n\nexport type TransitionConfigTarget = string | undefined;\n\nexport type TransitionConfigOrTarget<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = SingleOrArray<\n | TransitionConfigTarget\n | TransitionConfig<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n | TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >\n>;\n\nexport type TransitionConfigFunction<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TMeta extends MetaObject,\n TInput = undefined,\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & { input: TInput },\n enq: EnqueueObject<TEvent, TEmitted, SystemRegistry, TActorMap>\n) => {\n target?: string | string[];\n // target?: keyof TSS['states'];\n context?: TransitionContextPatch<_TCtx>;\n reenter?: boolean;\n meta?: TMeta;\n input?: Record<string, unknown>;\n} | void;\n\ntype TransitionFunctionArgs<\n TContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n context: TContext;\n event: TCurrentEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n parent: UnknownActorRef | undefined;\n value: StateValue;\n children: Record<string, AnyActor>;\n system: AnyActorSystem;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n} & OutputArg<TCurrentEvent>;\n\nexport type AnyTransitionConfigFunction = TransitionConfigFunction<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type TransitionsConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in EventDescriptor<TEvent>]?: TransitionConfigOrTarget<\n TContext,\n ExtractEvent<TEvent, K>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n};\n\ntype PartialEventDescriptor<TEventType extends string> =\n TEventType extends `${infer TLeading}.${infer TTail}`\n ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}`\n : never;\n\nexport type EventDescriptor<TEvent extends EventObject> =\n | TEvent['type']\n | PartialEventDescriptor<TEvent['type']>\n | '*';\n\nexport type NormalizeDescriptor<TDescriptor extends string> =\n TDescriptor extends '*'\n ? string\n : TDescriptor extends `${infer TLeading}.*`\n ? `${TLeading}.${string}`\n : TDescriptor;\n\ntype EventTypeMatchesDescriptor<\n TEventType extends string,\n TDescriptor extends string\n> = TEventType extends NormalizeDescriptor<TDescriptor> ? true : false;\n\ntype IsInternalEventType<\n TEventType extends string,\n TDescriptors extends string\n> =\n // Descriptors that collapsed to broad `string` (an untyped machine's\n // config) cannot classify anything: without the guard they would match\n // every event type and reduce the sendable events to `never`.\n string extends TDescriptors\n ? false\n : true extends (\n TDescriptors extends any\n ? EventTypeMatchesDescriptor<TEventType, TDescriptors>\n : never\n )\n ? true\n : false;\n\ntype ExcludeInternalEvents<\n TEvent extends EventObject,\n TDescriptors extends string\n> = TEvent extends any\n ? IsInternalEventType<TEvent['type'], TDescriptors> extends true\n ? never\n : TEvent\n : never;\n\ntype InternalEventDescriptorsFromConfig<\n TEvent extends EventObject,\n TConfig\n> = TConfig extends { internalEvents?: readonly EventDescriptor<TEvent>[] }\n ? TConfig['internalEvents'] extends readonly (infer TDesc)[]\n ? Extract<TDesc, string>\n : never\n : never;\n\ntype InternalEventTypes<TInternalEvent extends EventObject> =\n TInternalEvent extends any ? TInternalEvent['type'] : never;\n\ntype SendableEventFromMachine<\n TEvent extends EventObject,\n TInternalEvent extends EventObject,\n TConfig\n> =\n IsAny<TInternalEvent> extends true\n ? TEvent\n : ExcludeInternalEvents<\n TEvent,\n | InternalEventTypes<TInternalEvent>\n | InternalEventDescriptorsFromConfig<TEvent, TConfig>\n >;\n\nexport type IsLiteralString<T extends string> = string extends T ? false : true;\n\ntype ActorsBySrc<TActor extends ProvidedActor> = {\n [A in TActor as A['src']]: A['logic'];\n};\n\ntype DistributeActors<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n _TAction extends ParameterizedObject,\n _TGuard extends ParameterizedObject,\n _TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TSpecificActor extends ProvidedActor\n> = TSpecificActor extends { src: infer TSrc }\n ?\n | Compute<\n {\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | TSrc\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => TSrc | TSpecificActor['logic']);\n\n /**\n * The unique identifier for the invoked machine. If not specified,\n * this will be the machine's own `id`, or the URL (from `src`).\n */\n id?: TSpecificActor['id'];\n\n // TODO: currently we do not enforce required inputs here\n // in a sense, we shouldn't - they could be provided within the `sources` object\n // how do we verify if the required input has been provided?\n input?:\n | Mapper<\n TContext,\n TEvent,\n InputFrom<TSpecificActor['logic']>,\n TEvent\n >\n | InputFrom<TSpecificActor['logic']>;\n /**\n * The transition to take upon the invoked child machine reaching\n * its final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<OutputFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent<SnapshotFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n } & { [K in RequiredActorOptions<TSpecificActor>]: unknown }\n >\n | {\n id?: never;\n registryKey?: string;\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n }\n : never;\n\nexport type InvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta,\n TActor\n >\n : {\n /**\n * The unique identifier for the invoked machine. If not specified, this\n * will be the machine's own `id`, or the URL (from `src`).\n */\n id?: string;\n\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its\n * final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n };\n\nexport type AnyInvokeConfig = InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TMeta\n>;\n\nexport type AnyStateNodeConfig = Next_StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n// Accept any StateNode instance regardless of generic parameters\n// Using a union type to handle variance issues with machine.resolveState\nexport type AnyStateNode =\n | StateNode<any, any>\n | StateNode<never, EventObject>\n | StateNode<any, EventObject>\n | StateNode<never, any>;\n\ntype LoosenMachineSnapshot<TSnapshot> =\n TSnapshot extends MachineSnapshot<any, any, any, any, any, any, any, any>\n ? Omit<TSnapshot, 'matches' | 'can'> & {\n matches(partialStateValue: StateValue): boolean;\n can(event: any): boolean;\n }\n : never;\n\nexport type AnyMachineSnapshot = LoosenMachineSnapshot<\n MachineSnapshot<any, any, any, any, any, any, any, any>\n>;\n\nexport interface AnyStateMachine extends AnyActorLogic {\n id: string;\n root: AnyStateNode;\n /** @internal */\n _hasEventlessTransitions?: boolean;\n /** @internal */\n idMap: Map<string, AnyStateNode>;\n options?: { maxIterations?: number };\n states: StateNodesConfig<any, any>;\n events: Array<EventDescriptor<any>>;\n sources: Sources;\n config: any;\n version?: string;\n schemas?: import('./types.v6.ts').AnyMachineSchemas;\n snapshotSchema: import('./machineVersion.types.ts').MachineSnapshotSchema;\n eventSchema: import('./machineVersion.types.ts').MachineEventSchema;\n provide(sources: any): AnyStateMachine;\n resolveState(config: any): any;\n /** @internal */\n _getPreInitialState(actorScope: AnyActorScope, initEvent: EventObject): any;\n getTransitionData(\n snapshot: any,\n event: any,\n actorScope: AnyActorScope,\n selectionResults?: Map<AnyTransitionDefinition, unknown>\n ): AnyTransitionDefinition[];\n /** @internal */\n _canTransition(snapshot: AnyMachineSnapshot, event: any): boolean;\n getStateNodeById(stateId: string): AnyStateNode;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n}\n\nexport type AnyStateConfig = StateConfig<any, AnyEventObject>;\n\nexport type DelayConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> = number | DelayExpr<TContext, TExpressionEvent>;\n\nexport type InitialContext<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject\n> = TContext | ContextFactory<TContext, TActorMap, TInput, TEvent>;\n\nexport type ContextFactory<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject = EventObject\n> = ({\n spawn,\n actors,\n input,\n self\n}: {\n spawn: Spawner;\n actors: TActorMap;\n input: TInput;\n self: ActorSelf<\n MachineSnapshot<\n [TContext] extends [never] ? any : TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => [TContext] extends [never] ? MachineContext : TContext;\n\nexport interface ProvidedActor {\n src: string;\n logic: UnknownActorLogic;\n id?: string | undefined; // `| undefined` is required here for compatibility with `exactOptionalPropertyTypes`, see #4613\n}\n\nexport interface SetupTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildrenMap extends Record<string, string>,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n context?: TContext;\n events?: TEvent;\n children?: TChildrenMap;\n tags?: TTag;\n input?: TInput;\n output?: TOutput;\n emitted?: TEmitted;\n meta?: TMeta;\n}\n\nexport interface MachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> extends SetupTypes<\n TContext,\n TEvent,\n // in machine types we currently don't support `TChildren`\n // and IDs can still be configured through `TActor['id']`\n never,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta\n> {\n actors?: TActor;\n actions?: TAction;\n guards?: TGuard;\n delays?: TDelay;\n meta?: TMeta;\n}\n\nexport interface HistoryStateNode<\n TContext extends MachineContext\n> extends StateNode<TContext> {\n history: 'shallow' | 'deep';\n target: string | undefined;\n}\n\nexport type HistoryValue = Record<string, Array<AnyStateNode>>;\n\nexport type PersistedHistoryValue = Record<string, Array<{ id: string }>>;\n\nexport type AnyHistoryValue = HistoryValue;\n\nexport type StateFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> = T extends AnyStateMachine\n ? StateSnapshotFromMachine<T>\n : T extends (...args: any[]) => AnyStateMachine\n ? StateSnapshotFromMachine<ReturnType<T>>\n : never;\n\nexport type StateValueFromStateSchema<T extends StateSchema> =\n StateSchema extends T\n ? StateValue\n : ToStateValue<T> extends infer TStateValue\n ? TStateValue extends StateValue\n ? TStateValue\n : StateValue\n : StateValue;\n\ntype MatchingStateValueForStateFrom<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends StateValueMap\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends StateValueMap\n ? TStateValue extends StateValueMap\n ? MatchingStateValueMapForStateFrom<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ntype MatchingStateValueMapForStateFrom<\n TStateValue extends StateValueMap,\n TTestStateValue extends StateValueMap\n> = false extends {\n [K in keyof TTestStateValue & string]: K extends keyof TStateValue\n ? IsNever<\n MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n > extends true\n ? false\n : true\n : false;\n}[keyof TTestStateValue & string]\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype StateSnapshotFromStateValue<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema,\n TAllStateValue extends StateValue = TStateValue\n> = TStateValue extends unknown\n ? Omit<\n MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TStateValue>,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n 'matches'\n > & {\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches(partialStateValue: StateValue): boolean;\n }\n : never;\n\ntype StateSnapshotFromMachine<T extends AnyStateMachine> =\n SnapshotFrom<T> extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer TStateSchema\n >\n ? StateSnapshotFromStateValue<\n TContext,\n TEvent,\n TChildren,\n StateValueFromStateSchema<TStateSchema>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n StateValueFromStateSchema<TStateSchema>\n >\n : SnapshotFrom<T>;\n\nexport interface DoneActorEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.actor';\n output: TOutput;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorActorEvent<\n TErrorData = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.error.actor';\n error: TErrorData;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorPlatformEvent<\n TErrorData = unknown,\n TKind extends string = string\n> extends EventObject {\n type: `xstate.error.${TKind}`;\n error: TErrorData;\n}\n\nexport type ErrorEvent = ErrorActorEvent | ErrorPlatformEvent;\n\nexport interface SnapshotEvent<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>\n> extends EventObject {\n type: 'xstate.snapshot.actor';\n actorId: string;\n sessionId: string;\n snapshot: TSnapshot;\n}\n\nexport interface DoneStateEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.state';\n stateId: TId;\n output: TOutput;\n}\n\nexport interface AfterEvent extends EventObject {\n type: 'xstate.after';\n delay: number | string;\n stateId: string;\n}\n\nexport interface TimeoutEvent extends EventObject {\n type: 'xstate.timeout';\n stateId: string;\n}\n\nexport interface ActorTimeoutEvent extends EventObject {\n type: 'xstate.timeout.actor';\n actorId: string;\n sessionId?: string;\n}\n\nexport enum SpecialTargets {\n Internal = '#_internal'\n}\n\nexport type Mapper<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TResult,\n TEvent extends EventObject,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n args: {\n context: _TCtx;\n event: TExpressionEvent;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n Record<string, AnyActorRef>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n } & OutputArg<TExpressionEvent>\n) => TResult;\n\nexport interface TransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends Omit<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >,\n 'target' | 'to'\n> {\n target: ReadonlyArray<AnyStateNode> | undefined;\n source: AnyStateNode;\n reenter: boolean;\n eventType: EventDescriptor<TEvent>;\n /** @internal Additional runtime matching for generated transitions. */\n _eventMatcher?: (event: EventObject, snapshot: AnyMachineSnapshot) => boolean;\n to?: ((...args: any[]) => any) | undefined;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: any;\n event: any;\n output: any;\n }) => Record<string, unknown>);\n}\n\nexport type AnyTransitionDefinition = TransitionDefinition<any, any>;\n\nexport type InitialTransitionDefinition = {\n source: AnyStateNode;\n target: AnyStateNode[] | undefined;\n reenter?: boolean;\n eventType?: EventDescriptor<any>;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: MachineContext;\n event: EventObject;\n }) => Record<string, unknown>);\n to?: ((...args: any[]) => any) | undefined;\n};\n\nexport type TransitionDefinitionMap<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in EventDescriptor<TEvent>]: Array<\n TransitionDefinition<TContext, ExtractEvent<TEvent, K>>\n >;\n};\n\nexport type DelayExpr<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = (args: {\n context: [TContext] extends [never] ? any : TContext;\n event: TEvent;\n stateNode: AnyStateNode;\n}) => number;\n\nexport interface DelayedTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n delay: number | string | DelayExpr<TContext, TEvent>;\n}\n\nexport interface StateLike<TContext extends MachineContext> {\n value: StateValue;\n context: TContext;\n event: EventObject;\n}\n\nexport interface StateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n context: TContext;\n historyValue?: HistoryValue;\n /** @internal */\n _nodes: Array<AnyStateNode>;\n /** @internal */\n value?: StateValue;\n children: Record<string, AnyActorRef | undefined>;\n timers?: Record<string, LogicalTimer>;\n status: SnapshotStatus;\n output?: any;\n error?: unknown;\n /** @internal */\n _stateInputs?: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId?: number;\n /**\n * Deterministic generated-child-id counters owned by this snapshot, keyed\n * by src prefix.\n *\n * @internal\n */\n _nextActorIds?: Record<string, number>;\n machine?: StateMachine<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n}\n\n/** A deterministic delayed-delivery declaration owned by a logic snapshot. */\nexport interface LogicalTimer {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n /** `self` or the logical actor that will receive `event`. */\n target: 'self' | AnyActor;\n /**\n * The timer's wall-clock start, stamped at persist time by a running\n * wall-clock actor and carried through restore so re-persisting keeps the\n * original deadline.\n */\n startedAt?: number;\n}\n\n/** The logical input delivered to a timer's source when its runtime delay ends. */\nexport interface TimerEvent extends EventObject {\n type: 'xstate.timer';\n id: string;\n}\n\ndeclare const persistedSnapshotLogic: unique symbol;\n\ntype PersistedSnapshotLogicIdentity<TLogic> = TLogic extends {\n readonly id: infer TId extends string;\n}\n ? {\n readonly id: TId;\n readonly version: TLogic extends {\n readonly version: infer TVersion extends string;\n }\n ? TVersion\n : string;\n }\n : never;\n\n/** A persisted snapshot tied to a versioned actor logic identity. */\nexport type PersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: PersistedSnapshotLogicIdentity<TLogic>;\n};\n\n/**\n * A persisted snapshot restorable into the given actor logic: any snapshot\n * created by logic with the same machine `id` is accepted, regardless of\n * version (version mismatches are handled at runtime, e.g. by `migrate`).\n */\nexport type RestorablePersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: TLogic extends {\n readonly id: infer TId extends string;\n }\n ? { readonly id: TId; readonly version: string }\n : never;\n};\n\nexport interface ActorOptions<TLogic extends AnyActorLogic> {\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n *\n * @remarks\n * You can create your own “clock”. The clock interface supports these\n * methods:\n *\n * - `now` - optional; returns the current time in milliseconds\n * - `setTimeout` - same arguments as `window.setTimeout(fn, timeout)`\n * - `clearTimeout` - same arguments as `window.clearTimeout(id)`\n *\n * By default, `Date.now`, native `setTimeout`, and native `clearTimeout` are\n * used.\n *\n * For testing, XState provides `SimulatedClock`.\n * @see {@link Clock}\n * @see {@link SimulatedClock}\n */\n clock?: Clock;\n /**\n * Specifies the logger to be used for `log(...)` actions. Defaults to the\n * native `console.log(...)` method.\n */\n logger?: (...args: any[]) => void;\n parent?: AnyActor;\n /** @internal */\n syncSnapshot?: boolean;\n /** @internal */\n _systemRef?: { current?: AnyActorSystem };\n /** @internal */\n _sessionId?: string;\n /** @internal */\n _inert?: boolean;\n /** The custom `id` for referencing this service. */\n id?: string;\n /** @deprecated Use `inspect` instead. */\n devTools?: never;\n\n /** The registry key to register this actor under. */\n registryKey?: string;\n /** The input data to pass to the actor. */\n input?: InputFrom<TLogic>;\n\n /**\n * Initializes actor logic from a specific persisted internal state.\n *\n * @remarks\n * If the state is compatible with the actor logic, when the actor is started\n * it will be at that persisted state. Actions from machine actors will not be\n * re-executed, because they are assumed to have been already executed.\n * However, invocations will be restarted, and spawned actors will be restored\n * recursively.\n *\n * Can be generated with {@link Actor.getPersistedSnapshot}.\n * @see https://stately.ai/docs/persistence\n */\n snapshot?: Snapshot<unknown> &\n Partial<RestorablePersistedSnapshotFor<DoNotInfer<TLogic>>>;\n\n /** @deprecated Use `snapshot` instead. */\n state?: Snapshot<unknown>;\n\n /** The source actor logic. */\n src?: string | AnyActorLogic;\n\n /**\n * A callback function or observer object which can be used to inspect actor\n * system updates.\n *\n * @remarks\n * If a callback function is provided, it can accept an inspection event\n * argument. The inspection protocol has two event types:\n *\n * - `@xstate.actor` - An actor ref was created in the system (announces actor\n * topology: identity + parent).\n * - `@xstate.transition` - An actor transitioned. Carries every facet of the\n * transition with flat, always-present fields: `event`, `snapshot`,\n * `sourceRef`, `microsteps`, executed `actions`, and `sent`/scheduled\n * events.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * });\n *\n * const actor = createActor(machine, {\n * inspect: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef, inspectionEvent.parentRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * // flat, always-present facets — no narrowing required\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * });\n * ```\n *\n * Alternately, an observer object (`{ next?, error?, complete? }`) can be\n * provided:\n *\n * @example\n *\n * ```ts\n * const actor = createActor(machine, {\n * inspect: {\n * next: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(\n * inspectionEvent.actorRef,\n * inspectionEvent.parentRef\n * );\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * }\n * });\n * ```\n */\n inspect?:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void);\n}\n\nexport type AnyActor = ActorInstance<any, any, any, any>;\n\n/** @deprecated Use `AnyActor` instead. */\nexport type AnyInterpreter = AnyActor;\n\n// Based on RxJS types\nexport type Observer<T> = {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n};\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface Readable<T> extends Subscribable<T> {\n get: () => T;\n}\n\nexport interface InteropObservable<T> {\n [Symbol.observable]: () => InteropSubscribable<T>;\n}\n\nexport interface InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n}\n\nexport interface Subscribable<T> extends InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n subscribe(\n next: (value: T) => void,\n error?: (error: any) => void,\n complete?: () => void\n ): Subscription;\n}\n\ntype EventDescriptorMatches<\n TEventType extends string,\n TNormalizedDescriptor\n> = TEventType extends TNormalizedDescriptor\n ? true\n : TNormalizedDescriptor extends TEventType\n ? true\n : false;\n\nexport type ExtractEvent<\n TEvent extends EventObject,\n TDescriptor extends EventDescriptor<TEvent>\n> = string extends TEvent['type']\n ? TEvent\n : NormalizeDescriptor<TDescriptor> extends infer TNormalizedDescriptor\n ? TEvent extends any\n ? // true is the check type here to match both true and boolean\n true extends EventDescriptorMatches<\n TEvent['type'],\n TNormalizedDescriptor\n >\n ? TEvent\n : never\n : never\n : never;\n\nexport interface BaseActorRef<TEvent extends EventObject> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorLike<\n TCurrent,\n TEvent extends EventObject\n> extends Subscribable<TCurrent> {\n send: (event: TEvent) => void;\n}\n\n/**\n * A consumer-facing actor handle.\n *\n * `ActorRef` describes the contract a consumer needs: which events can be sent\n * to the actor, which snapshot it publishes for observation, and which emitted\n * events can be listened to. It intentionally does not expose lifecycle control\n * or runtime internals. A concrete `Actor` satisfies this interface, so APIs\n * should accept `ActorRef` whenever they only need to send events, read\n * snapshots, or listen to emitted events.\n */\nexport interface ActorRef<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends Subscribable<TSnapshot>, InteropObservable<TSnapshot> {\n send: (event: TSendEvent) => void;\n getSnapshot: () => TSnapshot;\n on: <TType extends TEmitted['type'] | '*'>(\n type: TType,\n handler: (\n emitted: TEmitted & (TType extends '*' ? unknown : { type: TType })\n ) => void\n ) => Subscription;\n}\n\ntype EventPayload<\n TEvent extends EventObject,\n TType extends TEvent['type']\n> = HomomorphicOmit<ExtractEvent<TEvent, TType>, 'type'>;\n\nexport type ActorTrigger<TEvent extends EventObject> = {\n [K in TEvent['type']]: {} extends EventPayload<TEvent, K>\n ? () => void\n : (payload: EventPayload<TEvent, K>) => void;\n};\n\n/**\n * Runtime-only actor capabilities.\n *\n * These members are needed by the interpreter, scheduler, inspection, and child\n * management code. Public consumer APIs should prefer `ActorRef` unless they\n * genuinely need lifecycle control such as starting, stopping, or accessing\n * system-owned runtime state.\n */\nexport interface ActorRuntime<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n _TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n /** The unique identifier for this actor relative to its parent. */\n id: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`.\n */\n readonly address: string;\n /**\n * The globally unique process ID for this invocation.\n *\n * @remarks\n * This is only defined once the actor is started.\n */\n sessionId: string | undefined;\n /** @internal */\n _send: (event: TEvent) => void;\n start: () => this;\n getPersistedSnapshot: () => Snapshot<unknown>;\n stop: () => void;\n toJSON?: () => any;\n _parent?: any;\n system: any;\n /** @internal Emits the transition inspection event for `snapshot`. */\n _inspectTransition(snapshot: TSnapshot, event: EventObject): void;\n /** @internal */\n _processingStatus: ProcessingStatus;\n /** @internal */\n _isRunning: () => boolean;\n src: string | AnyActorLogic;\n /** Registry key used by the actor system receptionist. */\n registryKey?: string;\n trigger: ActorTrigger<TSendEvent>;\n select<TSelected>(\n selector: (snapshot: TSnapshot) => TSelected,\n equalityFn?: (a: TSelected, b: TSelected) => boolean\n ): Readable<TSelected>;\n}\n\n/**\n * A concrete actor instance type.\n *\n * `ActorInstance` combines the consumer `ActorRef` contract with runtime\n * lifecycle capabilities. Values returned by `createActor(...)` and\n * `spawn(...)` naturally satisfy narrower `ActorRef` contracts.\n */\nexport interface ActorInstance<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends\n ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent>,\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent> {}\n\n/**\n * The actor's own full self handle.\n *\n * Internals and action/guard sources receive this shape because `self` can\n * participate in runtime-owned behavior while still being usable wherever an\n * `ActorRef` is expected.\n */\nexport type ActorSelf<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> = ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent> &\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent>;\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\nexport type ActorRefFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer _TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any //TStateSchema\n >,\n TEvent,\n TEmitted,\n SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n >\n : T extends Promise<infer U>\n ? ActorRefFrom<AsyncActorLogic<U>>\n : T extends ActorLogic<\n infer TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? ActorRef<TSnapshot, TEvent, TEmitted>\n : never;\n\nexport type SendableEventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n : EventFromLogic<TLogic>;\n\ntype OpaqueMachineSnapshot<TSnapshot extends Snapshot<unknown>> =\n TSnapshot extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer _TStateSchema\n >\n ? MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any\n >\n : TSnapshot;\n\nexport type ActorRefFromLogic<T extends AnyActorLogic> = ActorRef<\n OpaqueMachineSnapshot<SnapshotFrom<T>>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\nexport interface AnyActorRef extends Subscribable<any>, InteropObservable<any> {\n send(event: any): void;\n getSnapshot(): any;\n on(type: string, handler: (emitted: any) => void): Subscription;\n}\n\n/** The concrete actor instance type produced from actor logic. */\nexport type ActorFromLogic<T extends AnyActorLogic> = ActorInstance<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\ntype SendableEventFromActorRef<\n TActorRef,\n TFallback extends EventObject = AnyEventObject\n> = [NonNullable<TActorRef>] extends [never]\n ? TFallback\n : NonNullable<TActorRef> extends infer TNonNullableActorRef\n ? TNonNullableActorRef extends { send: (event: infer TEvent) => void }\n ? [TEvent] extends [never]\n ? TFallback\n : TEvent extends EventObject\n ? TEvent\n : TFallback\n : never\n : never;\n\nexport type ActorRefLike = Pick<AnyActor, 'sessionId' | 'send' | 'getSnapshot'>;\n\nexport type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;\n\nexport type DevToolsAdapter = (service: AnyActor) => void;\n\nexport type MachineSourcesFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer TActionMap,\n infer TActorMap,\n infer TGuardMap,\n infer TDelayMap\n >\n ? {\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n }\n : never;\n\nexport interface ActorScope<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem = AnyActorSystem,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n self: ActorSelf<TSnapshot, TEvent, TEmitted, TSendEvent>;\n id: string;\n sessionId: string;\n logger: (...args: any[]) => void;\n defer: (fn: () => void) => void;\n emit: (event: TEmitted) => void | PromiseLike<void>;\n system: TSystem;\n stopChild: (child: AnyActor) => void;\n actionExecutor: ActionExecutor;\n}\n\nexport type AnyActorScope = ActorScope<\n any, // TSnapshot\n any, // TEvent\n AnyActorSystem,\n any, // TEmitted\n any // TSendEvent\n>;\n\nexport type SnapshotStatus = 'active' | 'done' | 'error' | 'stopped';\n\nexport type Snapshot<TOutput> =\n | {\n status: 'active';\n output: undefined;\n error: undefined;\n }\n | {\n status: 'done';\n output: TOutput;\n error: undefined;\n }\n | {\n status: 'error';\n output: undefined;\n error: unknown;\n }\n | {\n status: 'stopped';\n output: undefined;\n error: undefined;\n };\n\nexport type ActorLogicTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect = ExecutableActionObject\n> = [nextSnapshot: TSnapshot, effects: TEffect[]];\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\nexport interface ActorLogic<\n in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope[\"self\"][\"getSnapshot\"]`\n in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope[\"self\"][\"send\"]`\n in TInput = NonReducibleUnknown,\n TSystem extends AnyActorSystem = AnyActorSystem,\n in out TEmitted extends EventObject = EventObject // it's invariant because it's also aprt of `ActorScope[\"self\"][\"on\"]`\n> {\n /** The initial setup/configuration used to create the actor logic. */\n config?: unknown;\n /** Optional runtime validator for pure calculation boundaries. */\n validator?: import('./validation.types.ts').ActorLogicValidator;\n /**\n * Transition function that processes the current state and an incoming event\n * to produce a new state and effects.\n *\n * @param snapshot - The current state.\n * @param event - The incoming event.\n * @param actorScope - The actor scope.\n * @returns A tuple of the next state and effects.\n */\n transition: (\n snapshot: TSnapshot,\n event: TEvent,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Transition function that produces the initial state and effects.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns A tuple of the initial state and effects.\n */\n initialTransition: (\n input: TInput,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Called to provide the initial state of the actor.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns The initial state.\n */\n getInitialSnapshot: (\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>,\n input: TInput\n ) => TSnapshot;\n /**\n * Called when Actor is created to restore the internal state of the actor\n * given a persisted state. The persisted state can be created by\n * `getPersistedSnapshot`.\n *\n * @param persistedState - The persisted state to restore from.\n * @param actorScope - The actor scope.\n * @returns The restored state.\n */\n restoreSnapshot?: (\n persistedState: Snapshot<unknown>,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called when the actor is started.\n *\n * @param snapshot - The starting state.\n * @param actorScope - The actor scope.\n * @param options - Start metadata, including whether the snapshot was\n * restored.\n */\n start?: (\n snapshot: TSnapshot,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>,\n options?: { restored: boolean }\n ) => void;\n /**\n * Obtains the internal state of the actor in a representation which can be be\n * persisted. The persisted state can be restored by `restoreSnapshot`.\n *\n * @param snapshot - The current state.\n * @returns The a representation of the internal state to be persisted.\n */\n getPersistedSnapshot: (\n snapshot: TSnapshot,\n options?: unknown\n ) => Snapshot<unknown>;\n /**\n * Returns an event that the actor should transition with to recover from an\n * execution error, or `undefined` if the given snapshot cannot handle it.\n * Actor logic without error-recovery semantics can omit this.\n */\n getExecutionErrorEvent?: (\n snapshot: TSnapshot,\n error: unknown\n ) => TEvent | undefined;\n}\n\nexport interface AnyActorLogic {\n config?: unknown;\n validator?: import('./validation.types.ts').ActorLogicValidator;\n transition(\n snapshot: any,\n event: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n initialTransition(\n input: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n getInitialSnapshot(actorScope: any, input: any): any;\n restoreSnapshot?(persistedState: Snapshot<unknown>, actorScope: any): any;\n start?(snapshot: any, actorScope: any, options?: { restored: boolean }): void;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n getExecutionErrorEvent?(snapshot: any, error: unknown): any;\n}\n\nexport type UnknownActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n AnyActorSystem,\n any // emitted\n>;\n\nexport type SnapshotFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends ActorRef<infer TSnapshot, infer _, infer __>\n ? TSnapshot\n : R extends Actor<infer TLogic>\n ? SnapshotFrom<TLogic>\n : R extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TSnapshot\n : R extends ActorScope<\n infer TSnapshot,\n infer _TEvent,\n infer _TEmitted,\n infer _TSystem\n >\n ? TSnapshot\n : never\n : never;\n\nexport type EventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TEvent\n : never;\n\nexport type EmittedFrom<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEmitted\n : [TLogic] extends [AnyStateMachine]\n ? AnyEventObject\n : TLogic extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? TEmitted\n : AnyEventObject;\n\ntype ResolveEventType<T> = T extends infer R\n ? R extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEvent\n : R extends MachineSnapshot<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends ActorRef<infer _TSnapshot, infer TEvent, infer _TEmitted>\n ? TEvent\n : never\n : never;\n\nexport type EventFrom<\n T,\n K extends Prop<TEvent, 'type'> = never,\n TEvent extends EventObject = ResolveEventType<T>\n> = IsNever<K> extends true ? TEvent : ExtractEvent<TEvent, K>;\n\nexport type ContextFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TContext\n : T extends MachineSnapshot<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : T extends Actor<infer TActorLogic>\n ? TActorLogic extends AnyStateMachine\n ? ContextFrom<TActorLogic>\n : never\n : never;\n\nexport type InferEvent<E extends EventObject> = {\n [T in E['type']]: { type: T } & Extract<E, { type: T }>;\n}[E['type']];\n\nexport type TODO = any;\n\nexport type StateValueFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['matches']\n>[0];\n\nexport type TagsFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['hasTag']\n>[0];\n\nexport interface ActorSystemInfo {\n actors: Record<string, AnyActorRef>;\n}\n\nexport type SystemRegistry = Record<string, AnyActorLogic>;\n\nexport type RegistryKeyForLogic<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = string extends keyof TSystemRegistry\n ? string\n : Values<{\n [K in keyof TSystemRegistry &\n string]: ActorRefFromLogic<TLogic> extends ActorRefFromLogic<\n TSystemRegistry[K]\n >\n ? K\n : never;\n }>;\n\nexport type RequiredActorOptions<TActor extends ProvidedActor> =\n | (undefined extends TActor['id'] ? never : 'id')\n | (undefined extends InputFrom<TActor['logic']> ? never : 'input');\n\nexport type RequiredLogicInput<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\ntype ExtractLiteralString<T extends string | undefined> = T extends string\n ? string extends T\n ? never\n : T\n : never;\n\ntype ToConcreteChildren<TActor extends ProvidedActor> = {\n [A in TActor as ExtractLiteralString<A['id']>]?: ActorFromLogic<A['logic']>;\n};\n\n// Actors that don't have literal string IDs — these are the only ones\n// that should appear in the index signature fallback, since actors with\n// literal IDs are already covered by ToConcreteChildren.\ntype NonConcreteActors<TActor extends ProvidedActor> = TActor extends any\n ? ExtractLiteralString<TActor['id']> extends never\n ? TActor\n : never\n : never;\n\nexport type ToChildren<TActor extends ProvidedActor> =\n // only proceed further if all configured `src`s are literal strings\n string extends TActor['src']\n ? // TODO: replace `AnyActorRef` with `UnknownActorRef`~\n // or maybe even `TActor[\"logic\"]` since it's possible to configure `{ src: string; logic: SomeConcreteLogic }`\n // TODO: consider adding `| undefined` here\n Record<string, AnyActor>\n : Compute<\n ToConcreteChildren<TActor> &\n {\n include: {\n [id: string]: NonConcreteActors<TActor> extends never\n ? AnyActor | undefined\n : NonConcreteActors<TActor> extends any\n ?\n | ActorFromLogic<NonConcreteActors<TActor>['logic']>\n | undefined\n : never;\n };\n exclude: unknown;\n }[NonConcreteActors<TActor> extends never ? 'exclude' : 'include']\n >;\n\nexport type StateSchema = {\n id?: string;\n route?: unknown;\n states?: Record<string, StateSchema>;\n contextSchema?: StandardSchemaV1;\n outputSchema?: StandardSchemaV1;\n input?: unknown;\n\n // Other types\n // Needed because TS treats objects with all optional properties as a \"weak\" object\n // https://github.com/statelyai/xstate/issues/5031\n type?: unknown;\n history?: unknown;\n target?: unknown;\n invoke?: unknown;\n on?: unknown;\n entry?: unknown;\n exit?: unknown;\n onDone?: unknown;\n onError?: unknown;\n timeout?: unknown;\n onTimeout?: unknown;\n after?: unknown;\n always?: unknown;\n choice?: unknown;\n meta?: unknown;\n output?: unknown;\n tags?: unknown;\n description?: unknown;\n};\n\nexport type StateSchemaFrom<T extends AnyStateMachine> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TStateSchema\n : never;\n\nexport type StateId<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> =\n | (TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: StateId<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n : never);\n\n/** Maps state IDs to their input types based on the StateSchema. */\nexport type StateIdInputs<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> = {\n [K in TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`]: TSchema['input'] extends undefined\n ? undefined\n : TSchema['input'];\n} & (TSchema['states'] extends Record<string, StateSchema>\n ? UnionToIntersection<\n Values<{\n [K in keyof TSchema['states'] & string]: StateIdInputs<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n >\n : {});\n\ntype UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (\n k: infer I\n) => void\n ? I\n : never;\n\ntype ContextFromStateSchema<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext\n> = TSchema['contextSchema'] extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema['contextSchema']> & MachineContext\n : TFallbackContext;\n\ntype ContextFromChildStateValue<\n TChildSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TChildValue\n> = ContextFromStateSchema<TChildSchema, TFallbackContext> &\n StateContextFromStateValue<\n TChildSchema,\n ContextFromStateSchema<TChildSchema, TFallbackContext>,\n TChildValue\n >;\n\nexport type StateContextFromStateValue<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TStateValue\n> = (TSchema['states'] extends Record<string, StateSchema>\n ? TStateValue extends keyof TSchema['states'] & string\n ? ContextFromStateSchema<TSchema['states'][TStateValue], TFallbackContext>\n : TStateValue extends Record<string, unknown>\n ? UnionToIntersection<\n Values<{\n [K in keyof TStateValue &\n keyof TSchema['states'] &\n string]: ContextFromChildStateValue<\n TSchema['states'][K],\n TFallbackContext,\n NonNullable<TStateValue[K]>\n >;\n }>\n >\n : TFallbackContext\n : TFallbackContext) &\n MachineContext;\n\nexport type RoutableStateId<TSchema extends StateSchema> =\n | (TSchema extends { route: any; id: string } ? `#${TSchema['id']}` : never)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: RoutableStateId<\n TSchema['states'][K]\n >;\n }>\n : never);\n\nexport interface StateMachineTypes {\n context: MachineContext;\n events: EventObject;\n actors: ProvidedActor;\n actions: ParameterizedObject;\n guards: ParameterizedObject;\n delays: string;\n tags: string;\n emitted: EventObject;\n}\n\n/** @deprecated */\nexport interface ResolvedStateMachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TEmitted extends EventObject = EventObject\n> {\n context: TContext;\n events: TEvent;\n actors: TActor;\n actions: TAction;\n guards: TGuard;\n delays: TDelay;\n tags: TTag;\n emitted: TEmitted;\n}\n\nexport type GetConcreteByKey<\n T,\n TKey extends keyof T,\n TValue extends T[TKey]\n> = T & Record<TKey, TValue>;\n\ntype _GroupStateKeys<\n T extends StateSchema,\n S extends keyof T['states']\n> = S extends any\n ? T['states'][S] extends { type: 'history' }\n ? [never, never]\n : T extends { type: 'parallel' }\n ? [S, never]\n : T['states'][S] extends { states: Record<string, StateSchema> }\n ? [S, never]\n : [never, S]\n : never;\n\ntype GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {\n nonLeaf: _GroupStateKeys<T, S & string>[0];\n leaf: _GroupStateKeys<T, S & string>[1];\n};\n\nexport type ToStateValue<T extends StateSchema> = T extends {\n states: Record<infer S, any>;\n}\n ? IsNever<S> extends true\n ? {}\n :\n | GroupStateKeys<T, S>['leaf']\n | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false\n ? T extends { type: 'parallel' }\n ? {\n [K in GroupStateKeys<T, S>['nonLeaf']]: ToStateValue<\n T['states'][K]\n >;\n }\n : Compute<\n Values<{\n [K in GroupStateKeys<T, S>['nonLeaf']]: {\n [StateKey in K]: ToStateValue<T['states'][K]>;\n };\n }>\n >\n : never)\n : {};\n\nexport interface BaseExecutableActionObject {\n params: NonReducibleUnknown;\n args: unknown[];\n exec(\n runtime?: Partial<ActorSystemRuntime>\n ): void | PromiseLike<void> | undefined;\n}\n\n/** The terminal result published when an actor completes or errors. */\nexport type ActorTermination =\n | { status: 'done'; output: unknown; error: undefined }\n | { status: 'error'; output: undefined; error: unknown };\n\nexport interface CustomExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'action';\n type: TType;\n action: ((...args: any[]) => void | PromiseLike<void>) | undefined;\n}\n\nexport interface EmitExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'emit';\n type: TType;\n source: AnyActor;\n event: EventObject & { type: TType };\n}\n\nexport interface SpawnExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.spawn';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n logic: AnyActorLogic;\n src: string | AnyActorLogic;\n input: unknown;\n args: Parameters<(typeof builtInActions)['@xstate.spawn']>;\n}\n\nexport interface StartExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.start';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.start']>;\n}\n\nexport interface RaiseExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.raise';\n source: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.raise']>;\n}\n\nexport interface SendToExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.sendTo';\n source: AnyActor;\n target: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.sendTo']>;\n}\n\nexport interface CancelExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.cancel';\n source: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.cancel']>;\n}\n\nexport interface StopExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.stop';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.stop']>;\n}\n\n/** An executable effect that publishes an actor's terminal result. */\nexport type TerminateExecutableActionObject = BaseExecutableActionObject & {\n kind: 'builtin';\n type: '@xstate.terminate';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.terminate']>;\n} & ActorTermination;\n\nexport type BuiltInExecutableActionObject = Values<{\n '@xstate.spawn': SpawnExecutableActionObject;\n '@xstate.start': StartExecutableActionObject;\n '@xstate.raise': RaiseExecutableActionObject;\n '@xstate.sendTo': SendToExecutableActionObject;\n '@xstate.cancel': CancelExecutableActionObject;\n '@xstate.stop': StopExecutableActionObject;\n '@xstate.terminate': TerminateExecutableActionObject;\n}>;\n\nexport type SpecialExecutableAction = BuiltInExecutableActionObject;\n\ntype TransitionExecutableActionObject<TType extends string = never> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType | (string & {})>;\n\ntype KnownSourceKeys<TSourceMap> = string extends keyof TSourceMap\n ? never\n : Extract<keyof TSourceMap, string>;\n\nexport type ExecutableActionObjectFromLogic<T extends AnyActorLogic> =\n T extends StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n infer TActionMap,\n any,\n any,\n any\n >\n ? TransitionExecutableActionObject<KnownSourceKeys<TActionMap>>\n : ExecutableActionObject;\n\nexport type ExecutableActionObject<TType extends string = string & {}> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType>;\n\nexport interface ToExecutableAction<\n T extends ParameterizedObject\n> extends CustomExecutableActionObject<T['type']> {\n type: T['type'];\n params: T['params'];\n action: undefined;\n}\n\nexport type ActionExecutor = (actionToExecute: ExecutableActionObject) => void;\n\n/** Mappers for subscribeTo - maps lifecycle events to machine events */\nexport interface SubscribeToMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\ntype EnqueueSpawnOptions<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = {\n input?: InputFrom<TLogic>;\n id?: string;\n syncSnapshot?: boolean;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n};\n\ntype EnqueueSpawnArgs<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = ConditionalRequired<\n [\n options?: EnqueueSpawnOptions<TLogic, TSystemRegistry> & {\n [K in RequiredLogicInput<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n>;\n\ntype EnqueueSpawner<\n TActorMap extends Sources['actors'],\n TSystemRegistry extends SystemRegistry\n> = {\n <TSource extends keyof TActorMap & string>(\n src: TSource,\n ...[options]: EnqueueSpawnArgs<TActorMap[TSource], TSystemRegistry>\n ): ActorFromLogic<TActorMap[TSource]>;\n <TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EnqueueSpawnArgs<TLogic, TSystemRegistry>\n ): ActorFromLogic<TLogic>;\n};\n\nexport type EnqueueObject<\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TSystemRegistry extends SystemRegistry = SystemRegistry,\n TActorMap extends Sources['actors'] = Sources['actors']\n> = {\n cancel: (id: string) => void;\n raise: (ev: TEvent, options?: { id?: string; delay?: number }) => void;\n /**\n * Spawns a child actor from a registered source key or logic. Without an\n * explicit `id`, the child gets a deterministic src-keyed id (`worker:0`,\n * `worker:1`, …) allocated from the parent snapshot's own counters, so ids\n * replay identically and persist with the parent.\n */\n spawn: EnqueueSpawner<TActorMap, TSystemRegistry>;\n emit: (emittedEvent: TEmittedEvent) => void;\n <T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): void;\n log: (...args: any[]) => void;\n sendTo: <TActorRef extends { send: (...args: any[]) => void } | undefined>(\n actorRef: TActorRef,\n event: SendableEventFromActorRef<NoInfer<TActorRef>>,\n options?: { id?: string; delay?: number }\n ) => void;\n stop: (actor?: AnyActorRef) => void;\n /**\n * Listen to emitted events from an actor. Returns a listener actor that can\n * be stopped via `enq.stop()`.\n *\n * @param actor - The actor to listen to\n * @param eventType - The emitted event type to listen for (supports\n * wildcards: 'event._', '_')\n * @param mapper - Function to transform emitted events into machine events\n */\n listen: <TEmitted extends EventObject, TMappedEvent extends TEvent>(\n actor: AnyActorRef,\n eventType: string,\n mapper: (event: TEmitted) => TMappedEvent\n ) => AnyActor;\n /**\n * Subscribe to lifecycle events (done/error/snapshot) from an actor. Returns\n * a subscription actor that can be stopped via `enq.stop()`.\n *\n * @param actor - The actor to subscribe to\n * @param mappers - Object with done/error/snapshot mappers, or a single\n * snapshot mapper function\n */\n subscribeTo: <TActor extends AnyActorRef, TMappedEvent extends TEvent>(\n actor: TActor,\n mappers:\n | SubscribeToMappers<\n SnapshotFrom<TActor>,\n OutputFrom<TActor>,\n TMappedEvent\n >\n | ((snapshot: SnapshotFrom<TActor>) => TMappedEvent)\n ) => AnyActor;\n};\n\nexport type Action<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TParams = Record<string, unknown> | undefined,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n _: {\n context: _TCtx;\n event: TEvent;\n parent: AnyActorRef | undefined;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n children: Record<string, AnyActor | undefined>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n system?: AnyActorSystem;\n params: TParams;\n },\n enqueue: EnqueueObject<TEvent, TEmittedEvent, SystemRegistry, TActorMap>\n) => {\n context?: Partial<_TCtx>;\n children?: Record<string, AnyActor | undefined>;\n} | void;\n\nexport type AnyAction =\n | Action<\n MachineContext,\n EventObject,\n EventObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n >\n | { action: (...args: any[]) => any; args: any[] }\n | AnyEventObject;\n","import { createInitEvent } from './eventUtils';\nimport { hasAmbientInspector } from './system';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n setInertActorScopeSnapshot\n} from './getNextSnapshot';\nimport {\n getProperAncestors,\n initialMicrostep,\n isAtomicStateNode,\n macrostep\n} from './stateUtils';\nimport {\n AnyActorLogic,\n AnyEventObject,\n AnyStateMachine,\n EventFromLogic,\n InputFrom,\n SnapshotFrom,\n ExecutableActionObjectFromLogic,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyActor,\n AnyActorScope,\n ExecutableActionObject\n} from './types';\nimport {\n beginSpawnAllocation,\n createSpawnEffect,\n finalizeTransitionResult\n} from './transitionActions.ts';\n\nimport type { EventObject } from './types';\n\ntype MachineMicrostep = [AnyMachineSnapshot, ExecutableActionObject[]];\n\nfunction attachMicrostepActorRefs(\n microsteps: MachineMicrostep[],\n actorScope: AnyActorScope,\n inputSnapshot?: AnyMachineSnapshot\n): MachineMicrostep[] {\n if (!microsteps.length) {\n return microsteps;\n }\n const result = microsteps.slice();\n const finalSnapshot = result.at(-1)![0];\n setInertActorScopeSnapshot(actorScope, finalSnapshot, false);\n if (finalSnapshot !== inputSnapshot) {\n attachSnapshotActorRef(actorScope, finalSnapshot);\n }\n for (const [snapshot] of result) {\n if (snapshot !== inputSnapshot && snapshot !== finalSnapshot) {\n const snapshotScope = createInertActorScope(\n snapshot.machine,\n snapshot,\n undefined,\n actorScope\n );\n attachSnapshotActorRef(snapshotScope, snapshot);\n }\n }\n return result;\n}\n\n/**\n * Given actor `logic`, a `snapshot`, and an `event`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute.\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function transition<T extends AnyActorLogic>(\n logic: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): [\n nextSnapshot: SnapshotFrom<T>,\n actions: ExecutableActionObjectFromLogic<T>[]\n] {\n const actorScope = createInertActorScope(logic, snapshot);\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const [nextSnapshot, effects] = finalizeTransitionResult(\n actorScope,\n snapshot,\n logic.transition(snapshot, event, actorScope)\n );\n\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n const returnedSnapshot =\n nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(actorScope, nextSnapshot);\n inspectPureTransition(actorScope, returnedSnapshot, event);\n return [returnedSnapshot, effects as ExecutableActionObjectFromLogic<T>[]];\n}\n\n/**\n * Given actor `logic` and optional `input`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute from the initial transition (no\n * previous state).\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function initialTransition<T extends AnyActorLogic>(\n logic: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): [SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]] {\n const actorScope = createInertActorScope(logic);\n\n const [nextSnapshot, executableActions] = finalizeTransitionResult(\n actorScope,\n undefined,\n logic.initialTransition(input, actorScope)\n );\n\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n const returnedSnapshot = attachSnapshotActorRef(actorScope, nextSnapshot);\n inspectPureTransition(actorScope, returnedSnapshot, createInitEvent(input));\n return [\n returnedSnapshot,\n executableActions as ExecutableActionObjectFromLogic<T>[]\n ];\n}\n\n/**\n * Emits the `@xstate.transition` inspection event for a snapshot produced by\n * the pure transition path, where no live actor loop does it. Free unless an\n * inspector is ambiently installed (a durable execution created with\n * `inspect`): only then is the snapshot's actor ref materialized to emit.\n */\nfunction inspectPureTransition(\n actorScope: unknown,\n snapshot: unknown,\n event: EventObject\n): void {\n if (!hasAmbientInspector()) {\n return;\n }\n const self = (actorScope as { self?: AnyActor }).self;\n if (self?.system._hasInspectionObservers?.()) {\n self._inspectTransition(snapshot as never, event);\n }\n}\n\n/**\n * Given a state `machine`, a `snapshot`, and an `event`, returns an array of\n * microsteps, where each microstep is a tuple of `[snapshot, actions]`.\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function getMicrosteps<T extends AnyStateMachine>(\n machine: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]> {\n const actorScope = createInertActorScope(machine, snapshot);\n beginSpawnAllocation(actorScope);\n\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n\n return attachMicrostepActorRefs(\n microsteps as MachineMicrostep[],\n actorScope,\n snapshot as AnyMachineSnapshot\n ) as Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]>;\n}\n\n/**\n * Given a state `machine` and optional `input`, returns an array of microsteps\n * from the initial transition, where each microstep is a tuple of `[snapshot,\n * actions]`.\n *\n * This is a pure function that does not execute `actions`.\n */\nexport function getInitialMicrosteps<T extends AnyStateMachine>(\n machine: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]> {\n const actorScope = createInertActorScope(machine);\n beginSpawnAllocation(actorScope);\n const initEvent = createInitEvent(input);\n const internalQueue: AnyEventObject[] = [];\n\n const preInitialSnapshot = machine._getPreInitialState(actorScope, initEvent);\n const contextSpawnEffects = Object.values(preInitialSnapshot.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n\n const first = initialMicrostep(\n machine.root,\n preInitialSnapshot,\n actorScope,\n initEvent,\n internalQueue\n );\n\n const { microsteps } = macrostep(\n first[0],\n initEvent,\n actorScope,\n internalQueue,\n [[first[0], [...contextSpawnEffects, ...first[1]]] as MachineMicrostep]\n );\n\n return attachMicrostepActorRefs(\n microsteps as MachineMicrostep[],\n actorScope\n ) as Array<[SnapshotFrom<T>, ExecutableActionObjectFromLogic<T>[]]>;\n}\n\n/**\n * Gets all potential next transitions from the current state.\n *\n * Returns all transitions that are available from the current state, including:\n *\n * - All transitions from atomic states (leaf states in the current state\n * configuration)\n * - All transitions from ancestor states (parent states that may handle events)\n * - All guarded transitions (regardless of whether their guards would pass)\n * - Always (eventless) transitions\n * - After (delayed) transitions\n *\n * The order of transitions is deterministic:\n *\n * 1. Atomic states are processed in document order\n * 2. For each atomic state, transitions are collected from the state itself first,\n * then its ancestors\n * 3. Within each state node, transitions are in the order they appear in the state\n * definition\n *\n * @param state - The current machine snapshot\n * @returns Array of transition definitions from the current state, in\n * deterministic order\n */\nexport function getNextTransitions(\n state: AnyMachineSnapshot\n): AnyTransitionDefinition[] {\n if (state.status !== 'active') {\n return [];\n }\n const potentialTransitions: AnyTransitionDefinition[] = [];\n const atomicStates = state.nodes.filter(isAtomicStateNode);\n const visited = new Set();\n\n // Collect all transitions from atomic states and their ancestors\n // Process atomic states in document order (as they appear in state.nodes)\n for (const stateNode of atomicStates) {\n // For each atomic state, process the state itself first, then its ancestors\n // This ensures child state transitions come before parent state transitions\n for (const s of [stateNode].concat(\n getProperAncestors(stateNode, undefined)\n )) {\n if (visited.has(s.id)) {\n continue;\n }\n visited.add(s.id);\n\n // Get all transitions for each event type\n // Include ALL transitions, even if the same event type appears in multiple state nodes\n // This is important for guarded transitions - all are \"potential\" regardless of guard evaluation\n for (const [, transitions] of s.transitions.entries()) {\n potentialTransitions.push(...transitions);\n }\n\n // Also include always (eventless) transitions\n if (s.always) {\n potentialTransitions.push(...s.always);\n }\n }\n }\n\n return potentialTransitions;\n}\n","import isDevelopment from '#is-development';\nimport { AnyActorRef, SnapshotFrom, Subscription } from './types.ts';\n\ninterface WaitForOptions {\n /**\n * How long to wait before rejecting, if no emitted state satisfies the\n * predicate.\n *\n * @defaultValue Infinity\n */\n timeout: number;\n\n /** A signal which stops waiting when aborted. */\n signal?: AbortSignal;\n}\n\nconst defaultWaitForOptions: WaitForOptions = {\n timeout: Infinity // much more than 10 seconds\n};\n\n/**\n * Subscribes to an actor ref and waits for its emitted value to satisfy a\n * predicate, and then resolves with that value. Will throw if the desired state\n * is not reached after an optional timeout. (defaults to Infinity).\n *\n * @example\n *\n * ```js\n * const state = await waitFor(someService, (state) => {\n * return state.hasTag('loaded');\n * });\n *\n * state.hasTag('loaded'); // true\n * ```\n *\n * @param actorRef The actor ref to subscribe to\n * @param predicate Determines if a value matches the condition to wait for\n * @param options\n * @returns A promise that eventually resolves to the emitted value that matches\n * the condition\n */\nexport function waitFor<TActorRef extends AnyActorRef>(\n actorRef: TActorRef,\n predicate: (emitted: SnapshotFrom<TActorRef>) => boolean,\n options?: Partial<WaitForOptions>\n): Promise<SnapshotFrom<TActorRef>> {\n const resolvedOptions: WaitForOptions = {\n ...defaultWaitForOptions,\n ...options\n };\n return new Promise((res, rej) => {\n const { signal } = resolvedOptions;\n if (signal?.aborted) {\n // oxlint-disable-next-line typescript/prefer-promise-reject-errors\n rej(signal.reason);\n return;\n }\n let done = false;\n if (isDevelopment && resolvedOptions.timeout < 0) {\n console.error(\n '`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.'\n );\n }\n const handle =\n resolvedOptions.timeout === Infinity\n ? undefined\n : setTimeout(() => {\n dispose();\n rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));\n }, resolvedOptions.timeout);\n\n const dispose = () => {\n clearTimeout(handle);\n done = true;\n sub?.unsubscribe();\n if (abortListener) {\n signal!.removeEventListener('abort', abortListener);\n }\n };\n\n function checkEmitted(emitted: SnapshotFrom<TActorRef>) {\n if (predicate(emitted)) {\n dispose();\n res(emitted);\n }\n }\n\n /**\n * If the `signal` option is provided, this will be the listener for its\n * `abort` event\n */\n let abortListener: () => void | undefined;\n // oxlint-disable-next-line prefer-const\n let sub: Subscription | undefined; // avoid TDZ when disposing synchronously\n\n // See if the current snapshot already matches the predicate\n checkEmitted(actorRef.getSnapshot());\n if (done) {\n return;\n }\n\n // only define the `abortListener` if the `signal` option is provided\n if (signal) {\n abortListener = () => {\n dispose();\n // XState does not \"own\" the signal, so we should reject with its reason (if any)\n // oxlint-disable-next-line typescript/prefer-promise-reject-errors\n rej(signal.reason);\n };\n signal.addEventListener('abort', abortListener);\n }\n\n sub = actorRef.subscribe({\n next: checkEmitted,\n error: (err) => {\n dispose();\n // oxlint-disable-next-line typescript/prefer-promise-reject-errors\n rej(err);\n },\n complete: () => {\n dispose();\n rej(new Error(`Actor terminated without satisfying predicate`));\n }\n });\n if (done) {\n sub.unsubscribe();\n }\n });\n}\n","import { Clock } from './system.ts';\n\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\nexport interface SimulatedClock extends Clock {\n start(speed: number): void;\n increment(ms: number): void;\n set(ms: number): void;\n}\n\ninterface SimulatedTimeout {\n start: number;\n timeout: number;\n fn: (...args: any[]) => void;\n}\nexport class SimulatedClock implements SimulatedClock {\n private timeouts: Map<number, SimulatedTimeout> = new Map();\n private _now: number = 0;\n private _id: number = 0;\n private _flushing = false;\n private _flushingInvalidated = false;\n\n public now() {\n return this._now;\n }\n private getId() {\n return this._id++;\n }\n public setTimeout(fn: (...args: any[]) => void, timeout: number) {\n this._flushingInvalidated = this._flushing;\n const id = this.getId();\n this.timeouts.set(id, {\n start: this.now(),\n timeout,\n fn\n });\n return id;\n }\n public clearTimeout(id: number) {\n this._flushingInvalidated = this._flushing;\n this.timeouts.delete(id);\n }\n public set(time: number) {\n if (this._now > time) {\n throw new Error('Unable to travel back in time');\n }\n\n this._now = time;\n this.flushTimeouts();\n }\n private flushTimeouts() {\n if (this._flushing) {\n this._flushingInvalidated = true;\n return;\n }\n this._flushing = true;\n\n const sorted = [...this.timeouts].sort(\n ([_idA, timeoutA], [_idB, timeoutB]) => {\n const endA = timeoutA.start + timeoutA.timeout;\n const endB = timeoutB.start + timeoutB.timeout;\n return endB > endA ? -1 : 1;\n }\n );\n\n for (const [id, timeout] of sorted) {\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this._flushing = false;\n this.flushTimeouts();\n return;\n }\n if (this.now() - timeout.start >= timeout.timeout) {\n this.timeouts.delete(id);\n timeout.fn.call(null);\n }\n }\n\n this._flushing = false;\n // Check if new timeouts were added during the last iteration\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this.flushTimeouts();\n }\n }\n public increment(ms: number): void {\n this._now += ms;\n this.flushTimeouts();\n }\n}\n","import { EventDescriptor, EventObject, ExtractEvent } from './types.ts';\nimport { matchesEventDescriptor, toArray } from './utils.ts';\n\n/**\n * Asserts that the given event object is of the specified type or types. Throws\n * an error if the event object is not of the specified types.\n *\n * @example\n *\n * ```ts\n * // ...\n * entry: ({ event }) => {\n * assertEvent(event, 'doNothing');\n * // event is { type: 'doNothing' }\n * },\n * // ...\n * exit: ({ event }) => {\n * assertEvent(event, 'greet');\n * // event is { type: 'greet'; message: string }\n *\n * assertEvent(event, ['greet', 'notify']);\n * // event is { type: 'greet'; message: string }\n * // or { type: 'notify'; message: string; level: 'info' | 'error' }\n * },\n * ```\n */\nexport function assertEvent<\n TEvent extends EventObject,\n TAssertedDescriptor extends EventDescriptor<TEvent>\n>(\n event: TEvent,\n type: TAssertedDescriptor | readonly TAssertedDescriptor[]\n): asserts event is ExtractEvent<TEvent, TAssertedDescriptor> {\n const types = toArray(type);\n\n const matches = types.some((descriptor) =>\n matchesEventDescriptor(event.type, descriptor as string)\n );\n\n if (!matches) {\n const typesText =\n types.length === 1\n ? `type matching \"${types[0]}\"`\n : `one of types matching \"${types.join('\", \"')}\"`;\n throw new Error(\n `Expected event ${JSON.stringify(event)} to have ${typesText}`\n );\n }\n}\n","import { isRemoteActorRef } from './remoteActorRef.ts';\nimport { getActorIdPrefix } from './system.ts';\nimport type { ExecutableActionObject } from './types.ts';\n\n/**\n * A serializable view of an executable effect. Actor references are replaced\n * by their logical addresses and actor sources by their registered source\n * keys, so a durable host can journal, deduplicate, and route effects without\n * holding live actor references. Payload fields (`event`, `input`, `params`,\n * `output`, `error`) pass through by reference and are only as serializable\n * as their values.\n *\n * @experimental\n */\nexport type EffectDescriptor =\n | {\n kind: 'builtin';\n type: '@xstate.spawn';\n source: string | undefined;\n actor: string;\n id: string;\n src: string;\n input: unknown;\n }\n | {\n kind: 'builtin';\n type: '@xstate.start';\n source: string | undefined;\n actor: string;\n id: string;\n }\n | {\n kind: 'builtin';\n type: '@xstate.raise';\n source: string;\n event: unknown;\n id: string | undefined;\n delay: number | undefined;\n }\n | {\n kind: 'builtin';\n type: '@xstate.sendTo';\n source: string;\n target: string;\n /** The target's incarnation token, when the target is a remote handle that carries one. */\n incarnation: string | undefined;\n event: unknown;\n id: string | undefined;\n delay: number | undefined;\n }\n | {\n kind: 'builtin';\n type: '@xstate.cancel';\n source: string;\n id: string;\n }\n | {\n kind: 'builtin';\n type: '@xstate.stop';\n source: string;\n actor: string;\n id: string;\n }\n | {\n kind: 'builtin';\n type: '@xstate.terminate';\n source: string;\n actor: string;\n id: string;\n status: 'done' | 'error';\n output: unknown;\n error: unknown;\n }\n | {\n kind: 'emit';\n type: string;\n source: string;\n event: unknown;\n }\n | {\n kind: 'action';\n type: string;\n params: unknown;\n };\n\n/**\n * Returns the serializable descriptor for an executable effect: the same\n * discriminants (`kind`, `type`) with actor references replaced by logical\n * addresses and actor sources by source keys. Payload fields pass through by\n * reference.\n *\n * @experimental\n */\nexport function getEffectDescriptor(\n effect: ExecutableActionObject\n): EffectDescriptor {\n if (effect.kind === 'action') {\n return {\n kind: 'action',\n type: effect.type,\n params: effect.params\n };\n }\n\n if (effect.kind === 'emit') {\n return {\n kind: 'emit',\n type: effect.type,\n source: effect.source.address,\n event: effect.event\n };\n }\n\n switch (effect.type) {\n case '@xstate.spawn':\n return {\n kind: 'builtin',\n type: '@xstate.spawn',\n source: effect.source?.address,\n actor: effect.actor.address,\n id: effect.id,\n // `src` is only a unique key for registered sources; anonymous inline\n // logic collapses to its logic id or 'x'. The `actor` address is the\n // identity field.\n src: getActorIdPrefix(effect.src),\n input: effect.input\n };\n case '@xstate.start':\n return {\n kind: 'builtin',\n type: '@xstate.start',\n source: effect.source?.address,\n actor: effect.actor.address,\n id: effect.id\n };\n case '@xstate.raise':\n return {\n kind: 'builtin',\n type: '@xstate.raise',\n source: effect.source.address,\n event: effect.event,\n id: effect.id,\n delay: effect.delay\n };\n case '@xstate.sendTo':\n return {\n kind: 'builtin',\n type: '@xstate.sendTo',\n source: effect.source.address,\n target: effect.target.address,\n incarnation: isRemoteActorRef(effect.target)\n ? effect.target.sessionId\n : undefined,\n event: effect.event,\n id: effect.id,\n delay: effect.delay\n };\n case '@xstate.cancel':\n return {\n kind: 'builtin',\n type: '@xstate.cancel',\n source: effect.source.address,\n id: effect.id\n };\n case '@xstate.stop':\n return {\n kind: 'builtin',\n type: '@xstate.stop',\n source: effect.source.address,\n actor: effect.actor.address,\n id: effect.id\n };\n case '@xstate.terminate':\n return {\n kind: 'builtin',\n type: '@xstate.terminate',\n source: effect.source.address,\n actor: effect.actor.address,\n id: effect.id,\n status: effect.status,\n output: effect.output,\n error: effect.error\n };\n }\n}\n","/** The Standard Schema interface. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\n/** Schemas that can be declared for an individual state node. */\nexport type SetupStateSchemas = {\n context?: StandardSchemaV1;\n input?: StandardSchemaV1;\n /** The output emitted when this state node completes. */\n output?: StandardSchemaV1;\n};\n\n/** A type-only Standard Schema produced by {@link types}. */\nexport interface TypeSchema<T> extends StandardSchemaV1<T, T> {\n readonly '~standard': StandardSchemaV1.Props<T, T> & {\n readonly vendor: 'xstate.types';\n };\n}\n\n/**\n * Declares schema types for inference only — no runtime validation.\n *\n * Use in a machine's `schemas` when you want TypeScript types without pulling\n * in a schema library like Zod. The returned value is a valid Standard Schema\n * whose validation is the identity function, so it carries types but never\n * rejects input.\n *\n * @example\n *\n * ```ts\n * import { createMachine, types } from 'xstate';\n *\n * const machine = createMachine({\n * schemas: {\n * context: types<{ count: number }>(),\n * events: {\n * inc: types<{ by: number }>(),\n * reset: types<{}>()\n * }\n * },\n * context: { count: 0 }\n * // ...\n * });\n * ```\n */\nexport function types<T>(): TypeSchema<T> {\n return {\n '~standard': {\n version: 1,\n vendor: 'xstate.types',\n validate: (value) => ({ value: value as T })\n }\n };\n}\n\n/** Returns true if the value is a type-only schema created by {@link types}. */\nexport function isTypeSchema(value: unknown): value is TypeSchema<unknown> {\n return (\n !!value &&\n typeof value === 'object' &&\n '~standard' in value &&\n (value as StandardSchemaV1)['~standard'].vendor === 'xstate.types'\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1;\n /** The vendor name of the schema library. */\n readonly vendor: string;\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>;\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined;\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output;\n /** The non-existent issues. */\n readonly issues?: undefined;\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>;\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string;\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey;\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input;\n /** The output type of the schema. */\n readonly output: Output;\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input'];\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output'];\n}\n","import { MachineSnapshot } from './State.ts';\nimport { isAtomicStateNode } from './stateUtils.ts';\nimport { AnyMachineSnapshot, AnyStateNode, StateSchema } from './types.ts';\n\ntype StateSchemaFromSnapshot<TSnapshot extends AnyMachineSnapshot> =\n TSnapshot extends MachineSnapshot<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer TStateSchema extends StateSchema\n >\n ? TStateSchema\n : StateSchema;\n\n/**\n * A mapper object that defines how to transform a snapshot based on its state.\n * Can be nested to match the state hierarchy of the machine.\n */\ntype StateSchemaMapper<\n TSnapshot extends AnyMachineSnapshot,\n T extends StateSchema,\n TResult\n> = {\n /** Maps the snapshot to a value when this state is active. */\n map?: (snapshot: TSnapshot) => TResult;\n /** Nested mappers for child states. */\n states?: {\n [K in keyof T['states']]?: T['states'][K] extends StateSchema\n ? StateSchemaMapper<TSnapshot, T['states'][K], TResult>\n : never;\n };\n};\n\n/**\n * Maps a machine snapshot to an array of result objects based on active states.\n *\n * Traverses all active state nodes (from atomic/leaf states up to root) and\n * collects results from matching `map` functions in the mapper object. Results\n * are ordered leaf-to-root (most specific state first).\n */\nexport function mapState<T extends AnyMachineSnapshot, TResult>(\n snapshot: T,\n mapper: StateSchemaMapper<T, StateSchemaFromSnapshot<T>, TResult>\n): { stateNode: AnyStateNode; result: TResult }[] {\n const results: { stateNode: AnyStateNode; result: TResult }[] = [];\n\n const findMapper = (\n currentMapper: StateSchemaMapper<T, StateSchemaFromSnapshot<T>, TResult>,\n nodePath: string[]\n ): StateSchemaMapper<T, any, TResult> | undefined => {\n let mapper: StateSchemaMapper<T, any, TResult> | undefined = currentMapper;\n\n for (const key of nodePath) {\n if (!mapper?.states) {\n return undefined;\n }\n const states = mapper.states as Record<\n string,\n StateSchemaMapper<T, any, TResult>\n >;\n if (!(key in states)) {\n return undefined;\n }\n mapper = states[key];\n }\n\n return mapper;\n };\n\n const visited = new Set<AnyStateNode>();\n\n for (const atomicNode of snapshot.nodes.filter(isAtomicStateNode)) {\n let current: AnyStateNode | undefined = atomicNode;\n while (current && !visited.has(current)) {\n visited.add(current);\n\n const nodeMapper = findMapper(mapper, current.path);\n if (nodeMapper?.map) {\n results.push({ stateNode: current, result: nodeMapper.map(snapshot) });\n }\n\n current = current.parent;\n }\n }\n\n return results;\n}\n","import { AnyActorRef, OutputFrom } from './types.ts';\n\n/**\n * Returns a promise that resolves to the `output` of the actor when it is done.\n *\n * @example\n *\n * ```ts\n * const machine = createMachine({\n * // ...\n * output: {\n * count: 42\n * }\n * });\n *\n * const actor = createActor(machine);\n *\n * actor.start();\n *\n * const output = await toPromise(actor);\n *\n * console.log(output);\n * // logs { count: 42 }\n * ```\n */\nexport function toPromise<T extends AnyActorRef>(\n actor: T\n): Promise<OutputFrom<T>> {\n return new Promise((resolve, reject) => {\n actor.subscribe({\n complete: () => {\n resolve(actor.getSnapshot().output);\n },\n error: reject\n });\n });\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_INIT","XSTATE_SPAWN","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","XSTATE_LOGIC_EFFECT_RESOLVE","XSTATE_LOGIC_EFFECT_REJECT","XSTATE_LOGIC_EFFECT_START","createAfterEvent","delayRef","id","type","delay","stateId","createAfterEventId","createTimeoutEventId","createInvokeTimeoutEvent","invokeId","sessionId","actorId","createInvokeTimeoutEventId","createDoneStateEvent","output","createErrorPlatformEvent","kind","error","createInitEvent","input","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","assertSendToEvent","Error","builtInActions","actor","system","spawnActor","_parent","startActor","@xstate.raise","actorScope","_event","options","scheduleTimer","self","@xstate.sendTo","undefined","_relay","@xstate.cancel","sendId","cancelTimer","@xstate.stop","stopActor","@xstate.terminate","termination","terminateActor","sourceKeyCaches","WeakMap","resolveRegisteredActorSource","actors","logic","cache","get","Map","key","Object","keys","registeredLogic","has","set","subscriptions","createAttachedLogic","attach","initialTransition","_","status","state","target","getSnapshot","subscription","parentSubscription","torndown","teardown","unsubscribe","parent","subscribe","complete","transition","delete","getInitialSnapshot","getPersistedSnapshot","snapshot","restoreSnapshot","relayMappedToParent","getEvent","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","on","emittedEvent","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","lazyActorScope","isLazyActorScope","getActorScopeParent","withActorScope","args","actorArgs","defineProperties","enumerable","execCustomEffect","action","execEmitEffect","runtime","source","emitEvent","createCustomEffect","params","exec","execSpawnEffect","execStartEffect","execStopEffect","execTerminateEffect","execRaiseEffect","execSendToEffect","sendEvent","execCancelEffect","updateLogicalTimers","effect","isBuiltInExecutableAction","timers","nextTimerId","_nextTimerId","mergeContextPatch","context","patch","pushBuiltInAction","actions","actionRecord","push","mergeActorIdCounters","current","update","merged","Math","max","applyChildUpdate","children","counters","_nextActorIds","owned","_unregister","getTransitionActionRecord","spawnAllocations","createSpawnAllocation","explicitIds","Set","stoppedIds","beginSpawnAllocation","getWorkingSnapshotOf","_snapshot","nextChildIndex","allocation","prefix","allocateChildId","src","localAllocation","getActorIdPrefix","assertChildIdFree","existing","occupied","add","reserveChildId","generated","parseGeneratedActorId","index","createTransitionEnqueue","internalEvents","actorSubscriptions","createActors","props","cancel","emit","log","logger","raise","raisedEvent","spawn","registeredActors","sources","getRegisteredActors","resolveTransitionSpawnSource","registryKey","createActorRef","childUpdate","pushSpawnedChild","sendTo","message","stop","actorInstance","recordStoppedChild","assign","listen","listenerActor","subscribeTo","subscriptionActor","createEnqueueObject","getBuiltInActionFields","createStartEffect","createSpawnEffect","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","resolveActionsWithContext","currentSnapshot","intermediateSnapshot","executableActions","actionArgs","getEventOutput","machine","isInline","resolvedAction","bind","actionParams","_childUpdate","emittedEventParams","name","res","emptyEnqueueObject","builtInFields","isEmittedEvent","typedExecutableAction","enqueueFn","fn","noop","emptyActor","parseDurationToMilliseconds","duration","normalizedDuration","trim","millisecondsMatch","match","parseInt","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","slice","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDelayToMilliseconds","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","getKeyedActors","peek","_peekKeyedActors","call","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","baseState","root","copyRegisteredActors","reverseKeyedActors","create","sourceVersion","_register","_set","String","getAll","fromEntries","_hasInspectionObservers","_sendInspectionEvent","values","getSnapshotActorRef","created","copySnapshotActorRef","ref","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","size","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","isInertActorScope","_inert","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","defer","stopChild","actionExecutor","createMaterializedInertActorScope","actorLogic","sourceRef","sourceChildren","sourceSelf","snapshotRef","previousSelf","createActor","_sessionId","_systemRef","_address","_actorScope","_stop","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","isMachineSnapshot","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","resolveDelay","delaySource","configuredDelay","referencedDelay","getConfiguredDelayValue","getStateInput","stateNodeId","_stateInputs","isAtomicStateNode","stateNode","getChildren","states","filter","sn","getProperAncestors","toStateNode","ancestors","m","getAllStateNodes","stateNodes","nodeSet","activeParentSet","s","initialStates","getInitialStateNodes","initialStateNode","getStateValue","rootNode","config","adjList","getValueFromAdj","baseNode","childStateNodes","childStateNode","stateValue","isInFinalState","stateNodeSet","every","isStateId","str","getLegacyEventType","matchesActorSession","getCandidates","eventTypes","legacyType","getEventTypeAliases","exactMatches","flatMap","transitions","wildcardCandidates","eventDescriptor","includes","sort","a","b","length","scheduleDelayedEvent","timerId","resolveEvent","resolveScheduledDelay","oldEntry","entry","x","enq","oldExit","exit","formatTransition","descriptor","transitionConfig","normalizedTarget","normalizeTarget","reenter","resolveTarget","assertLegalTargetSet","toJSON","map","t","isStateNodeDescendantOf","ancestor","getLeastCommonStateNodeAncestor","left","right","leftAncestors","targets","leftIndex","rightIndex","commonAncestor","getStateNodeById","isInternalTarget","getStateNodeByPath","resolvedTarget","resolveHistoryDefaultTransition","initial","to","_historyDefaultTransition","isHistoryNode","iter","descStateNode","initialState","getStateNode","stateKey","result","statePath","arrayStatePath","toStatePath","currentStateNode","shift","getStateNodes","childStateKeys","Array","allStateNodes","i","subStateNode","transitionNode","selectionResults","subStateKeys","subStateKey","allInnerTransitions","subStateValue","innerTransitions","isDescendant","parentStateNode","marker","hasDescendantState","hasIntersection","s1","s2","s1Size","isArray","s2Size","set1","item","removeConflictingTransitions","enabledTransitions","resolveTransition","filteredTransitions","exitSets","getExitSet","exitSet","computeExitSet","t1","t1Preempted","transitionsToRemove","t2","t3","from","createTransitionResultResolver","resolveActions","getTransitionResult","selectionResult","getEffectiveTargetStates","historyValue","targetSet","targetNode","node","narrowParallelDomain","domain","targetStates","narrowed","region","find","getTransitionDomain","_transitionDomain","head","tail","concat","statesToExit","initialMicrostep","preInitialState","initEvent","internalQueue","initialStateNodes","statesForDefaultEntry","collectDefaultEntryStates","microstep","other","_statesForDefaultEntry","isInitial","mutStateNodeSet","nodes","originalContext","getCurrentTransitionResult","changesState","getStateActionsAndContext","transitionFn","updatedContext","guards","delays","_special","nextState","getInvokeStopActions","invokeDef","invoke","exitStates","changedHistory","order","currentStateNodes","exitStateNode","historyNode","predicate","history","stateInput","exitActions","nextContext","cloneMachineSnapshot","resolvedState","resolvedActions","invokeStopActions","stoppedState","stopEffects","transitionActions","toArray","enterStates","getMachineOutput","rootCompletionNode","completionOutput","rootDoneEvent","e","resolveOutput","stateInputMap","parallelDoneEvent","statesToEnter","historyDefaultsByParent","addAncestorStatesToEnter","reentrancyDomain","anc","addDescendantStatesToEnter","historyStateNodes","historyDefaultTransition","historyParent","defaults","stateInputsChanged","completedNodes","stateNodeToEnter","invoked","resolveReferencedActor","syncSnapshot","contextChangedByEntry","resultActions","nextInternalEvents","defaultTransitions","Boolean","defaultTransition","initialActions","initialContext","initialInput","initialInternalEvents","ancestorMarker","regionOutput","regionDoneEvent","finalChild","resolvedTransitionState","transitionExecutableActions","nextStateNodes","allExitActions","forEach","stopChildren","withoutTimers","cancelEffects","cancelTimers","_nodes","transitionArgs","getTransitionArgs","reusable","resolvedInput","resolvedContext","macrostep","initialMicrosteps","microsteps","removeTerminatedChild","terminalEvent","lastEffects","at","completeMacrostep","starts","attachedStarts","childStarts","deriveDeferredStarts","shouldTerminate","terminalEffects","lastSnapshot","addMicrostep","step","collectedMicrosteps","_collectedMicrosteps","stoppedChildrenSnapshot","nextEvent","normalizeWithId","idKey","startsWith","normalized","afterPrefix","idMap","delayText","isNaN","normalizeLegacyInternalEvent","timer","currentEvent","isErr","isErrorEvent","getTransitionData","_hasEventlessTransitions","shouldSelectEventlessTransitions","maxIterations","Infinity","iterationCount","microstepCount","selectEventlessTransitions","previousState","hasEffect","evaluateTransitionFunction","enabled","triggerTransitionEffect","transitionEffectSignal","transitionEffectEnqueue","transitionTo","sourceId","transitionEffectTargets","pop","timerIds","enabledTransitionSet","atomicStates","atomicStateNode","loop","always","evaluateCandidate","candidate","matches","pattern","entries","is","matchesEvent","_eventMatcher","guard","guardArgs","withActorSelfAndParent","evaluation","emptySubscription","restoreHint","isRemoteActorRef","actorRef","_remote","remoteSnapshot","freeze","createRemoteActorRef","handle","address","incarnation","_syncSnapshot","send","_send","select","trigger","_isRunning","xstate$type","ACTOR_REF_TYPE","emptySnapshotRecord","compactSnapshotRecord","machineSnapshotMatches","testValue","matchesState","machineSnapshotHasTag","tag","tags","machineSnapshotCan","_canTransition","machineSnapshotToJSON","getMeta","getInputs","can","hasTag","jsonValues","machineSnapshotGetMeta","meta","machineSnapshotGetInputs","collectTags","createMachineSnapshot","configWithSnapshot","clonedSnapshot","serializeHistoryValue","persistContext","contextPart","copy","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","segment","charCodeAt","pathToStateValue","previous","toArrayStrict","isDoneEvent","toTransitionConfigArray","configLike","transitionLike","toObserver","nextHandler","errorHandler","completionHandler","isObserver","indexStr","nodeId","invokeConfig","configSrc","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","async","runStep","sendSelf","getStepEffect","Promise","resolve","reject","waitForStep","deliverEvent","assertEventCanBeSent","runtimeTarget","_lastSourceRef","isInternalEventType","_terminate","systemIdPrefix","nextSystemId","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","toString","padStart","join","randomUUID","replaceAll","Date","now","random","createSystemIdPrefix","logicId","encodeAddressSegment","separator","lastIndexOf","isSafeInteger","getActorIdCounterKey","bumpActorIdCounter","counterKey","emptyScheduledTimers","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_keyedActors","_reverseKeyedActors","_identity","systemId","nextSessionId","scheduler","_clock","_logger","restoredSnapshot","clock","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","targetRef","targetId","schedule","existingId","_timerMap","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","changed","inspect","observerOrFn","observer","resolvedInspectionEvent","rootId","override","stopActorLocally","terminateActorLocally","_emit","deadLetter","reason","runLogic","cancelAllTimers","scheduledTimers","resetScheduledTimers","scheduledId","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","Actor","_trigger","Proxy","payload","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_collectedActions","_initialEffects","_deferred","_restored","resolvedOptions","rootActor","createRuntimeSystem","requestedId","counter","resolveActorId","persistedState","_setSnapshot","parentRef","_getLogger","_defer","defineProperty","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","_next","deferred","deferredFn","_inspectTransition","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","Stopped","handler","listeners","selector","equalityFn","selected","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","startedAt","min","caughtError","reportError","assertValid","validator","request","check","effectStates","executeLogicEffect","getEffectState","cleanup","createLogic","calculateTransition","cleanupLogicEffects","trackedEffects","emitted","createEmitEffect","sendBack","sentEvent","keyOrExec","maybeExec","enqueueEffect","run","eventOrigin","resolveContext","instanceStates","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","XSTATE_ASYNC_RESOLVE","XSTATE_ASYNC_REJECT","TimeoutError","super","emptyLogic","EMPTY_OBJECT","StateNode","path","description","schemas","after","events","ownEvents","_candidateCache","_key","_machine","firstStateKey","choice","validateStateNodeConfig","collection","iteratee","collectionKeys","mapValues","stateConfig","resolvedId","sourceName","_initialize","afterConfig","timeoutConfig","onTimeoutConfig","onTimeout","invokeDefs","fromDelaysMap","eventMatcher","delayedTransitions","eventPattern","delayedTransition","getDelayedTransitions","addTransitions","additions","transitionsConfig","mapTransitionConfigs","onDone","onError","createCancelInvokeTimeoutTransition","timeoutEventId","_args","formatInvokeCompletionTransition","rest","didEnqueue","trackingEnqueue","apply","thisArg","argArray","Reflect","prop","receiver","withInvokeMatch","invokeTimeoutEventId","invokeDoneTransitions","rawTransition","formatTransitions","validateChoiceResult","formatChoiceTransitions","_refreshEventMetadata","object","memoizedData","memo","_target","targetString","resolvedTargets","formatInitialTransition","descriptorKey","getEventDescriptorKey","candidates","transitionConfigs","findEventSchema","hasOwn","emptyCanActor","emptyCanActorScope","getEmptyCanActorScope","StateMachine","_internalEventType","version","snapshotSchema","eventSchema","internalEventDescriptors","_json","vendor","validate","issues","contextSchema","resolveState","eventSchemas","internalEventSchemas","isFrameworkEvent","schema","rootStateNode","routeTransitions","collectRoutes","route","routeId","routeConfig","routeMatches","_guard","routeOptions","formatRouteTransitions","provide","provided","resolvedStateValue","usesInertScope","resolvedActorScope","fastSnapshot","_transitionFast","returnedSnapshot","_attachPureActorRef","_collectEffects","skipInitializingActor","sourceNode","stateChanged","snapshots","emptyActorScope","transitionData","_getPreInitialState","preInitial","spawnedChildren","referencedSrc","createSpawner","withActorSelf","takeSpawnAllocationCounters","contextSpawnEffects","finalizeInitialResult","macroState","errorMacrostep","childId","_rehydrated","fullPath","relativePath","resolvedStateId","STATE_IDENTIFIER","childrenJson","timersJson","embedChildren","embed","remote","snapshotActor","scheduled","persisted","stateInputs","snapshotMachine","persistedMachine","legacyPersistedVersion","persistedVersion","migrate","snapshotData","snapshotChildren","actorData","childState","persistedTimers","targetDescription","revivedHistoryValue","revived","arr","resolved","reviveHistoryValue","validateStateValue","missingStateError","childNode","_persistedSnapshotVersion","_nextActorId","_legacyNextActorId","persistedRest","restoredCounters","seen","WeakSet","reviveContext","createMachine","allocations","beginFSMEffects","ids","execute","fields","createFSMEnqueue","resolveFSMEffects","appendFSMStarts","ordered","attached","findIndex","splice","createFSMSendEffect","finalizeFSMEffects","emptySources","emptyExecutableActions","emptyFSMActions","assertPersistableFSM","resolveTransitionContext","resolveInput","prototype","hasOwnProperty","cloneSnapshot","_stateInput","stopSnapshot","cleanupFSM","completeFinalState","runStateActions","completed","exited","exitEffects","cleaned","cleanupEffects","invalidStringTarget","delayToMs","parsedDelay","parseFloat","isExpression","isResolvable","isCode","toPath","extractSerializableDelays","toActionArray","validateChoiceConfig","branch","when","isBuiltInActionJSON","valueToJSON","isActorLogic","isRuntimeSchema","v","jsonValue","invokeToJSON","def","sourcesToJSON","stateNodeConfigToJSON","machineConfigToJSON","isObject","isVersionedStateMachine","finalizeSnapshot","validateEvents","all","validated","setup","extend","extension","base","mergeSchemas","mergeMaps","mergeSetupConfigs","machineConfig","mergedSchemas","mergedStates","mergeStateSchemas","mergedActions","mergedActors","mergedGuards","mergedDelays","createStateConfig","configStates","setupStates","configState","setupState","SpecialTargets","attachMicrostepActorRefs","inputSnapshot","finalSnapshot","inspectPureTransition","defaultWaitForOptions","timeouts","_now","_id","_flushing","_flushingInvalidated","getId","time","flushTimeouts","sorted","_idA","timeoutA","_idB","timeoutB","endA","increment","types","typesText","JSON","stringify","asyncLogic","createBaseLogic","resolvedValue","data","actorSelf","controller","AbortController","timeoutMs","timeoutId","abort","runBody","signal","then","response","errorData","callbackOrConfig","callback","callbackState","receivers","dispose","receive","listener","lazyObservableOrConfig","lazyObservable","_subscription","assertNoStringTransitions","runActions","actionsConfig","actionCount","currentContext","selectTransition","transitionCount","transitionCore","directTransition","targetState","hasContext","hasInput","selectedTransition","iterations","nextValue","transitionResult","afterTransition","entered","entryActions","completionEffects","unshift","createSnapshot","raisedSnapshot","raisedActions","json","resolvedSources","evaluators","mergeSources","expressionResolver","expressionLanguage","getEvaluator","lang","evaluator","evaluateResolvable","slot","resolveValue","makeScope","extra","getDurationConfig","assertResolvable","createExpressionResolver","resolveCondition","condition","declarativeGuard","guardImpl","makeChoiceConfig","resolveRouteConfig","resolvedGuard","executeActions","stack","definition","iterActions","actionArray","getTransitionConfig","dynamic","assertCondition","assertAction","definitions","assertActions","assertTransition","transitionPath","assertStateNode","invokePath","assertMachineJSON","contextConfig","iterNode","nodeKey","invokes","inv","xstate.stateIn","xstate.not","inner","impl","observableCreatorOrConfig","observableCreator","_config","runtimeRef","pendingObservers","createActorFromLogic","flushObservers","active","preInitialSnapshot","first","potentialTransitions","visited","byIdentity","machinesByIdentity","machineId","unversioned","parseSnapshot","raw","adaptEvents","adaptationOptions","sourceError","sourceValidationFailed","hasTypedSource","sourceEvents","adapter","adapters","wildcardAdapter","cause","migrateSnapshot","migrationOptions","parseError","exactMigration","migrations","wildcardMigration","defaultId","getSnapshotSource","results","findMapper","currentMapper","nodePath","atomicNode","nodeMapper","rej","aborted","sub","abortListener","removeEventListener","checkEmitted","addEventListener"],"mappings":"6OAKO,MAAMA,EAKXC,WAAAA,CAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,KAAAA,GACLJ,KAAKC,SAAU,EACfD,KAAKK,OACP,CAEOC,KAAAA,GAGDN,KAAKE,WACPF,KAAKE,SAASK,KAAO,KACrBP,KAAKG,MAAQH,KAAKE,SAEtB,CAEOM,OAAAA,CAAQC,GACb,MAAMC,EAAW,CACfC,MAAOF,EACPF,KAAM,MAGR,GAAIP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