xstate 6.0.0-alpha.37 → 6.0.0-alpha.39

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.
Files changed (44) hide show
  1. package/dist/{StateMachine-7197482a.development.cjs.js → StateMachine-144215d2.development.cjs.js} +22 -2
  2. package/dist/{StateMachine-009b5bc4.esm.js → StateMachine-2f47d890.esm.js} +22 -2
  3. package/dist/{StateMachine-5d0aac92.cjs.js → StateMachine-94084ac7.cjs.js} +22 -2
  4. package/dist/{StateMachine-9da92cbf.development.esm.js → StateMachine-da29dd2e.development.esm.js} +22 -2
  5. package/dist/{createActor-164c86f5.development.esm.js → createActor-2a03d4b2.development.esm.js} +15 -3
  6. package/dist/{createActor-19e83fb9.esm.js → createActor-a211c276.esm.js} +15 -3
  7. package/dist/{createActor-8462b9cc.development.cjs.js → createActor-c0f78b8a.development.cjs.js} +14 -2
  8. package/dist/{createActor-fd53ec92.cjs.js → createActor-d5305cc9.cjs.js} +14 -2
  9. package/dist/declarations/src/createMachine.d.ts +3 -3
  10. package/dist/declarations/src/index.d.ts +3 -2
  11. package/dist/declarations/src/setup.d.ts +16 -12
  12. package/dist/declarations/src/types.d.ts +1 -1
  13. package/dist/declarations/src/types.v6.d.ts +11 -4
  14. package/dist/{index-acf2bd02.development.esm.js → index-17f889df.development.esm.js} +2 -2
  15. package/dist/{index-13e54113.cjs.js → index-21d08fff.cjs.js} +1 -1
  16. package/dist/{index-14478488.development.cjs.js → index-3d1368f7.development.cjs.js} +1 -1
  17. package/dist/{index-abf9ab72.esm.js → index-7020402e.esm.js} +2 -2
  18. package/dist/{transition-169651ca.cjs.js → transition-2dcabac8.cjs.js} +1 -1
  19. package/dist/{transition-a306226e.development.cjs.js → transition-4ba58b71.development.cjs.js} +1 -1
  20. package/dist/{transition-760b0fc6.esm.js → transition-e8a13c00.esm.js} +1 -1
  21. package/dist/{transition-61a126e0.development.esm.js → transition-f581ffa6.development.esm.js} +1 -1
  22. package/dist/xstate-actors.cjs.js +2 -2
  23. package/dist/xstate-actors.development.cjs.js +2 -2
  24. package/dist/xstate-actors.development.esm.js +2 -2
  25. package/dist/xstate-actors.esm.js +2 -2
  26. package/dist/xstate-actors.umd.min.js.map +1 -1
  27. package/dist/xstate-durable.cjs.js +2 -2
  28. package/dist/xstate-durable.development.cjs.js +2 -2
  29. package/dist/xstate-durable.development.esm.js +2 -2
  30. package/dist/xstate-durable.esm.js +2 -2
  31. package/dist/xstate-durable.umd.min.js.map +1 -1
  32. package/dist/xstate-graph.cjs.js +3 -3
  33. package/dist/xstate-graph.development.cjs.js +3 -3
  34. package/dist/xstate-graph.development.esm.js +3 -3
  35. package/dist/xstate-graph.esm.js +3 -3
  36. package/dist/xstate-graph.umd.min.js +1 -1
  37. package/dist/xstate-graph.umd.min.js.map +1 -1
  38. package/dist/xstate.cjs.js +7 -10
  39. package/dist/xstate.development.cjs.js +7 -10
  40. package/dist/xstate.development.esm.js +9 -12
  41. package/dist/xstate.esm.js +9 -12
  42. package/dist/xstate.umd.min.js +1 -1
  43. package/dist/xstate.umd.min.js.map +1 -1
  44. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"xstate-durable.umd.min.js","sources":["../src/constants.ts","../src/eventUtils.ts","../src/Mailbox.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actorScope.ts","../src/transitionActions.ts","../src/snapshotActorRef.ts","../src/utils.ts","../src/system.ts","../src/State.ts","../src/createActor.ts","../src/getNextSnapshot.ts","../src/durable/index.ts","../src/transition.ts"],"sourcesContent":["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","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","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","/**\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 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 { 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 type { ActorSystemRuntime } 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 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 | { type: 'add'; actor: AnyActor; id: string }\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\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 };\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 | undefined\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id: id ?? actor.id };\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\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: (logic, options) => {\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? (logic as any).id\n } as AnyActor;\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, options?.id);\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 const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actor\n );\n action.childUpdate = { type: 'remove', actor };\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\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 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","import 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 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 into\n // a live runtime system.\n _hasInspectionObservers: () => false,\n _sendInspectionEvent: () => {}\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 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 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 { markSystemSnapshotDirty } from './snapshotActorRef.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/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined\n): string {\n if (requestedId !== undefined) {\n const match = /^x:(\\d+)$/.exec(requestedId);\n const reservedId = match ? Number(match[1]) : undefined;\n if (reservedId !== undefined && Number.isSafeInteger(reservedId)) {\n const nextActorId = Math.max(\n system._snapshot._nextActorId,\n reservedId + 1\n );\n if (nextActorId !== system._snapshot._nextActorId) {\n system._snapshot._nextActorId = nextActorId;\n markSystemSnapshotDirty(system);\n }\n }\n return requestedId;\n }\n\n const id = `x:${system._snapshot._nextActorId++}`;\n markSystemSnapshotDirty(system);\n return id;\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 * An external interpreter can override these operations while the default actor\n * system provides the local in-memory implementation.\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 /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\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 _nextActorId: number;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\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 _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 = {\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 _nextActorId?: number;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n _nextActorId: restoredSnapshot?._nextActorId ?? 0\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 const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n _lastSourceRef?: AnyActor;\n };\n const targetMachine = runtimeTarget.logic;\n const isInternalEvent =\n typeof targetMachine?.isInternalEventType === 'function' &&\n targetMachine.isInternalEventType(event.type);\n\n if (isInternalEvent && source !== target) {\n throw new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n\n // remember the last source for unified transition inspect event\n runtimeTarget._lastSourceRef = source;\n target._send(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 if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed = (this._children?.delete(actor.sessionId!) ?? false) || changed;\n } else {\n changed = 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 public spawnActor(): void {}\n\n public startActor(actor: AnyActor): void {\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n }\n\n public terminateActor(actor: AnyActor, termination: ActorTermination): void {\n (\n actor as AnyActor & { _terminate(value: ActorTermination): void }\n )._terminate(termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n this._recordSent(source, target, event);\n this._deliver(source, target, event);\n }\n\n public emitEvent(source: AnyActor, event: EventObject): void {\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public scheduleTimer(source: AnyActor, id: string, delay: number): void {\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void {\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void {\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n 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 { $$ACTOR_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';\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 /**\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 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 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 for (const id in children) {\n const child = children[id] as any;\n if (\n isDevelopment &&\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 childrenJson[id as keyof typeof childrenJson] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\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 timersJson[id] = {\n id: timer.id,\n delay: timer.delay,\n type: timer.type,\n event,\n target\n };\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n _nextActorId:\n getSnapshotActorRef(snapshot)?.systemState.snapshot._nextActorId,\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_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 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 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 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\nexport const $$ACTOR_TYPE = 1;\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 /** 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 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 private _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 const timers: Record<string, { id: string; delay: number }> =\n (\n this._snapshot as unknown as {\n timers?: Record<string, { id: string; delay: number }>;\n }\n ).timers ?? {};\n for (const timer of Object.values(timers)) {\n this.system.scheduleTimer(this, timer.id, timer.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 // do nothing\n if (isDevelopment) {\n // TODO: circular serialization issues\n // const eventString = ''; //JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.`\n );\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 public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\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(): Snapshot<unknown>;\n public getPersistedSnapshot(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\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 represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\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 { 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 }\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 type { ActorSystemRuntime } from '../system.ts';\nimport { initialTransition, transition } from '../transition.ts';\nimport type {\n AnyActorLogic,\n CustomExecutableActionObject,\n EventFromLogic,\n ExecutableActionObjectFromLogic,\n InputFrom,\n OutputFrom,\n Snapshot,\n SnapshotFrom\n} from '../types.ts';\n\nexport interface DurableEffectMetadata {\n /** Stable within one durable execution. */\n id: string;\n transitionIndex: number;\n effectIndex: number;\n}\n\nexport interface DurableWaitMetadata {\n /** Stable within one durable execution. */\n id: string;\n transitionIndex: number;\n}\n\nexport interface DurableEffect<TEffect> extends DurableEffectMetadata {\n effect: TEffect;\n}\n\nexport interface DurableExecutionAdapter<TLogic extends AnyActorLogic> {\n /**\n * Executes a custom action as a durable host step or activity. The host\n * should identify the action by `type` and memoize or deduplicate it using\n * `metadata.id`.\n */\n executeAction(\n action: CustomExecutableActionObject,\n metadata: DurableEffectMetadata,\n runtime: Partial<ActorSystemRuntime>\n ): void | PromiseLike<void>;\n /**\n * Creates the runtime used by one effect. Timers, messaging and\n * child actors should be translated to equivalent host operations. The\n * complete effect is provided for hosts that need serializable actor source,\n * input, event or target data beyond the runtime method arguments.\n */\n runtime?(\n metadata: DurableEffectMetadata,\n effect: ExecutableActionObjectFromLogic<TLogic>\n ): Partial<ActorSystemRuntime>;\n /** Waits durably for the next event addressed to this execution. */\n waitForEvent(\n metadata: DurableWaitMetadata\n ): EventFromLogic<TLogic> | PromiseLike<EventFromLogic<TLogic>>;\n /** Index assigned to the first transition. Defaults to `0`. */\n transitionIndex?: number;\n}\n\nexport class DurableExecutionCancelledError extends Error {\n constructor() {\n super('Durable execution was stopped');\n this.name = 'DurableExecutionCancelledError';\n }\n}\n\nexport class DurableExecutionResumeError extends Error {\n constructor() {\n super(\n 'run() can only start a fresh durable execution; resume checkpoints with transition() and the persisted snapshot'\n );\n this.name = 'DurableExecutionResumeError';\n }\n}\n\nexport interface DurableExecution<TLogic extends AnyActorLogic> {\n /** Index assigned to the next transition. Persist this with checkpoints. */\n readonly nextTransitionIndex: number;\n initialTransition(\n ...[input]: undefined extends InputFrom<TLogic>\n ? [input?: InputFrom<TLogic>]\n : [input: InputFrom<TLogic>]\n ): [\n snapshot: SnapshotFrom<TLogic>,\n effects: DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[]\n ];\n transition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventFromLogic<TLogic>\n ): [\n snapshot: SnapshotFrom<TLogic>,\n effects: DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[]\n ];\n executeEffects(\n effects: readonly DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[]\n ): Promise<void>;\n waitForEvent(): Promise<EventFromLogic<TLogic>>;\n run(\n ...[input]: undefined extends InputFrom<TLogic>\n ? [input?: InputFrom<TLogic>]\n : [input: InputFrom<TLogic>]\n ): Promise<OutputFrom<TLogic>>;\n}\n\n/**\n * Creates a host-neutral durable execution around pure actor transitions.\n *\n * The returned transition methods only calculate snapshots and tag their\n * effects. Persistence, retries, messaging, timers and child execution remain\n * responsibilities of the adapter.\n *\n * @experimental\n */\nexport function createDurable<TLogic extends AnyActorLogic>(\n logic: TLogic,\n adapter: DurableExecutionAdapter<TLogic>\n): DurableExecution<TLogic> {\n let nextTransitionIndex = adapter.transitionIndex ?? 0;\n const startingTransitionIndex = nextTransitionIndex;\n let lastTransitionIndex =\n nextTransitionIndex === 0 ? undefined : nextTransitionIndex - 1;\n\n if (!Number.isSafeInteger(nextTransitionIndex) || nextTransitionIndex < 0) {\n throw new RangeError('transitionIndex must be a non-negative safe integer');\n }\n\n const tagEffects = (\n effects: ExecutableActionObjectFromLogic<TLogic>[]\n ): DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[] => {\n const transitionIndex = nextTransitionIndex++;\n lastTransitionIndex = transitionIndex;\n return effects.map((effect, effectIndex) => ({\n id: `${transitionIndex}:${effectIndex}`,\n transitionIndex,\n effectIndex,\n effect\n }));\n };\n\n const execution: DurableExecution<TLogic> = {\n get nextTransitionIndex() {\n return nextTransitionIndex;\n },\n initialTransition(...args) {\n const [snapshot, effects] = initialTransition(logic, ...args);\n return [snapshot, tagEffects(effects)];\n },\n transition(snapshot, event) {\n const [nextSnapshot, effects] = transition(logic, snapshot, event);\n return [nextSnapshot, tagEffects(effects)];\n },\n async executeEffects(effects) {\n for (const { effect, ...metadata } of effects) {\n const runtime = adapter.runtime?.(metadata, effect) ?? {};\n if (effect.kind === 'action') {\n await adapter.executeAction(effect, metadata, runtime);\n } else {\n await effect.exec(runtime);\n }\n }\n },\n async waitForEvent() {\n if (lastTransitionIndex === undefined) {\n throw new Error('Cannot wait for an event before the first transition');\n }\n return adapter.waitForEvent({\n id: `event:${lastTransitionIndex}`,\n transitionIndex: lastTransitionIndex\n });\n },\n async run(...args) {\n if (\n startingTransitionIndex !== 0 ||\n nextTransitionIndex !== startingTransitionIndex\n ) {\n throw new DurableExecutionResumeError();\n }\n let [snapshot, effects] = execution.initialTransition(...args);\n await execution.executeEffects(effects);\n\n while ((snapshot as Snapshot<OutputFrom<TLogic>>).status === 'active') {\n const event = await execution.waitForEvent();\n [snapshot, effects] = execution.transition(snapshot, event);\n await execution.executeEffects(effects);\n }\n\n const terminalSnapshot = snapshot as Snapshot<OutputFrom<TLogic>>;\n if (terminalSnapshot.status === 'done') {\n return terminalSnapshot.output;\n }\n if (terminalSnapshot.status === 'error') {\n throw terminalSnapshot.error;\n }\n throw new DurableExecutionCancelledError();\n }\n };\n\n return execution;\n}\n","import { createInitEvent } from './eventUtils';\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 createSpawnEffect,\n finalizeTransitionResult\n} from './transitionActions.ts';\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 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 return [\n returnedSnapshot,\n executableActions as ExecutableActionObjectFromLogic<T>[]\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\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 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 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"],"names":["XSTATE_STOP","XSTATE_TERMINATE","createInitEvent","input","type","Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","lazyActorScope","execTerminateEffect","runtime","actor","system","termination","status","output","error","undefined","terminateActor","createTerminationEffect","actorScope","snapshot","Error","args","self","kind","exec","source","id","params","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","effect","noop","emptyActor","props","action","enqueueFn","fn","Object","assign","cancel","emit","log","raise","spawn","sendTo","stop","listen","subscribeTo","createEnqueueObject","snapshotActorRefs","WeakMap","lazySnapshotActorRefs","emptyKeyedActors","Map","getKeyedActors","peek","_peekKeyedActors","call","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","children","baseState","registeredActors","state","root","sessionId","set","copyRegisteredActors","reverseKeyedActors","create","_snapshot","sourceVersion","_register","_unregister","delete","registryKey","get","_set","existing","String","getAll","fromEntries","_hasInspectionObservers","_sendInspectionEvent","values","getSnapshotActorRef","created","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","size","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","complete","systemIdPrefix","freeze","nextSystemId","transitionEffectSignal","transitionEffectTargets","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","Array","from","toString","padStart","join","randomUUID","replaceAll","Date","now","Math","random","slice","createSystemIdPrefix","emptyScheduledTimers","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_isRunning","_keyedActors","actors","_reverseKeyedActors","options","_identity","systemId","nextSessionId","scheduler","_clock","_logger","createActorRef","restoredSnapshot","clock","logger","_scheduledTimers","_nextActorId","_recordSent","target","delay","_inspectionObservers","inspectionSource","_collectedSent","push","targetRef","targetId","schedule","existingId","_timerMap","timer","getSnapshot","timers","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","runtimeTarget","targetMachine","logic","isInternalEventType","_lastSourceRef","_send","changed","entries","inspect","observerOrFn","observer","Set","add","unsubscribe","resolvedInspectionEvent","rootId","forEach","spawnActor","startActor","stopActor","_stop","_terminate","sendEvent","emitEvent","_emit","scheduleTimer","cancelTimer","cancelAllTimers","_relay","length","includes","scheduledTimers","resetScheduledTimers","scheduledId","max","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","actionExecutor","Actor","trigger","_trigger","Proxy","_","eventType","payload","send","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_parent","_syncSnapshot","ref","_actorScope","_collectedMicrosteps","_collectedActions","_initialEffects","src","_deferred","_restored","resolvedOptions","parent","syncSnapshot","_systemRef","current","rootActor","createRuntimeSystem","_sessionId","requestedId","match","reservedId","Number","isSafeInteger","nextActorId","resolveActorId","persistedState","_setSnapshot","restoreSnapshot","_inert","initialTransition","actorRef","parentRef","_getLogger","defer","_defer","defineProperty","stopChild","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","transition","update","_next","deferred","i","deferredFn","_inspectTransition","sourceRef","microsteps","actions","sent","_flushInitialEffects","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","on","handler","listeners","select","selector","equalityFn","is","selected","actorId","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","nextState","caughtError","invokeId","reportError","toJSON","xstate$$type","getPersistedSnapshot","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","createMaterializedInertActorScope","actorLogic","sourceChildren","currentSnapshot","sourceSelf","snapshotRef","previousSelf","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","DurableExecutionCancelledError","super","name","DurableExecutionResumeError","adapter","nextTransitionIndex","transitionIndex","startingTransitionIndex","lastTransitionIndex","RangeError","tagEffects","map","effectIndex","execution","executableActions","executeEffects","metadata","executeAction","waitForEvent","run","terminalSnapshot"],"mappings":"oPAKO,MAGMA,EAAc,eACdC,EAAmB,oBCoHzB,SAASC,EAAgBC,GAC9B,MAAO,CAAEC,KDzHgB,eCyHGD,QAC9B,CC1HO,MAAME,EAKXC,WAAAA,CAAoBC,GAA2BC,KA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gBAC7B/W,EAAUY,GAAW8V,EAAUrF,WAAWrR,EAAUvB,SAC/CiY,EAAUE,eAAehW,EACjC,CAEA,MAAMqW,EAAmBjX,EACzB,GAAgC,SAA5BiX,EAAiBxX,OACnB,OAAOwX,EAAiBvX,OAE1B,GAAgC,UAA5BuX,EAAiBxX,OACnB,MAAMwX,EAAiBtX,MAEzB,MAAM,IAAIkW,CACZ,GAGF,OAAOa,CACT"}
1
+ {"version":3,"file":"xstate-durable.umd.min.js","sources":["../src/constants.ts","../src/eventUtils.ts","../src/Mailbox.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actorScope.ts","../src/transitionActions.ts","../src/snapshotActorRef.ts","../src/utils.ts","../src/system.ts","../src/State.ts","../src/createActor.ts","../src/getNextSnapshot.ts","../src/durable/index.ts","../src/transition.ts"],"sourcesContent":["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","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","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","/**\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 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 { 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 type { ActorSystemRuntime } 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 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 | { type: 'add'; actor: AnyActor; id: string }\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\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 };\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 | undefined\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id: id ?? actor.id };\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\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: (logic, options) => {\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? (logic as any).id\n } as AnyActor;\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, options?.id);\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 const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actor\n );\n action.childUpdate = { type: 'remove', actor };\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","import 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 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 into\n // a live runtime system.\n _hasInspectionObservers: () => false,\n _sendInspectionEvent: () => {}\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 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 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 { markSystemSnapshotDirty } from './snapshotActorRef.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/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined\n): string {\n if (requestedId !== undefined) {\n const match = /^x:(\\d+)$/.exec(requestedId);\n const reservedId = match ? Number(match[1]) : undefined;\n if (reservedId !== undefined && Number.isSafeInteger(reservedId)) {\n const nextActorId = Math.max(\n system._snapshot._nextActorId,\n reservedId + 1\n );\n if (nextActorId !== system._snapshot._nextActorId) {\n system._snapshot._nextActorId = nextActorId;\n markSystemSnapshotDirty(system);\n }\n }\n return requestedId;\n }\n\n const id = `x:${system._snapshot._nextActorId++}`;\n markSystemSnapshotDirty(system);\n return id;\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 * An external interpreter can override these operations while the default actor\n * system provides the local in-memory implementation.\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 /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\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 _nextActorId: number;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\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 _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 = {\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 _nextActorId?: number;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n _nextActorId: restoredSnapshot?._nextActorId ?? 0\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 const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n _lastSourceRef?: AnyActor;\n };\n const targetMachine = runtimeTarget.logic;\n const isInternalEvent =\n typeof targetMachine?.isInternalEventType === 'function' &&\n targetMachine.isInternalEventType(event.type);\n\n if (isInternalEvent && source !== target) {\n throw new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n\n // remember the last source for unified transition inspect event\n runtimeTarget._lastSourceRef = source;\n target._send(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 if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed = (this._children?.delete(actor.sessionId!) ?? false) || changed;\n } else {\n changed = 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 public spawnActor(): void {}\n\n public startActor(actor: AnyActor): void {\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n }\n\n public terminateActor(actor: AnyActor, termination: ActorTermination): void {\n (\n actor as AnyActor & { _terminate(value: ActorTermination): void }\n )._terminate(termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n this._recordSent(source, target, event);\n this._deliver(source, target, event);\n }\n\n public emitEvent(source: AnyActor, event: EventObject): void {\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public scheduleTimer(source: AnyActor, id: string, delay: number): void {\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void {\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void {\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n 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 { $$ACTOR_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';\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 /**\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 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 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 for (const id in children) {\n const child = children[id] as any;\n if (\n isDevelopment &&\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 childrenJson[id as keyof typeof childrenJson] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\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 timersJson[id] = {\n id: timer.id,\n delay: timer.delay,\n type: timer.type,\n event,\n target\n };\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n _nextActorId:\n getSnapshotActorRef(snapshot)?.systemState.snapshot._nextActorId,\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_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 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 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 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\nexport const $$ACTOR_TYPE = 1;\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 /** 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 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 private _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 const timers: Record<string, { id: string; delay: number }> =\n (\n this._snapshot as unknown as {\n timers?: Record<string, { id: string; delay: number }>;\n }\n ).timers ?? {};\n for (const timer of Object.values(timers)) {\n this.system.scheduleTimer(this, timer.id, timer.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 // do nothing\n if (isDevelopment) {\n // TODO: circular serialization issues\n // const eventString = ''; //JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.`\n );\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 public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\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(): Snapshot<unknown>;\n public getPersistedSnapshot(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\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 represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\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 { 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 }\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 type { ActorSystemRuntime } from '../system.ts';\nimport { initialTransition, transition } from '../transition.ts';\nimport type {\n AnyActorLogic,\n CustomExecutableActionObject,\n EventFromLogic,\n ExecutableActionObjectFromLogic,\n InputFrom,\n OutputFrom,\n Snapshot,\n SnapshotFrom\n} from '../types.ts';\n\nexport interface DurableEffectMetadata {\n /** Stable within one durable execution. */\n id: string;\n transitionIndex: number;\n effectIndex: number;\n}\n\nexport interface DurableWaitMetadata {\n /** Stable within one durable execution. */\n id: string;\n transitionIndex: number;\n}\n\nexport interface DurableEffect<TEffect> extends DurableEffectMetadata {\n effect: TEffect;\n}\n\nexport interface DurableExecutionAdapter<TLogic extends AnyActorLogic> {\n /**\n * Executes a custom action as a durable host step or activity. The host\n * should identify the action by `type` and memoize or deduplicate it using\n * `metadata.id`.\n */\n executeAction(\n action: CustomExecutableActionObject,\n metadata: DurableEffectMetadata,\n runtime: Partial<ActorSystemRuntime>\n ): void | PromiseLike<void>;\n /**\n * Creates the runtime used by one effect. Timers, messaging and\n * child actors should be translated to equivalent host operations. The\n * complete effect is provided for hosts that need serializable actor source,\n * input, event or target data beyond the runtime method arguments.\n */\n runtime?(\n metadata: DurableEffectMetadata,\n effect: ExecutableActionObjectFromLogic<TLogic>\n ): Partial<ActorSystemRuntime>;\n /** Waits durably for the next event addressed to this execution. */\n waitForEvent(\n metadata: DurableWaitMetadata\n ): EventFromLogic<TLogic> | PromiseLike<EventFromLogic<TLogic>>;\n /** Index assigned to the first transition. Defaults to `0`. */\n transitionIndex?: number;\n}\n\nexport class DurableExecutionCancelledError extends Error {\n constructor() {\n super('Durable execution was stopped');\n this.name = 'DurableExecutionCancelledError';\n }\n}\n\nexport class DurableExecutionResumeError extends Error {\n constructor() {\n super(\n 'run() can only start a fresh durable execution; resume checkpoints with transition() and the persisted snapshot'\n );\n this.name = 'DurableExecutionResumeError';\n }\n}\n\nexport interface DurableExecution<TLogic extends AnyActorLogic> {\n /** Index assigned to the next transition. Persist this with checkpoints. */\n readonly nextTransitionIndex: number;\n initialTransition(\n ...[input]: undefined extends InputFrom<TLogic>\n ? [input?: InputFrom<TLogic>]\n : [input: InputFrom<TLogic>]\n ): [\n snapshot: SnapshotFrom<TLogic>,\n effects: DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[]\n ];\n transition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventFromLogic<TLogic>\n ): [\n snapshot: SnapshotFrom<TLogic>,\n effects: DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[]\n ];\n executeEffects(\n effects: readonly DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[]\n ): Promise<void>;\n waitForEvent(): Promise<EventFromLogic<TLogic>>;\n run(\n ...[input]: undefined extends InputFrom<TLogic>\n ? [input?: InputFrom<TLogic>]\n : [input: InputFrom<TLogic>]\n ): Promise<OutputFrom<TLogic>>;\n}\n\n/**\n * Creates a host-neutral durable execution around pure actor transitions.\n *\n * The returned transition methods only calculate snapshots and tag their\n * effects. Persistence, retries, messaging, timers and child execution remain\n * responsibilities of the adapter.\n *\n * @experimental\n */\nexport function createDurable<TLogic extends AnyActorLogic>(\n logic: TLogic,\n adapter: DurableExecutionAdapter<TLogic>\n): DurableExecution<TLogic> {\n let nextTransitionIndex = adapter.transitionIndex ?? 0;\n const startingTransitionIndex = nextTransitionIndex;\n let lastTransitionIndex =\n nextTransitionIndex === 0 ? undefined : nextTransitionIndex - 1;\n\n if (!Number.isSafeInteger(nextTransitionIndex) || nextTransitionIndex < 0) {\n throw new RangeError('transitionIndex must be a non-negative safe integer');\n }\n\n const tagEffects = (\n effects: ExecutableActionObjectFromLogic<TLogic>[]\n ): DurableEffect<ExecutableActionObjectFromLogic<TLogic>>[] => {\n const transitionIndex = nextTransitionIndex++;\n lastTransitionIndex = transitionIndex;\n return effects.map((effect, effectIndex) => ({\n id: `${transitionIndex}:${effectIndex}`,\n transitionIndex,\n effectIndex,\n effect\n }));\n };\n\n const execution: DurableExecution<TLogic> = {\n get nextTransitionIndex() {\n return nextTransitionIndex;\n },\n initialTransition(...args) {\n const [snapshot, effects] = initialTransition(logic, ...args);\n return [snapshot, tagEffects(effects)];\n },\n transition(snapshot, event) {\n const [nextSnapshot, effects] = transition(logic, snapshot, event);\n return [nextSnapshot, tagEffects(effects)];\n },\n async executeEffects(effects) {\n for (const { effect, ...metadata } of effects) {\n const runtime = adapter.runtime?.(metadata, effect) ?? {};\n if (effect.kind === 'action') {\n await adapter.executeAction(effect, metadata, runtime);\n } else {\n await effect.exec(runtime);\n }\n }\n },\n async waitForEvent() {\n if (lastTransitionIndex === undefined) {\n throw new Error('Cannot wait for an event before the first transition');\n }\n return adapter.waitForEvent({\n id: `event:${lastTransitionIndex}`,\n transitionIndex: lastTransitionIndex\n });\n },\n async run(...args) {\n if (\n startingTransitionIndex !== 0 ||\n nextTransitionIndex !== startingTransitionIndex\n ) {\n throw new DurableExecutionResumeError();\n }\n let [snapshot, effects] = execution.initialTransition(...args);\n await execution.executeEffects(effects);\n\n while ((snapshot as Snapshot<OutputFrom<TLogic>>).status === 'active') {\n const event = await execution.waitForEvent();\n [snapshot, effects] = execution.transition(snapshot, event);\n await execution.executeEffects(effects);\n }\n\n const terminalSnapshot = snapshot as Snapshot<OutputFrom<TLogic>>;\n if (terminalSnapshot.status === 'done') {\n return terminalSnapshot.output;\n }\n if (terminalSnapshot.status === 'error') {\n throw terminalSnapshot.error;\n }\n throw new DurableExecutionCancelledError();\n }\n };\n\n return execution;\n}\n","import { createInitEvent } from './eventUtils';\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 createSpawnEffect,\n finalizeTransitionResult\n} from './transitionActions.ts';\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 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 return [\n returnedSnapshot,\n executableActions as ExecutableActionObjectFromLogic<T>[]\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\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 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 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"],"names":["XSTATE_STOP","XSTATE_TERMINATE","createInitEvent","input","type","Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","lazyActorScope","execTerminateEffect","runtime","actor","system","termination","status","output","error","undefined","terminateActor","createTerminationEffect","actorScope","snapshot","Error","args","self","kind","exec","source","id","params","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","effect","noop","emptyActor","props","action","enqueueFn","fn","Object","assign","cancel","emit","log","raise","spawn","sendTo","stop","listen","subscribeTo","createEnqueueObject","snapshotActorRefs","WeakMap","lazySnapshotActorRefs","emptyKeyedActors","Map","getKeyedActors","peek","_peekKeyedActors","call","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","children","baseState","registeredActors","state","root","sessionId","set","copyRegisteredActors","reverseKeyedActors","create","_snapshot","sourceVersion","_register","_unregister","delete","registryKey","get","_set","existing","String","getAll","fromEntries","_hasInspectionObservers","_sendInspectionEvent","values","getSnapshotActorRef","created","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","size","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","complete","systemIdPrefix","freeze","nextSystemId","transitionEffectSignal","transitionEffectTargets","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","Array","from","toString","padStart","join","randomUUID","replaceAll","Date","now","Math","random","slice","createSystemIdPrefix","emptyScheduledTimers","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_isRunning","_keyedActors","actors","_reverseKeyedActors","options","_identity","systemId","nextSessionId","scheduler","_clock","_logger","createActorRef","restoredSnapshot","clock","logger","_scheduledTimers","_nextActorId","_recordSent","target","delay","_inspectionObservers","inspectionSource","_collectedSent","push","targetRef","targetId","schedule","existingId","_timerMap","timer","getSnapshot","timers","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","runtimeTarget","targetMachine","logic","isInternalEventType","_lastSourceRef","_send","changed","entries","inspect","observerOrFn","observer","Set","add","unsubscribe","resolvedInspectionEvent","rootId","forEach","spawnActor","startActor","stopActor","_stop","_terminate","sendEvent","emitEvent","_emit","scheduleTimer","cancelTimer","cancelAllTimers","_relay","length","includes","scheduledTimers","resetScheduledTimers","scheduledId","max","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","actionExecutor","Actor","trigger","_trigger","Proxy","_","eventType","payload","send","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_parent","_syncSnapshot","ref","_actorScope","_collectedMicrosteps","_collectedActions","_initialEffects","src","_deferred","_restored","resolvedOptions","parent","syncSnapshot","_systemRef","current","rootActor","createRuntimeSystem","_sessionId","requestedId","match","reservedId","Number","isSafeInteger","nextActorId","resolveActorId","persistedState","_setSnapshot","restoreSnapshot","_inert","initialTransition","actorRef","parentRef","_getLogger","defer","_defer","defineProperty","stopChild","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","transition","update","_next","deferred","i","deferredFn","_inspectTransition","sourceRef","microsteps","actions","sent","_flushInitialEffects","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","on","handler","listeners","select","selector","equalityFn","is","selected","actorId","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","nextState","caughtError","invokeId","reportError","toJSON","xstate$$type","getPersistedSnapshot","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","createMaterializedInertActorScope","actorLogic","sourceChildren","currentSnapshot","sourceSelf","snapshotRef","previousSelf","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","DurableExecutionCancelledError","super","name","DurableExecutionResumeError","adapter","nextTransitionIndex","transitionIndex","startingTransitionIndex","lastTransitionIndex","RangeError","tagEffects","map","effectIndex","execution","executableActions","executeEffects","metadata","executeAction","waitForEvent","run","terminalSnapshot"],"mappings":"oPAKO,MAGMA,EAAc,eACdC,EAAmB,oBCoHzB,SAASC,EAAgBC,GAC9B,MAAO,CAAEC,KDzHgB,eCyHGD,QAC9B,CC1HO,MAAME,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,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