xstate 6.0.0-alpha.49 → 6.0.0-alpha.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{StateMachine-0adb3a70.cjs.js → StateMachine-1e6ee14a.cjs.js} +18 -6
- package/dist/{StateMachine-29450e6d.development.cjs.js → StateMachine-70df737c.development.cjs.js} +18 -6
- package/dist/{StateMachine-2af31c11.esm.js → StateMachine-8cea8974.esm.js} +18 -6
- package/dist/{StateMachine-faf50c5c.development.esm.js → StateMachine-bc28e207.development.esm.js} +18 -6
- package/dist/{createActor-b4dd05ae.cjs.js → createActor-27fd819f.cjs.js} +80 -10
- package/dist/{createActor-88709f74.development.esm.js → createActor-74e185ee.development.esm.js} +80 -11
- package/dist/{createActor-268165d4.esm.js → createActor-ad3a1abe.esm.js} +80 -11
- package/dist/{createActor-a1e0dffb.development.cjs.js → createActor-ea9a560c.development.cjs.js} +80 -10
- package/dist/declarations/src/effectDescriptor.d.ts +9 -0
- package/dist/declarations/src/index.d.ts +1 -1
- package/dist/declarations/src/inspection.d.ts +24 -7
- package/dist/declarations/src/runtimeHelpers.d.ts +6 -3
- package/dist/declarations/src/system.d.ts +38 -3
- package/dist/declarations/src/types.d.ts +35 -2
- package/dist/{effectDescriptor-7ff6802f.development.cjs.js → effectDescriptor-16b6f3b4.cjs.js} +12 -1
- package/dist/{effectDescriptor-39d22100.development.esm.js → effectDescriptor-38598bd3.development.esm.js} +12 -1
- package/dist/{effectDescriptor-be348e50.cjs.js → effectDescriptor-40ca302f.development.cjs.js} +12 -1
- package/dist/{effectDescriptor-30c9a744.esm.js → effectDescriptor-7dac431a.esm.js} +12 -1
- package/dist/{fsm-e18a7cb4.development.esm.js → fsm-25f10f50.development.esm.js} +1 -1
- package/dist/{fsm-c1316948.development.cjs.js → fsm-697ffd89.development.cjs.js} +1 -1
- package/dist/{fsm-7a2e9697.cjs.js → fsm-7adaf0ea.cjs.js} +1 -1
- package/dist/{fsm-b804b3e9.esm.js → fsm-dc1bb88b.esm.js} +1 -1
- package/dist/{types-fbabaeee.cjs.js → types-a14db10c.development.cjs.js} +6 -1
- package/dist/{types-3c3455f7.esm.js → types-a313e7e2.esm.js} +6 -1
- package/dist/{types-b3fea5bd.development.cjs.js → types-bc22b358.cjs.js} +6 -1
- package/dist/{types-adda3842.development.esm.js → types-c37714eb.development.esm.js} +6 -1
- package/dist/xstate-actors.cjs.js +12 -3
- package/dist/xstate-actors.development.cjs.js +12 -3
- package/dist/xstate-actors.development.esm.js +13 -4
- package/dist/xstate-actors.esm.js +13 -4
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.js +2 -2
- package/dist/xstate-durable.development.cjs.js +2 -2
- package/dist/xstate-durable.development.esm.js +2 -2
- package/dist/xstate-durable.esm.js +2 -2
- package/dist/xstate-durable.umd.min.js +1 -1
- package/dist/xstate-durable.umd.min.js.map +1 -1
- package/dist/xstate-fsm.cjs.js +2 -2
- package/dist/xstate-fsm.development.cjs.js +2 -2
- package/dist/xstate-fsm.development.esm.js +2 -2
- package/dist/xstate-fsm.esm.js +2 -2
- package/dist/xstate-graph.cjs.js +2 -2
- package/dist/xstate-graph.development.cjs.js +2 -2
- package/dist/xstate-graph.development.esm.js +2 -2
- package/dist/xstate-graph.esm.js +2 -2
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-scxml.cjs.js +3 -3
- package/dist/xstate-scxml.development.cjs.js +3 -3
- package/dist/xstate-scxml.development.esm.js +3 -3
- package/dist/xstate-scxml.esm.js +3 -3
- package/dist/xstate-scxml.umd.min.js +1 -1
- package/dist/xstate-scxml.umd.min.js.map +1 -1
- package/dist/xstate-validation.cjs.js +1 -1
- package/dist/xstate-validation.development.cjs.js +1 -1
- package/dist/xstate-validation.development.esm.js +1 -1
- package/dist/xstate-validation.esm.js +1 -1
- package/dist/xstate.cjs.js +5 -5
- package/dist/xstate.development.cjs.js +5 -5
- package/dist/xstate.development.esm.js +8 -8
- package/dist/xstate.esm.js +8 -8
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xstate-actors.umd.min.js","sources":["../src/Mailbox.ts","../src/constants.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/utils.ts","../src/actors/subscription.ts","../src/transitionActions.ts","../src/actions.ts","../src/delay.ts","../src/snapshotActorRef.ts","../src/runtimeHelpers.ts","../src/system.ts","../src/createActor.ts","../src/validation.ts","../src/actors/logic.ts","../src/actors/callback.ts","../src/actors/observable.ts","../src/actors/promise.ts","../src/actors/index.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = '@xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\nexport const XSTATE_STOP = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\nexport function createAfterEventId(delayRef: number | string, id: string) {\n return `xstate.after.${delayRef}.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout', stateId: id };\n}\n\nexport function createTimeoutEventId(id: string) {\n return `xstate.timeout.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createInvokeTimeoutEventId(invokeId: string) {\n return `xstate.timeout.actor.${invokeId}`;\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import { XSTATE_STOP } from '../constants.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n return {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n 'xstate.listener'\n );\n}\n\n// Singleton logic instance\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import 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 { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, 'xstate.subscription');\n}\n\n// Singleton logic instance\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\n","import isDevelopment from '#is-development';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport { createErrorPlatformEvent } from './eventUtils.ts';\nimport {\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime\n} from './system.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport { getEventOutput } from './utils.ts';\nimport type {\n Action,\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableActionObject,\n CustomExecutableActionObject,\n EmitExecutableActionObject,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n RaiseExecutableActionObject,\n SendToExecutableActionObject,\n Snapshot,\n SpecialExecutableAction,\n SpawnExecutableActionObject,\n StartExecutableActionObject,\n StopExecutableActionObject,\n TerminateExecutableActionObject\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableActionObject\n): void | PromiseLike<void> | undefined {\n return this.action?.(...this.args);\n}\n\nfunction execEmitEffect(\n this: EmitExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.emitEvent!(this.source, this.event);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableActionObject {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableActionObject {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay ?? 0);\n}\n\nfunction execSendToEffect(\n this: SendToExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, this.id);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableActionObject,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableAction(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n if (!snapshot.timers?.[effect.id]) {\n return snapshot;\n }\n const timers = { ...snapshot.timers };\n delete timers[effect.id];\n return { ...snapshot, timers };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n let nextTimerId = snapshot._nextTimerId ?? 0;\n const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;\n effect.id = id;\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n\n return {\n ...snapshot,\n timers: {\n ...snapshot.timers,\n [id]: {\n id,\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n }\n },\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : `Cannot stop non-child actor ${update.actor.id}`\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(`Actor source '${source}' is not provided`);\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved namespace.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (isDevelopment && prefix.startsWith('xstate.')) {\n throw new Error(\n `Child actor ids with the \"xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : `Child actor id '${id}' is already in use`\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n if (typeof raisedEvent === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${raisedEvent}\" }) instead`\n : `Only event objects may be used with raise`\n );\n }\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? src ?? (logic as any).id\n } as AnyActor;\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n if (!actor) {\n internalEvents.push(\n createErrorPlatformEvent('communication', {\n message: 'Unable to send event to an undefined actor',\n event\n })\n );\n return;\n }\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n return createEnqueueObject(props, (action, ...args) => {\n pushBuiltInAction(actions, action, ...args);\n });\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableAction> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, id] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n id\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\nfunction createStartEffect(actor: AnyActor): StartExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\nexport function createSpawnEffect(\n actor: AnyActor\n): SpawnExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableActionObject {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error('Cannot terminate an active or stopped actor');\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableActionObject>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableActionObject>\n): StartExecutableActionObject[] {\n const attachedStarts: StartExecutableActionObject[] = [];\n const childStarts: StartExecutableActionObject[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\nexport function isBuiltInExecutableAction(\n action: ExecutableActionObject\n): action is SpecialExecutableAction {\n return action.kind === 'builtin';\n}\n\n/** Executes transition effects sequentially, awaiting each runtime operation. */\nexport async function executeEffects(\n effects: readonly ExecutableActionObject[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of actions) {\n const actionArgs = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n },\n actorScope\n )\n : {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n };\n\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...actionRecord.args)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (resolvedAction && '_special' in resolvedAction) {\n executableActions.push({\n kind: 'action',\n exec: execCustomEffect,\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : ((action as any).type ?? '(anonymous)')\n : action.name || '(anonymous)',\n params: actionParams,\n args: [],\n action: undefined\n });\n\n const specialAction = resolvedAction as unknown as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n\n const res = specialAction(actionArgs as any, emptyEnqueueObject);\n\n if (res && ('context' in res || 'children' in res)) {\n // Special-action patches never change `nodes`, so a shallow clone is\n // equivalent to `cloneMachineSnapshot` — and keeps this module (and\n // non-machine logic like `createFSM`) independent of State.ts.\n intermediateSnapshot = {\n ...intermediateSnapshot,\n ...(res.context !== undefined\n ? {\n context: mergeContextPatch(\n intermediateSnapshot.context,\n res.context\n )\n }\n : {}),\n ...('children' in res ? { children: res.children } : {})\n };\n }\n continue;\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, action.args)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action ? action.args : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableAction = executableAction as ExecutableActionObject;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableAction,\n actorScope\n );\n executableActions.push(typedExecutableAction);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n\nconst emptyEnqueueObject = createEnqueueObject({}, noop);\n","import isDevelopment from '#is-development';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : `Only event objects may be used with sendTo`\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n _event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, sendId: string) => {\n return actorScope.system.cancelTimer(actorScope.self, sendId);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\n}\n","import { hasAmbientInspector } from './inspectionAmbient.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${String(registryKey)}' already exists.`\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport type { ActorTermination, AnyActor, AnyEventObject } from './types.ts';\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n return (actor.getSnapshot() as { effects?: StepEffects }).effects?.[key];\n}\n\nfunction waitForStep<TStepOutput>(\n actor: AnyActor,\n key: string\n): Promise<TStepOutput> {\n return new Promise((resolve, reject) => {\n const subscription = actor.subscribe((snapshot) => {\n const effect = (snapshot as { effects?: StepEffects }).effects?.[key];\n if (effect?.status === 'done') {\n subscription.unsubscribe();\n resolve(effect.output as TStepOutput);\n } else if (effect?.status === 'error') {\n subscription.unsubscribe();\n reject(effect.error as Error);\n }\n });\n });\n}\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n if (effect?.status === 'active') {\n return waitForStep(actor, key);\n }\n\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n try {\n const output = await exec();\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n return output;\n } catch (error) {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n throw error;\n }\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n assertEventCanBeSent(source, target, event);\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n _lastSourceRef?: AnyActor;\n _send(event: AnyEventObject): void;\n };\n\n runtimeTarget._lastSourceRef = source;\n runtimeTarget._send(event);\n}\n\n/**\n * Ensures internal events cannot cross an actor boundary from an external\n * sender. Host runtimes must call this before taking ownership of delivery.\n */\nexport function assertEventCanBeSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n throw new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","import isDevelopment from '#is-development';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription,\n AnyActorLogic,\n ActorOptions\n} from './types.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { toObserver } from './utils.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n assertEventCanBeSent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n id: string;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, id: string, delay: number): void;\n cancel(source: AnyActor, id: string): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet systemIdPrefix: string | undefined;\nlet nextSystemId = 0;\n\n/** @internal */\nexport const transitionEffectSignal = new Error('Transition effect');\n/** @internal */\nexport const transitionEffectTargets: AnyActor[] = [];\n\nfunction createSystemIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createSystemId(): string {\n systemIdPrefix ??= createSystemIdPrefix();\n return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n systemId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Anonymous machines get the placeholder id '(machine)'; only named logic\n // earns a named id prefix.\n return typeof logicId === 'string' &&\n logicId.length &&\n logicId !== '(machine)'\n ? logicId\n : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.systemId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Publishes an emitted event. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /** Schedules a logical timer. */\n scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, id: string): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry: the default logs in development and emits an\n * inspection event.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: string\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(actor: AnyActor, id: string): ScheduledTimerId {\n return `${actor.sessionId}.${id}` as ScheduledTimerId;\n}\n\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n systemId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n systemId: createSystemId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n ) {\n const restoredSnapshot =\n typeof options.snapshot === 'object' && options.snapshot !== null\n ? (options.snapshot as {\n scheduler?: Record<ScheduledTimerId, ScheduledTimer>;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, id: string, delay: number): void {\n const existingId = createScheduledTimerId(source, id);\n if (this._timerMap?.[existingId] !== undefined) {\n this.cancel(source, id);\n }\n\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n id,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n const scheduledTimerId = createScheduledTimerId(source, id);\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, id });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, id: string): void {\n const scheduledTimerId = createScheduledTimerId(source, id);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.id);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${registryKey as string}' already exists.`\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n assertEventCanBeSent(source, target, event);\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: string\n ): void | PromiseLike<void> {\n this._sendInspectionEvent({\n type: '@xstate.deadletter',\n actorRef: target,\n sourceRef: source,\n event,\n reason\n });\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason);\n }\n if (isDevelopment) {\n console.warn(\n `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n return override(source, id, delay);\n }\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, id);\n }\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, id } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n id,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotFor,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableActionObject,\n Readable,\n ActorLogicTransitionResult\n} from './types.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\n/**\n * Marks a serialized object as an actor reference (`xstate$type` in JSON\n * output and persisted context).\n */\nexport const ACTOR_REF_TYPE = 'actorRef';\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableActionObject[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (event: EventFromLogic<TLogic>) => void;\n private mailbox?: Mailbox<EventFromLogic<TLogic>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableActionObject[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n snapshot: resolvedOptions.snapshot ?? resolvedOptions.state,\n createActorRef\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const persistedState = options?.snapshot ?? options?.state;\n this._restored = persistedState !== undefined;\n try {\n if (persistedState) {\n this._setSnapshot(\n this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n );\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._setSnapshot({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>);\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n this.system.emitEvent(this, event);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableActionObject) => void {\n const actionExecutor = (action: ExecutableActionObject) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : `Cannot stop non-child actor ${child.id}`\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableActionObject): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n void action.exec();\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n type RestoredTimer = { id: string; delay: number; startedAt?: number };\n const timers =\n (\n this._snapshot as unknown as {\n timers?: Record<string, RestoredTimer>;\n }\n ).timers ?? {};\n // startedAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of Object.values(timers)) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.startedAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.startedAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, timer.id, delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n private _error(err: unknown): void {\n this._stopProcedure();\n if (!this.observers?.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n } else {\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n safeCall(errorListener, err);\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(\n this._lastSourceRef,\n this as AnyActor,\n event,\n 'stopped'\n );\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: its `id`, `address`,\n * and registered source key (when the actor was created from one).\n */\n public toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: this.id,\n address: this.address,\n src: typeof this.src === 'string' ? this.src : undefined\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n public getPersistedSnapshot(\n options?: unknown\n ): Snapshot<unknown> & PersistedSnapshotFor<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START,\n XSTATE_STOP\n} from '../constants.ts';\nimport { createInitEvent } from '../eventUtils.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { ActorSystemRuntime, AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n finalizeTransitionResult,\n createCustomEffect,\n createEmitEffect,\n createSendToEffect\n} from '../transitionActions.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n ActorScope,\n AnyActorRef,\n EventObject,\n ExecutableActionObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type LogicSnapshot<TContext, TOutput, TInput> = Snapshot<TOutput> & {\n context: TContext;\n input: TInput | undefined;\n effects?: Record<string, LogicEffectState>;\n};\n\nexport type LogicEffectState =\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown };\n\nexport interface LogicArgs<TContext, TEvent extends EventObject, TInput> {\n context: TContext;\n event: TEvent;\n input: TInput;\n system: AnyActorSystem;\n self: LogicActorRef<TContext, unknown, TEvent, TInput>;\n}\n\nexport type LogicEffect<\n _TEvent extends EventObject,\n _TEmitted extends EventObject\n> = ExecutableActionObject;\n\nexport interface LogicEnqueue<\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n emit: (emitted: TEmitted) => void;\n sendBack: (event: EventObject) => void;\n raise: (event: TEvent) => void;\n effect: {\n (\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n };\n}\n\nexport type LogicPatch<TContext, TOutput, TInput> = Partial<{\n context: TContext;\n input: TInput | undefined;\n status: LogicSnapshot<TContext, TOutput, TInput>['status'];\n output: TOutput;\n error: unknown;\n effects: Record<string, LogicEffectState>;\n}>;\n\nexport type LogicFunction<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> = (\n args: LogicArgs<TContext, TEvent, TInput>,\n enq: LogicEnqueue<TEvent, TEmitted>\n) => void | LogicPatch<TContext, TOutput, TInput>;\n\nexport interface LogicConfig<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n id?: string;\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n context: TContext | ((args: { input: TInput }) => TContext);\n run: LogicFunction<TContext, TOutput, TEvent, TInput, TEmitted>;\n}\n\ninterface LogicTransition<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> {\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): [\n LogicSnapshot<TContext, TOutput, TInput>,\n LogicEffect<TEvent, TEmitted>[]\n ];\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): LogicSnapshot<TContext, TOutput, TInput>;\n}\n\nexport type LogicActorLogic<\n TContext,\n TOutput,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = Omit<\n ActorLogic<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >,\n 'transition'\n> & {\n id?: string;\n transition: LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n};\n\nexport type LogicActorRef<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput\n> = ActorRefFromLogic<LogicActorLogic<TContext, TOutput, TEvent, TInput>>;\n\nconst effectStates = new WeakMap<\n AnyActorRef,\n Map<PropertyKey, { cleanup?: () => void }>\n>();\n\nfunction getEffectState(self: AnyActorRef) {\n let state = effectStates.get(self);\n if (!state) {\n state = new Map();\n effectStates.set(self, state);\n }\n return state;\n}\n\nfunction executeLogicEffect(\n self: AnyActorRef,\n key: string | undefined,\n effect: () => void | (() => void)\n): void {\n const state = getEffectState(self);\n if (key !== undefined && state.has(key)) {\n return;\n }\n const cleanup = effect();\n state.set(key ?? Symbol(), {\n cleanup: typeof cleanup === 'function' ? cleanup : undefined\n });\n}\n\nfunction cleanupLogicEffects(self: AnyActorRef): void {\n const state = effectStates.get(self);\n if (!state) {\n return;\n }\n for (const { cleanup } of state.values()) {\n cleanup?.();\n }\n effectStates.delete(self);\n}\n\nfunction resolveContext<TContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext),\n input: TInput\n) {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : context;\n}\n\nexport function createLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput,\n const TInputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & {\n schemas: { input: TInputSchema; output?: undefined };\n }\n): LogicActorLogic<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: undefined; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> {\n const calculateTransition = ((snapshot, event, actorScope) => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n\n if (event.type === XSTATE_STOP) {\n return [\n {\n ...snapshot,\n status: 'stopped',\n input: undefined\n },\n [\n createCustomEffect('xstate.logic.cleanup', () =>\n cleanupLogicEffects(actorScope.self)\n )\n ]\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_START) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: { status: 'active' }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'done',\n output: (event as any).output\n }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'error',\n error: (event as any).error\n }\n }\n },\n []\n ];\n }\n\n const effects: LogicEffect<TEvent, TEmitted>[] = [];\n const trackedEffects: Record<string, LogicEffectState> = {};\n const enqueueEffect = (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ) => {\n if (snapshot.effects?.[key]) {\n return;\n }\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, key, () => exec(runtime)),\n { key }\n )\n );\n trackedEffects[key] = { status: 'active' };\n };\n const enq: LogicEnqueue<TEvent, TEmitted> = {\n emit: (emitted) => {\n effects.push(createEmitEffect(actorScope, emitted));\n },\n sendBack: (sentEvent) => {\n const parent = actorScope.self._parent;\n if (parent) {\n effects.push(createSendToEffect(actorScope, parent, sentEvent));\n }\n },\n raise: (raisedEvent) => {\n effects.push(\n createSendToEffect(actorScope, actorScope.self, raisedEvent)\n );\n },\n effect: ((keyOrExec, maybeExec) => {\n if (typeof keyOrExec === 'string') {\n enqueueEffect(keyOrExec, maybeExec);\n return;\n }\n const exec = keyOrExec as (\n runtime?: Partial<ActorSystemRuntime>\n ) => void | (() => void);\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, undefined, () =>\n exec(runtime)\n )\n )\n );\n }) as LogicEnqueue<TEvent, TEmitted>['effect']\n };\n\n const patch = config.run(\n {\n context: snapshot.context,\n event,\n input: snapshot.input!,\n system: actorScope.system,\n self: actorScope.self as any,\n emit: actorScope.emit\n } as LogicArgs<TContext, TEvent, TInput>,\n enq\n );\n\n const nextSnapshot = {\n ...snapshot,\n ...(patch || {})\n } as LogicSnapshot<TContext, TOutput, TInput>;\n\n if ('context' in snapshot || patch?.context !== undefined) {\n (nextSnapshot as any).context = patch?.context ?? snapshot.context;\n }\n if (patch?.effects || Object.keys(trackedEffects).length) {\n (nextSnapshot as any).effects = {\n ...snapshot.effects,\n ...patch?.effects,\n ...trackedEffects\n };\n }\n\n return finalizeTransitionResult(actorScope, snapshot, [\n nextSnapshot,\n effects\n ]);\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const transition = ((snapshot, event, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'event',\n logic,\n event,\n eventOrigin: (actorScope.self as any)._lastSourceRef\n ? 'actor'\n : 'external'\n });\n }\n const result = calculateTransition(snapshot, event, actorScope);\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'result',\n logic,\n snapshot: result[0],\n effects: result[1]\n });\n }\n return result;\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const logic: LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> = {\n id: config.id,\n config,\n validator: config.validator,\n transition,\n start: (snapshot, actorScope, options) => {\n if (!options?.restored) {\n return;\n }\n const [nextSnapshot, effects] = transition(\n snapshot,\n createInitEvent(snapshot.input) as unknown as TEvent,\n actorScope\n );\n Object.assign(snapshot, nextSnapshot);\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n },\n initialTransition: (input, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'input',\n logic,\n input\n });\n }\n const context = resolveContext(config.context, input);\n const snapshot = {\n status: 'active' as const,\n output: undefined,\n error: undefined,\n input\n };\n\n if (context !== undefined) {\n (snapshot as any).context = context;\n }\n\n return transition(\n { ...snapshot } as LogicSnapshot<TContext, TOutput, TInput>,\n createInitEvent(input) as unknown as TEvent,\n actorScope\n );\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\ninterface CallbackInstanceState<TEvent extends EventObject> {\n receivers: Set<(e: TEvent) => void> | undefined;\n dispose: (() => void) | void;\n}\n\nconst instanceStates = /* #__PURE__ */ new WeakMap<\n AnyActorRef,\n CallbackInstanceState<any>\n>();\n\nexport type CallbackSnapshot<TInput> = Snapshot<undefined> & {\n input: TInput;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n CallbackSnapshot<TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createCallbackLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createCallbackLogic, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = createCallbackLogic<Event, Input>(\n * ({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef<Event, Input>\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * }\n * );\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link createCallbackLogic}\n */\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorRefFromLogic<CallbackActorLogic<TEvent, TInput>>;\n\ntype Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type CallbackLogicFunction<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n sendBack,\n receive,\n emit\n}: {\n /**\n * Data that was provided to the callback actor\n *\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /** The actor system to which the callback actor belongs */\n system: AnyActorSystem;\n /** The parent actor of the callback actor */\n self: CallbackActorRef<TEvent>;\n /** A function that can send events back to the parent actor */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument; the\n * listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n emit: (emitted: TEmitted) => void;\n}) => (() => void) | void;\n\nexport interface CallbackLogicConfig<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: CallbackLogicFunction<TEvent, TSentEvent, TInput, TEmitted>;\n}\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = createCallbackLogic(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createCallbackLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<\n TEvent,\n AnyEventObject,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): CallbackActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callback: CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callbackOrConfig:\n | CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n | CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted> {\n const callback =\n typeof callbackOrConfig === 'function'\n ? callbackOrConfig\n : callbackOrConfig.run;\n const schemas =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.schemas;\n const validator =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.validator;\n\n return createBaseLogic<undefined, undefined, TEvent, TInput, TEmitted>({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n const emit = (args as any).emit as (emitted: TEmitted) => void;\n const callbackState = instanceStates.get(self as any);\n callbackState?.receivers?.forEach((receiver) => receiver(event));\n\n enq.effect('callback', () => {\n const callbackState: CallbackInstanceState<TEvent> = {\n receivers: undefined,\n dispose: undefined\n };\n\n instanceStates.set(self as any, callbackState);\n\n callbackState.dispose = callback({\n input,\n system,\n self: self as any,\n sendBack: (event) => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n const parent = (self as any)._parent;\n if (parent) {\n system._relay(self as any, parent, event);\n }\n },\n receive: (listener) => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit: emit as (emitted: TEmitted) => void\n });\n\n return () => {\n instanceStates.delete(self as any);\n callbackState.receivers?.clear();\n callbackState.dispose?.();\n };\n });\n }\n }) as unknown as CallbackActorLogic<TEvent, TInput, TEmitted>;\n}\n","import { XSTATE_INIT, XSTATE_STOP } from '../constants';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot,\n Subscribable,\n Subscription\n} from '../types';\nimport { createLogic as createBaseLogic } from './logic.ts';\nimport { finalizeTransitionResult } from '../transitionActions.ts';\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\nexport type ObservableSnapshot<\n TContext,\n TInput extends NonReducibleUnknown\n> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createObservableLogic` or\n * `createEventObservableLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = createObservableLogic<Context, Input>(\n * ({ input, self }) => {\n * self;\n * // ^? ObservableActor<Event, Input>\n *\n * return interval(input.period ?? 1_000);\n * }\n * );\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActor<Event, Input>\n * ```\n *\n * @see {@link createObservableLogic}\n * @see {@link createEventObservableLogic}\n */\nexport type ObservableActorRef<TContext> = ActorRefFromLogic<\n ObservableActorLogic<TContext, any>\n>;\n\ntype ObservableActor<\n TContext,\n TInput extends NonReducibleUnknown = any,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<ObservableActorLogic<TContext, TInput, TEmitted>>;\n\nexport type ObservableLogicFunction<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TContext, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TContext>;\n\nexport interface ObservableLogicConfig<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: ObservableLogicFunction<TContext, TInput, TEmitted>;\n}\n\nexport type EventObservableLogicFunction<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TEvent, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TEvent>;\n\nexport interface EventObservableLogicConfig<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: EventObservableLogicFunction<TEvent, TInput, TEmitted>;\n}\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = createObservableLogic((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nexport function createObservableLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<TContext, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreator: ObservableLogicFunction<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreatorOrConfig:\n | ObservableLogicFunction<TContext, TInput, TEmitted>\n | ObservableLogicConfig<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted> {\n const observableCreator =\n typeof observableCreatorOrConfig === 'function'\n ? observableCreatorOrConfig\n : observableCreatorOrConfig.run;\n const schemas =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.schemas;\n const validator =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.validator;\n\n return createBaseLogic<\n TContext | undefined,\n undefined,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT: {\n return {\n context: event.data as TContext\n };\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n status: 'error',\n error: (event as any).data,\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'error', error: (event as any).data }\n }\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n status: 'done',\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'done' }\n }\n };\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const subscription = observableCreator({\n input,\n system,\n self: self as any,\n emit: ((event: TEmitted) =>\n void runtime.emitEvent!(actorSelf, event)) as (\n emitted: TEmitted\n ) => void\n }).subscribe({\n next: (value) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: (err) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n sendSelf({\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n\n return () => subscription.unsubscribe();\n });\n }\n }) as unknown as ObservableActorLogic<TContext, TInput, TEmitted>;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * createEventObservableLogic,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = createEventObservableLogic(\n * () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<TEvent, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservable: EventObservableLogicFunction<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservableOrConfig:\n | EventObservableLogicFunction<TEvent, TInput, TEmitted>\n | EventObservableLogicConfig<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted> {\n const lazyObservable =\n typeof lazyObservableOrConfig === 'function'\n ? lazyObservableOrConfig\n : lazyObservableOrConfig.run;\n const validator =\n typeof lazyObservableOrConfig === 'function'\n ? undefined\n : lazyObservableOrConfig.validator;\n\n // TODO: event types\n const logic: ObservableActorLogic<TEvent, TInput, TEmitted> = {\n config: lazyObservableOrConfig,\n validator,\n transition: (state, event, actorScope) => {\n if (state.status !== 'active') {\n return [state, []];\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_OBSERVABLE_COMPLETE:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return [\n {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n },\n []\n ];\n default:\n return [state, []];\n }\n },\n initialTransition: (input, _) => {\n if (validator) {\n assertValid(validator, { kind: 'input', logic, input });\n }\n const snapshot = {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>;\n return [snapshot, []];\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n start: (state, { self, system, emit }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self,\n emit: (event) => {\n void emit(event);\n }\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot: any) => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n","import { parseDelayToMilliseconds } from '../delay.ts';\nimport { runStep } from '../runtimeHelpers.ts';\nimport { XSTATE_INIT } from '../constants.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\nexport type AsyncSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nconst XSTATE_ASYNC_RESOLVE = 'xstate.async.resolve';\nconst XSTATE_ASYNC_REJECT = 'xstate.async.reject';\n\nexport type AsyncActorLogic<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n AsyncSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\nexport type AsyncActorRef<TOutput> = ActorRefFromLogic<\n AsyncActorLogic<TOutput, unknown>\n>;\n\ntype AsyncActor<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<AsyncActorLogic<TOutput, TInput, TEmitted>>;\n\nexport interface LogicArgs<TOutput, TInput> {\n /** Data that was provided to the async actor. */\n input: TInput;\n /** The actor system to which the async actor belongs. */\n system: AnyActorSystem;\n /** The async actor. */\n self: AsyncActor<TOutput, TInput>;\n /** Aborted when the async actor is stopped or times out. */\n signal: AbortSignal;\n}\n\nexport interface LogicEnqueue<TEmitted extends EventObject> {\n /** Emits an event that can be observed with `actor.on(...)`. */\n emit: (emitted: TEmitted) => void;\n /**\n * Executes async work as a durable effect keyed by `key`.\n *\n * @experimental The durability semantics (step journaling, replay, and\n * resumption across persistence) are not finalized and may change.\n */\n step: <TStepOutput>(\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>\n ) => Promise<TStepOutput>;\n}\n\nexport type LogicFunction<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = (\n args: LogicArgs<TOutput, TInput>,\n enq: LogicEnqueue<TEmitted>\n) => PromiseLike<TOutput>;\n\ntype AsyncLogicFunctionOutput<\n TLogicFunction extends (...args: any[]) => PromiseLike<any>\n> = Awaited<ReturnType<TLogicFunction>>;\n\nexport interface LogicConfig<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n /**\n * Stable identifier for this async logic. This identifies the logic, not a\n * particular actor instance.\n */\n id?: string;\n validator?: ActorLogicValidator;\n /** Schemas for inferring async logic types. */\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n /** Maximum time this async logic may run before it is aborted and errors. */\n timeout?: number | string;\n /** The async work to execute when the actor starts. */\n run: LogicFunction<TOutput, TInput, TEmitted>;\n}\n\nexport class TimeoutError extends Error {\n constructor(timeout: number | string) {\n super(`Async logic timed out after ${timeout}.`);\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Represents an actor created by `createAsyncLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createAsyncLogic, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = createAsyncLogic<Output, Input>({\n * run: async ({ input, self }, enq) => {\n * self;\n * // ^? AsyncActor<Output, Input>\n * enq.emit({ type: 'request.start' });\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * }\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? AsyncActor<Output, Input>\n * ```\n *\n * @see {@link createAsyncLogic}\n */\n\n/**\n * An actor logic creator which returns async logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from async actor logic can:\n *\n * - Output the resolved value of the async process\n * - Error with the rejected value of the async process\n * - Abort when stopped or timed out\n *\n * Sending events to async actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const asyncLogic = createAsyncLogic({\n * id: 'fetch-user',\n * timeout: '30s',\n * run: async ({ signal }, enq) => {\n * enq.emit({ type: 'request.start' });\n * const result = await fetch('https://example.com/...', {\n * signal\n * }).then((data) => data.json());\n *\n * return result;\n * }\n * });\n *\n * const asyncActor = createActor(asyncLogic);\n * asyncActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * asyncActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param asyncLogic A config object with a `run` function which returns a\n * Promise, and accepts an object with the following properties:\n *\n * - `input` - Data that was provided to the async actor\n * - `self` - The async actor ref\n * - `system` - The actor system to which the async actor belongs\n * - `signal` - An abort signal for cancellation\n *\n * `run` also receives an `enq` object with the following properties:\n *\n * - `emit` - Emits an event that can be observed with `actor.on(...)`\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject,\n TLogicFunction extends LogicFunction<\n any,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n > = LogicFunction<any, StandardSchemaV1.InferOutput<TInputSchema>, TEmitted>\n>(\n asyncLogic: Omit<\n LogicConfig<\n never,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n >,\n 'run' | 'schemas'\n > & {\n schemas: { input: TInputSchema; output?: never };\n run: TLogicFunction;\n }\n): AsyncActorLogic<\n AsyncLogicFunctionOutput<TLogicFunction>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TOutputSchema extends StandardSchemaV1,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: never; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: Omit<LogicConfig<TOutput, TInput, TEmitted>, 'schemas'> & {\n schemas?: undefined;\n }\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<TOutput, TInput, TEmitted>\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string } {\n const config = asyncLogic;\n\n return createBaseLogic<\n undefined,\n TOutput,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n id: config.id,\n validator: config.validator,\n schemas: config.schemas,\n context: undefined,\n run: ({ event, input, self, system }, enq) => {\n switch (event.type) {\n case XSTATE_ASYNC_RESOLVE: {\n const resolvedValue = (event as any).data ?? (event as any).output;\n return {\n status: 'done',\n output: resolvedValue,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'done', output: resolvedValue }\n }\n };\n }\n case XSTATE_ASYNC_REJECT: {\n const error = (event as any).data ?? (event as any).error;\n return {\n status: 'error',\n error,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'error', error }\n }\n };\n }\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const controller = new AbortController();\n const timeout = config.timeout;\n const timeoutMs = parseDelayToMilliseconds(timeout);\n const timeoutId =\n timeoutMs === undefined\n ? undefined\n : system._clock.setTimeout(() => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controller.abort();\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: new TimeoutError(timeout!)\n });\n }, timeoutMs);\n\n const clearTimeout = () => {\n if (timeoutId !== undefined) {\n system._clock.clearTimeout(timeoutId);\n }\n };\n\n const runBody = () =>\n Promise.resolve(\n config.run(\n {\n input,\n system,\n self: self as any,\n signal: controller.signal\n },\n {\n emit: (event) => void runtime.emitEvent!(actorSelf, event),\n // Steps route through the runtime: a durable host that\n // implements `runStep` owns the step journal; otherwise the\n // built-in behavior memoizes into this actor's own snapshot,\n // self-sending through the same runtime as the other effects.\n step: (key, exec) =>\n runtime.runStep\n ? (Promise.resolve(\n runtime.runStep(actorSelf, key, exec)\n ) as Promise<any>)\n : runStep(actorSelf, key, exec, sendSelf)\n }\n )\n );\n // The whole body is one durable unit: a host that implements\n // `runLogic` journals it by the actor's address — or re-runs the\n // registered logic from (src, input) on a remote executor, ignoring\n // the closure. The default runs it here, unjournaled.\n const resolvedPromise = runtime.runLogic\n ? Promise.resolve(runtime.runLogic(actorSelf, runBody))\n : runBody();\n\n resolvedPromise.then(\n (response) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_RESOLVE,\n data: response\n });\n },\n (errorData) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: errorData\n });\n }\n );\n\n return () => {\n controller.abort();\n clearTimeout();\n };\n });\n\n return {\n effects: {\n async: { status: 'active' }\n }\n };\n }\n }) as unknown as AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorFromLogic } from '../types.ts';\nimport { createLogic } from './logic.ts';\nexport {\n createCallbackLogic,\n type CallbackActorLogic,\n type CallbackActorRef,\n type CallbackLogicConfig,\n type CallbackSnapshot,\n type CallbackLogicFunction\n} from './callback.ts';\nexport {\n createObservableLogic,\n createEventObservableLogic,\n type EventObservableLogicConfig,\n type EventObservableLogicFunction,\n type ObservableActorLogic,\n type ObservableActorRef,\n type ObservableLogicConfig,\n type ObservableLogicFunction,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n createLogic,\n type LogicActorLogic,\n type LogicActorRef,\n type LogicArgs,\n type LogicConfig,\n type LogicEffect,\n type LogicEffectState,\n type LogicEnqueue,\n type LogicFunction,\n type LogicPatch,\n type LogicSnapshot\n} from './logic.ts';\nexport {\n createAsyncLogic,\n type AsyncActorLogic,\n type AsyncActorRef,\n type AsyncSnapshot,\n type LogicArgs as AsyncLogicArgs,\n type LogicConfig as AsyncLogicConfig,\n type LogicEnqueue as AsyncLogicEnqueue,\n type LogicFunction as AsyncLogicFunction,\n TimeoutError\n} from './promise.ts';\nexport {\n createListenerLogic,\n listenerLogic,\n type ListenerActorLogic,\n type ListenerActorRef,\n type ListenerSnapshot,\n type ListenerInput\n} from './listener.ts';\nexport {\n createSubscriptionLogic,\n subscriptionLogic,\n type SubscriptionActorLogic,\n type SubscriptionActorRef,\n type SubscriptionSnapshot,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './subscription.ts';\n\nconst emptyLogic = /* #__PURE__ */ createLogic<undefined, undefined>({\n context: undefined,\n run: () => undefined\n});\n\nexport function createEmptyActor(): ActorFromLogic<typeof emptyLogic> {\n return createActor(emptyLogic);\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_INIT","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_LOGIC_EFFECT_RESOLVE","XSTATE_LOGIC_EFFECT_REJECT","XSTATE_LOGIC_EFFECT_START","createInitEvent","input","type","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","subscriptions","WeakMap","createAttachedLogic","attach","id","initialTransition","_","status","output","undefined","error","state","self","system","target","actor","getSnapshot","subscription","parentSubscription","torndown","teardown","unsubscribe","parent","_parent","subscribe","complete","set","transition","get","delete","getInitialSnapshot","actorScope","getPersistedSnapshot","snapshot","restoreSnapshot","relayMappedToParent","getEvent","_relay","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","on","emittedEvent","descriptor","partialEventTokens","split","eventTokens","tokenIndex","length","partialEventToken","eventToken","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","execEmitEffect","runtime","source","emitEvent","createCustomEffect","action","params","kind","exec","args","execTerminateEffect","termination","terminateActor","execSendToEffect","Error","assertSendToEvent","delay","scheduleTimer","sendEvent","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","effect","noop","emptyActor","parseDelayToMilliseconds","duration","normalizedDuration","trim","millisecondsMatch","match","parseInt","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","slice","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDurationToMilliseconds","props","enqueueFn","fn","Object","assign","cancel","emit","log","raise","spawn","sendTo","stop","listen","subscribeTo","createEnqueueObject","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","Map","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","getSnapshotActorRef","existing","create","created","setSnapshotActorRef","baseSystem","sourceVersion","previousRef","reusableRef","systemState","sourceSystem","capturedActors","root","_getRootActor","peekedChildren","_peekChildren","children","size","captureRegisteredActors","baseKeyedActors","peek","_peekKeyedActors","call","keyedActors","getKeyedActors","child","values","getSnapshotChildren","sessionId","registryKey","_snapshot","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","async","runStep","key","sendSelf","getStepEffect","Promise","resolve","reject","waitForStep","assertEventCanBeSent","runtimeTarget","logic","isInternalEventType","systemIdPrefix","nextSystemId","transitionEffectSignal","transitionEffectTargets","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","Array","from","toString","padStart","join","randomUUID","replaceAll","Date","now","Math","random","createSystemIdPrefix","encodeAddressSegment","includes","getActorIdCounterKey","prefix","address","bumpActorIdCounter","counterKey","counters","_nextActorIds","resolveActorId","requestedId","options","generated","separator","lastIndexOf","index","isSafeInteger","parseGeneratedActorId","src","logicId","getActorIdPrefix","counter","emptyScheduledTimers","freeze","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_isRunning","_keyedActors","actors","reverseKeyedActors","_reverseKeyedActors","_identity","systemId","nextSessionId","scheduler","_clock","_logger","createActorRef","restoredSnapshot","clock","logger","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","push","targetRef","targetId","schedule","existingId","_timerMap","timer","timers","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","_lastSourceRef","_send","deliverEvent","_register","_unregister","changed","getAll","fromEntries","entries","_set","inspect","observerOrFn","observer","Set","add","_hasInspectionObservers","_sendInspectionEvent","resolvedInspectionEvent","rootId","forEach","spawnActor","startActor","override","stopActor","_stop","stopActorLocally","_terminate","terminateActorLocally","_emit","deadLetter","reason","actorRef","sourceRef","runLogic","cancelTimer","cancelAllTimers","scheduledTimers","resetScheduledTimers","scheduledId","max","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","actionExecutor","Actor","_address","trigger","_trigger","Proxy","payload","send","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_syncSnapshot","ref","_actorScope","_collectedMicrosteps","_collectedActions","_initialEffects","_deferred","_restored","resolvedOptions","syncSnapshot","_systemRef","current","rootActor","createRuntimeSystem","_sessionId","persistedState","_setSnapshot","_inert","parentRef","_getLogger","defer","_defer","defineProperty","stopChild","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","update","_next","deferred","i","deferredFn","_inspectTransition","microsteps","actions","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","Stopped","handler","listeners","select","selector","equalityFn","is","selected","actorId","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","startedAt","min","nextState","caughtError","invokeId","reportError","toJSON","xstate$type","assertValid","validator","request","check","effectStates","executeLogicEffect","getEffectState","has","cleanup","createLogic","config","calculateTransition","cleanupLogicEffects","trackedEffects","enq","emitted","createEmitEffect","sendBack","sentEvent","raisedEvent","keyOrExec","maybeExec","enqueueEffect","patch","run","context","keys","eventOrigin","result","resolveContext","instanceStates","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","XSTATE_ASYNC_RESOLVE","XSTATE_ASYNC_REJECT","TimeoutError","super","name","emptyLogic","asyncLogic","createBaseLogic","schemas","resolvedValue","data","actorSelf","controller","AbortController","timeoutMs","timeoutId","abort","runBody","signal","step","then","response","errorData","callbackOrConfig","callback","callbackState","receivers","receiver","dispose","receive","listener","lazyObservableOrConfig","lazyObservable","_subscription","observableCreatorOrConfig","observableCreator"],"mappings":"mPAKO,MAAMA,EAKXC,WAAAA,CAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,KAAAA,GACLJ,KAAKC,SAAU,EACfD,KAAKK,OACP,CAEOC,KAAAA,GAGDN,KAAKE,WACPF,KAAKE,SAASK,KAAO,K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O,CACLpb,OAAQ,QACRG,MAAQ7B,EAAc0d,KACtB/c,WAAOiB,EACP2E,QAAS,CACPrF,WAAY,CAAEQ,OAAQ,QAASG,MAAQ7B,EAAc0d,QAG3D,KAAKX,GACH,MAAO,CACLrb,OAAQ,OACRf,WAAOiB,EACP2E,QAAS,CACPrF,WAAY,CAAEQ,OAAQ,UAK1B1B,EAAMY,OAASR,GAInBwb,EAAIhV,OAAO,CAAC5B,EAAUhD,KACpB,MAAM2b,EAAY5b,EACZsK,EAAYrM,IACXgF,EAAQiB,UAAW0X,EAAWA,EAAW3d,IAC1CoC,EAAe+c,EAAkB,CACrCxe,QACAqB,SACAD,KAAMA,EACN8G,KAAQ7I,IACDgF,EAAQE,UAAWyY,EAAW3d,MAGpC2C,UAAU,CACX7C,KAAOI,IACLmM,EAAS,CACPzL,KAAMic,GACNa,KAAMxd,KAGV2B,MAAQf,IACNuL,EAAS,CACPzL,KAAMkc,GACNY,KAAM5c,KAGV8B,SAAUA,KACRyJ,EAAS,CACPzL,KAAMmc,QAKZ,MAAO,IAAM3a,EAAaI,kBAIlC"}
|
|
1
|
+
{"version":3,"file":"xstate-actors.umd.min.js","sources":["../src/Mailbox.ts","../src/constants.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/utils.ts","../src/actors/subscription.ts","../src/transitionActions.ts","../src/actions.ts","../src/delay.ts","../src/snapshotActorRef.ts","../src/runtimeHelpers.ts","../src/system.ts","../src/createActor.ts","../src/validation.ts","../src/actors/logic.ts","../src/actors/callback.ts","../src/actors/observable.ts","../src/actors/promise.ts","../src/actors/index.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = '@xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\nexport const XSTATE_STOP = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\nexport function createAfterEventId(delayRef: number | string, id: string) {\n return `xstate.after.${delayRef}.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout', stateId: id };\n}\n\nexport function createTimeoutEventId(id: string) {\n return `xstate.timeout.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createInvokeTimeoutEventId(invokeId: string) {\n return `xstate.timeout.actor.${invokeId}`;\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import { XSTATE_STOP } from '../constants.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n return {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n 'xstate.listener'\n );\n}\n\n// Singleton logic instance\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import 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 { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, 'xstate.subscription');\n}\n\n// Singleton logic instance\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\n","import isDevelopment from '#is-development';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport { createErrorPlatformEvent } from './eventUtils.ts';\nimport {\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime,\n type DeadLetterDetail,\n type EventRejectionReason\n} from './system.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport { getEventOutput } from './utils.ts';\nimport type {\n Action,\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableActionObject,\n CustomExecutableActionObject,\n EmitExecutableActionObject,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n RaiseExecutableActionObject,\n DeadLetterExecutableActionObject,\n SendToExecutableActionObject,\n Snapshot,\n SpecialExecutableAction,\n SpawnExecutableActionObject,\n StartExecutableActionObject,\n StopExecutableActionObject,\n TerminateExecutableActionObject\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableActionObject\n): void | PromiseLike<void> | undefined {\n return this.action?.(...this.args);\n}\n\nfunction execEmitEffect(\n this: EmitExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.emitEvent!(this.source, this.event);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableActionObject {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\nfunction execDeadLetterEffect(\n this: DeadLetterExecutableActionObject,\n runtime: EffectRuntime = this.target.system\n): void | PromiseLike<void> {\n return runtime.deadLetter!(\n this.source,\n this.target,\n this.event,\n this.reason,\n this.detail\n );\n}\n\n/** @internal Creates a dead-letter effect for a boundary-rejected event. */\nexport function createDeadLetterEffect(\n actorScope: AnyActorScope,\n source: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n): DeadLetterExecutableActionObject {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source,\n target: actorScope.self,\n event,\n reason,\n detail,\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableActionObject {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay ?? 0);\n}\n\nfunction execSendToEffect(\n this: SendToExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, this.id);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableActionObject,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableAction(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n if (!snapshot.timers?.[effect.id]) {\n return snapshot;\n }\n const timers = { ...snapshot.timers };\n delete timers[effect.id];\n return { ...snapshot, timers };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n let nextTimerId = snapshot._nextTimerId ?? 0;\n const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;\n effect.id = id;\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n\n return {\n ...snapshot,\n timers: {\n ...snapshot.timers,\n [id]: {\n id,\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n }\n },\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : `Cannot stop non-child actor ${update.actor.id}`\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(`Actor source '${source}' is not provided`);\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved namespace.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (isDevelopment && prefix.startsWith('xstate.')) {\n throw new Error(\n `Child actor ids with the \"xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : `Child actor id '${id}' is already in use`\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n if (typeof raisedEvent === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${raisedEvent}\" }) instead`\n : `Only event objects may be used with raise`\n );\n }\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? src ?? (logic as any).id\n } as AnyActor;\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n if (!actor) {\n internalEvents.push(\n createErrorPlatformEvent('communication', {\n message: 'Unable to send event to an undefined actor',\n event\n })\n );\n return;\n }\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n return createEnqueueObject(props, (action, ...args) => {\n pushBuiltInAction(actions, action, ...args);\n });\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableAction> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, id] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n id\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\nfunction createStartEffect(actor: AnyActor): StartExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\nexport function createSpawnEffect(\n actor: AnyActor\n): SpawnExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableActionObject {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error('Cannot terminate an active or stopped actor');\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableActionObject>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableActionObject>\n): StartExecutableActionObject[] {\n const attachedStarts: StartExecutableActionObject[] = [];\n const childStarts: StartExecutableActionObject[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\nexport function isBuiltInExecutableAction(\n action: ExecutableActionObject\n): action is SpecialExecutableAction {\n return action.kind === 'builtin';\n}\n\n/** Executes transition effects sequentially, awaiting each runtime operation. */\nexport async function executeEffects(\n effects: readonly ExecutableActionObject[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of actions) {\n const actionArgs = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n },\n actorScope\n )\n : {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n };\n\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...actionRecord.args)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (resolvedAction && '_special' in resolvedAction) {\n executableActions.push({\n kind: 'action',\n exec: execCustomEffect,\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : ((action as any).type ?? '(anonymous)')\n : action.name || '(anonymous)',\n params: actionParams,\n args: [],\n action: undefined\n });\n\n const specialAction = resolvedAction as unknown as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n\n const res = specialAction(actionArgs as any, emptyEnqueueObject);\n\n if (res && ('context' in res || 'children' in res)) {\n // Special-action patches never change `nodes`, so a shallow clone is\n // equivalent to `cloneMachineSnapshot` — and keeps this module (and\n // non-machine logic like `createFSM`) independent of State.ts.\n intermediateSnapshot = {\n ...intermediateSnapshot,\n ...(res.context !== undefined\n ? {\n context: mergeContextPatch(\n intermediateSnapshot.context,\n res.context\n )\n }\n : {}),\n ...('children' in res ? { children: res.children } : {})\n };\n }\n continue;\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, action.args)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action ? action.args : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableAction = executableAction as ExecutableActionObject;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableAction,\n actorScope\n );\n executableActions.push(typedExecutableAction);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n\nconst emptyEnqueueObject = createEnqueueObject({}, noop);\n","import isDevelopment from '#is-development';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : `Only event objects may be used with sendTo`\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n _event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, sendId: string) => {\n return actorScope.system.cancelTimer(actorScope.self, sendId);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\n}\n","import { hasAmbientInspector } from './inspectionAmbient.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${String(registryKey)}' already exists.`\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport type { ActorTermination, AnyActor, AnyEventObject } from './types.ts';\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n return (actor.getSnapshot() as { effects?: StepEffects }).effects?.[key];\n}\n\nfunction waitForStep<TStepOutput>(\n actor: AnyActor,\n key: string\n): Promise<TStepOutput> {\n return new Promise((resolve, reject) => {\n const subscription = actor.subscribe((snapshot) => {\n const effect = (snapshot as { effects?: StepEffects }).effects?.[key];\n if (effect?.status === 'done') {\n subscription.unsubscribe();\n resolve(effect.output as TStepOutput);\n } else if (effect?.status === 'error') {\n subscription.unsubscribe();\n reject(effect.error as Error);\n }\n });\n });\n}\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n if (effect?.status === 'active') {\n return waitForStep(actor, key);\n }\n\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n try {\n const output = await exec();\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n return output;\n } catch (error) {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n throw error;\n }\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n const runtimeTarget = target as AnyActor & {\n _lastSourceRef?: AnyActor;\n _send(event: AnyEventObject): void;\n };\n\n runtimeTarget._lastSourceRef = source;\n runtimeTarget._send(event);\n}\n\n/**\n * Returns the boundary error preventing this delivery, if any: an internal\n * event type cannot cross an actor boundary from an external sender.\n */\nfunction getEventBoundaryError(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): Error | undefined {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n return new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n return undefined;\n}\n\n/**\n * Rejects an event that must not cross the delivery boundary — an internal\n * event type sent from outside its owning actor — by reporting it as a dead\n * letter. Returns `true` when the event was rejected and must not be\n * delivered. Host runtimes must call this before taking ownership of\n * delivery.\n */\nexport function rejectUndeliverableEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): boolean {\n const error = getEventBoundaryError(source, target, event);\n if (error) {\n void target.system.deadLetter(source, target, event, 'internalEvent', {\n error\n });\n return true;\n }\n return false;\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","import isDevelopment from '#is-development';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription,\n AnyActorLogic,\n ActorOptions\n} from './types.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { toObserver } from './utils.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n rejectUndeliverableEvent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n id: string;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, id: string, delay: number): void;\n cancel(source: AnyActor, id: string): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet systemIdPrefix: string | undefined;\nlet nextSystemId = 0;\n\n/** @internal */\nexport const transitionEffectSignal = new Error('Transition effect');\n/** @internal */\nexport const transitionEffectTargets: AnyActor[] = [];\n\nfunction createSystemIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createSystemId(): string {\n systemIdPrefix ??= createSystemIdPrefix();\n return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n systemId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Anonymous machines get the placeholder id '(machine)'; only named logic\n // earns a named id prefix.\n return typeof logicId === 'string' &&\n logicId.length &&\n logicId !== '(machine)'\n ? logicId\n : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.systemId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\n/**\n * Why an event was not delivered: `'invalidEvent'` (payload failed its\n * declared schema), `'internalEvent'` (an internal event type sent from\n * outside its owning actor) or `'stopped'` (the target actor already\n * stopped). Hosts may report additional reasons.\n */\nexport type EventRejectionReason =\n | 'invalidEvent'\n | 'internalEvent'\n | 'stopped'\n | (string & {});\n\n/** Extra detail attached to a dead letter. */\nexport interface DeadLetterDetail {\n /** Standard Schema issues for `invalidEvent` rejections. */\n issues?: readonly StandardSchemaV1.Issue[];\n /** The underlying error describing the rejection. */\n error?: Error;\n}\n\n/**\n * Describes an event that was rejected at the delivery boundary instead of\n * being delivered to its target actor (a dead letter).\n */\nexport interface EventRejection extends DeadLetterDetail {\n /** The event that was rejected. */\n event: AnyEventObject;\n /** The actor the event was addressed to. */\n targetRef: AnyActor | undefined;\n /** The `id` of the target actor. */\n targetId: string | undefined;\n /** The actor that sent the event, or `undefined` for an external send. */\n sourceRef: AnyActor | undefined;\n /** Whether the event came from outside the system or from another actor. */\n eventOrigin: 'external' | 'actor';\n reason: EventRejectionReason;\n}\n\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Publishes an emitted event. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /** Schedules a logical timer. */\n scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, id: string): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry: the default logs in development, emits an\n * inspection event and calls the root actor's `onRejectedEvent` hook.\n * `detail` carries validation issues and the underlying error for events\n * rejected at the delivery boundary.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(actor: AnyActor, id: string): ScheduledTimerId {\n return `${actor.sessionId}.${id}` as ScheduledTimerId;\n}\n\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n systemId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n _onRejectedEvent?: (rejection: EventRejection) => void;\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n systemId: createSystemId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n onRejectedEvent?: (rejection: EventRejection) => void;\n }\n ) {\n this._onRejectedEvent = options.onRejectedEvent;\n const restoredSnapshot =\n typeof options.snapshot === 'object' && options.snapshot !== null\n ? (options.snapshot as {\n scheduler?: Record<ScheduledTimerId, ScheduledTimer>;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, id: string, delay: number): void {\n const existingId = createScheduledTimerId(source, id);\n if (this._timerMap?.[existingId] !== undefined) {\n this.cancel(source, id);\n }\n\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n id,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n const scheduledTimerId = createScheduledTimerId(source, id);\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, id });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, id: string): void {\n const scheduledTimerId = createScheduledTimerId(source, id);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.id);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${registryKey as string}' already exists.`\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void> {\n this._sendInspectionEvent({\n type: '@xstate.deadletter',\n actorRef: target,\n sourceRef: source,\n event,\n reason,\n issues: detail?.issues,\n error: detail?.error\n });\n this._onRejectedEvent?.({\n event,\n targetRef: target,\n targetId: target.id,\n sourceRef: source,\n eventOrigin: source ? 'actor' : 'external',\n reason,\n issues: detail?.issues,\n error: detail?.error\n });\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason, detail);\n }\n if (isDevelopment) {\n console.warn(\n `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n return override(source, id, delay);\n }\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, id);\n }\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, id } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n id,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n onRejectedEvent?: (rejection: EventRejection) => void;\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotFor,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableActionObject,\n Readable,\n ActorLogicTransitionResult\n} from './types.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\n/**\n * Marks a serialized object as an actor reference (`xstate$type` in JSON\n * output and persisted context).\n */\nexport const ACTOR_REF_TYPE = 'actorRef';\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableActionObject[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (event: EventFromLogic<TLogic>) => void;\n private mailbox?: Mailbox<EventFromLogic<TLogic>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableActionObject[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n snapshot: resolvedOptions.snapshot ?? resolvedOptions.state,\n createActorRef,\n onRejectedEvent: resolvedOptions.onRejectedEvent\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const persistedState = options?.snapshot ?? options?.state;\n this._restored = persistedState !== undefined;\n try {\n if (persistedState) {\n this._setSnapshot(\n this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n );\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._setSnapshot({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>);\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n this.system.emitEvent(this, event);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableActionObject) => void {\n const actionExecutor = (action: ExecutableActionObject) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : `Cannot stop non-child actor ${child.id}`\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableActionObject): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n void action.exec();\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n type RestoredTimer = { id: string; delay: number; startedAt?: number };\n const timers =\n (\n this._snapshot as unknown as {\n timers?: Record<string, RestoredTimer>;\n }\n ).timers ?? {};\n // startedAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of Object.values(timers)) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.startedAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.startedAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, timer.id, delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n private _error(err: unknown): void {\n this._stopProcedure();\n if (!this.observers?.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n } else {\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n safeCall(errorListener, err);\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(\n this._lastSourceRef,\n this as AnyActor,\n event,\n 'stopped'\n );\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: its `id`, `address`,\n * and registered source key (when the actor was created from one).\n */\n public toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: this.id,\n address: this.address,\n src: typeof this.src === 'string' ? this.src : undefined\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n public getPersistedSnapshot(\n options?: unknown\n ): Snapshot<unknown> & PersistedSnapshotFor<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START,\n XSTATE_STOP\n} from '../constants.ts';\nimport { createInitEvent } from '../eventUtils.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport {\n ActorSystemRuntime,\n AnyActorSystem,\n type DeadLetterDetail\n} from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n finalizeTransitionResult,\n createCustomEffect,\n createDeadLetterEffect,\n createEmitEffect,\n createSendToEffect\n} from '../transitionActions.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n ActorScope,\n AnyActorRef,\n EventObject,\n ExecutableActionObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type LogicSnapshot<TContext, TOutput, TInput> = Snapshot<TOutput> & {\n context: TContext;\n input: TInput | undefined;\n effects?: Record<string, LogicEffectState>;\n};\n\nexport type LogicEffectState =\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown };\n\nexport interface LogicArgs<TContext, TEvent extends EventObject, TInput> {\n context: TContext;\n event: TEvent;\n input: TInput;\n system: AnyActorSystem;\n self: LogicActorRef<TContext, unknown, TEvent, TInput>;\n}\n\nexport type LogicEffect<\n _TEvent extends EventObject,\n _TEmitted extends EventObject\n> = ExecutableActionObject;\n\nexport interface LogicEnqueue<\n TEvent extends EventObject,\n TEmitted extends EventObject\n> {\n emit: (emitted: TEmitted) => void;\n sendBack: (event: EventObject) => void;\n raise: (event: TEvent) => void;\n effect: {\n (\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ): void;\n };\n}\n\nexport type LogicPatch<TContext, TOutput, TInput> = Partial<{\n context: TContext;\n input: TInput | undefined;\n status: LogicSnapshot<TContext, TOutput, TInput>['status'];\n output: TOutput;\n error: unknown;\n effects: Record<string, LogicEffectState>;\n}>;\n\nexport type LogicFunction<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> = (\n args: LogicArgs<TContext, TEvent, TInput>,\n enq: LogicEnqueue<TEvent, TEmitted>\n) => void | LogicPatch<TContext, TOutput, TInput>;\n\nexport interface LogicConfig<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n id?: string;\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n context: TContext | ((args: { input: TInput }) => TContext);\n run: LogicFunction<TContext, TOutput, TEvent, TInput, TEmitted>;\n}\n\ninterface LogicTransition<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput,\n TEmitted extends EventObject\n> {\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): [\n LogicSnapshot<TContext, TOutput, TInput>,\n LogicEffect<TEvent, TEmitted>[]\n ];\n (\n snapshot: LogicSnapshot<TContext, TOutput, TInput>,\n event: TEvent,\n actorScope: ActorScope<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): LogicSnapshot<TContext, TOutput, TInput>;\n}\n\nexport type LogicActorLogic<\n TContext,\n TOutput,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = Omit<\n ActorLogic<\n LogicSnapshot<TContext, TOutput, TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n >,\n 'transition'\n> & {\n id?: string;\n transition: LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n};\n\nexport type LogicActorRef<\n TContext,\n TOutput,\n TEvent extends EventObject,\n TInput\n> = ActorRefFromLogic<LogicActorLogic<TContext, TOutput, TEvent, TInput>>;\n\nconst effectStates = new WeakMap<\n AnyActorRef,\n Map<PropertyKey, { cleanup?: () => void }>\n>();\n\nfunction getEffectState(self: AnyActorRef) {\n let state = effectStates.get(self);\n if (!state) {\n state = new Map();\n effectStates.set(self, state);\n }\n return state;\n}\n\nfunction executeLogicEffect(\n self: AnyActorRef,\n key: string | undefined,\n effect: () => void | (() => void)\n): void {\n const state = getEffectState(self);\n if (key !== undefined && state.has(key)) {\n return;\n }\n const cleanup = effect();\n state.set(key ?? Symbol(), {\n cleanup: typeof cleanup === 'function' ? cleanup : undefined\n });\n}\n\nfunction cleanupLogicEffects(self: AnyActorRef): void {\n const state = effectStates.get(self);\n if (!state) {\n return;\n }\n for (const { cleanup } of state.values()) {\n cleanup?.();\n }\n effectStates.delete(self);\n}\n\nfunction resolveContext<TContext, TInput>(\n context: TContext | ((args: { input: TInput }) => TContext),\n input: TInput\n) {\n return typeof context === 'function'\n ? (context as (args: { input: TInput }) => TContext)({ input })\n : context;\n}\n\nexport function createLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput,\n const TInputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & {\n schemas: { input: TInputSchema; output?: undefined };\n }\n): LogicActorLogic<\n TContext,\n TOutput,\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n const TOutputSchema extends StandardSchemaV1,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: undefined; output: TOutputSchema };\n }\n): LogicActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TEvent,\n TInput,\n TEmitted\n>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted>;\nexport function createLogic<\n TContext,\n TOutput = unknown,\n TEvent extends EventObject = EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: LogicConfig<TContext, TOutput, TEvent, TInput, TEmitted>\n): LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> {\n const calculateTransition = ((snapshot, event, actorScope) => {\n if (snapshot.status !== 'active') {\n return [snapshot, []];\n }\n\n if (event.type === XSTATE_STOP) {\n return [\n {\n ...snapshot,\n status: 'stopped',\n input: undefined\n },\n [\n createCustomEffect('xstate.logic.cleanup', () =>\n cleanupLogicEffects(actorScope.self)\n )\n ]\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_START) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: { status: 'active' }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'done',\n output: (event as any).output\n }\n }\n },\n []\n ];\n }\n\n if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {\n return [\n {\n ...snapshot,\n effects: {\n ...snapshot.effects,\n [(event as any).key]: {\n status: 'error',\n error: (event as any).error\n }\n }\n },\n []\n ];\n }\n\n const effects: LogicEffect<TEvent, TEmitted>[] = [];\n const trackedEffects: Record<string, LogicEffectState> = {};\n const enqueueEffect = (\n key: string,\n exec: (runtime?: Partial<ActorSystemRuntime>) => void | (() => void)\n ) => {\n if (snapshot.effects?.[key]) {\n return;\n }\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, key, () => exec(runtime)),\n { key }\n )\n );\n trackedEffects[key] = { status: 'active' };\n };\n const enq: LogicEnqueue<TEvent, TEmitted> = {\n emit: (emitted) => {\n effects.push(createEmitEffect(actorScope, emitted));\n },\n sendBack: (sentEvent) => {\n const parent = actorScope.self._parent;\n if (parent) {\n effects.push(createSendToEffect(actorScope, parent, sentEvent));\n }\n },\n raise: (raisedEvent) => {\n effects.push(\n createSendToEffect(actorScope, actorScope.self, raisedEvent)\n );\n },\n effect: ((keyOrExec, maybeExec) => {\n if (typeof keyOrExec === 'string') {\n enqueueEffect(keyOrExec, maybeExec);\n return;\n }\n const exec = keyOrExec as (\n runtime?: Partial<ActorSystemRuntime>\n ) => void | (() => void);\n effects.push(\n createCustomEffect(\n 'xstate.logic.effect',\n (runtime = actorScope.self.system) =>\n executeLogicEffect(actorScope.self, undefined, () =>\n exec(runtime)\n )\n )\n );\n }) as LogicEnqueue<TEvent, TEmitted>['effect']\n };\n\n const patch = config.run(\n {\n context: snapshot.context,\n event,\n input: snapshot.input!,\n system: actorScope.system,\n self: actorScope.self as any,\n emit: actorScope.emit\n } as LogicArgs<TContext, TEvent, TInput>,\n enq\n );\n\n const nextSnapshot = {\n ...snapshot,\n ...(patch || {})\n } as LogicSnapshot<TContext, TOutput, TInput>;\n\n if ('context' in snapshot || patch?.context !== undefined) {\n (nextSnapshot as any).context = patch?.context ?? snapshot.context;\n }\n if (patch?.effects || Object.keys(trackedEffects).length) {\n (nextSnapshot as any).effects = {\n ...snapshot.effects,\n ...patch?.effects,\n ...trackedEffects\n };\n }\n\n return finalizeTransitionResult(actorScope, snapshot, [\n nextSnapshot,\n effects\n ]);\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const transition = ((snapshot, event, actorScope) => {\n if (config.validator) {\n const sourceRef = (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = config.validator.check({\n kind: 'event',\n logic,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: rejected (never delivered), not an actor error.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n actorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n )\n ]\n ];\n }\n }\n const result = calculateTransition(snapshot, event, actorScope);\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'result',\n logic,\n snapshot: result[0],\n effects: result[1]\n });\n }\n return result;\n }) as LogicTransition<TContext, TOutput, TEvent, TInput, TEmitted>;\n\n const logic: LogicActorLogic<TContext, TOutput, TEvent, TInput, TEmitted> = {\n id: config.id,\n config,\n validator: config.validator,\n transition,\n start: (snapshot, actorScope, options) => {\n if (!options?.restored) {\n return;\n }\n const [nextSnapshot, effects] = transition(\n snapshot,\n createInitEvent(snapshot.input) as unknown as TEvent,\n actorScope\n );\n Object.assign(snapshot, nextSnapshot);\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n },\n initialTransition: (input, actorScope) => {\n if (config.validator) {\n assertValid(config.validator, {\n kind: 'input',\n logic,\n input\n });\n }\n const context = resolveContext(config.context, input);\n const snapshot = {\n status: 'active' as const,\n output: undefined,\n error: undefined,\n input\n };\n\n if (context !== undefined) {\n (snapshot as any).context = context;\n }\n\n return transition(\n { ...snapshot } as LogicSnapshot<TContext, TOutput, TInput>,\n createInitEvent(input) as unknown as TEvent,\n actorScope\n );\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\ninterface CallbackInstanceState<TEvent extends EventObject> {\n receivers: Set<(e: TEvent) => void> | undefined;\n dispose: (() => void) | void;\n}\n\nconst instanceStates = /* #__PURE__ */ new WeakMap<\n AnyActorRef,\n CallbackInstanceState<any>\n>();\n\nexport type CallbackSnapshot<TInput> = Snapshot<undefined> & {\n input: TInput;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n CallbackSnapshot<TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createCallbackLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createCallbackLogic, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = createCallbackLogic<Event, Input>(\n * ({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef<Event, Input>\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * }\n * );\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link createCallbackLogic}\n */\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorRefFromLogic<CallbackActorLogic<TEvent, TInput>>;\n\ntype Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type CallbackLogicFunction<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n sendBack,\n receive,\n emit\n}: {\n /**\n * Data that was provided to the callback actor\n *\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /** The actor system to which the callback actor belongs */\n system: AnyActorSystem;\n /** The parent actor of the callback actor */\n self: CallbackActorRef<TEvent>;\n /** A function that can send events back to the parent actor */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument; the\n * listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n emit: (emitted: TEmitted) => void;\n}) => (() => void) | void;\n\nexport interface CallbackLogicConfig<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: CallbackLogicFunction<TEvent, TSentEvent, TInput, TEmitted>;\n}\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = createCallbackLogic(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createCallbackLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<\n TEvent,\n AnyEventObject,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): CallbackActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callback: CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted>;\nexport function createCallbackLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n callbackOrConfig:\n | CallbackLogicFunction<TEvent, AnyEventObject, TInput, TEmitted>\n | CallbackLogicConfig<TEvent, AnyEventObject, TInput, TEmitted>\n): CallbackActorLogic<TEvent, TInput, TEmitted> {\n const callback =\n typeof callbackOrConfig === 'function'\n ? callbackOrConfig\n : callbackOrConfig.run;\n const schemas =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.schemas;\n const validator =\n typeof callbackOrConfig === 'function'\n ? undefined\n : callbackOrConfig.validator;\n\n return createBaseLogic<undefined, undefined, TEvent, TInput, TEmitted>({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n const emit = (args as any).emit as (emitted: TEmitted) => void;\n const callbackState = instanceStates.get(self as any);\n callbackState?.receivers?.forEach((receiver) => receiver(event));\n\n enq.effect('callback', () => {\n const callbackState: CallbackInstanceState<TEvent> = {\n receivers: undefined,\n dispose: undefined\n };\n\n instanceStates.set(self as any, callbackState);\n\n callbackState.dispose = callback({\n input,\n system,\n self: self as any,\n sendBack: (event) => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n const parent = (self as any)._parent;\n if (parent) {\n system._relay(self as any, parent, event);\n }\n },\n receive: (listener) => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit: emit as (emitted: TEmitted) => void\n });\n\n return () => {\n instanceStates.delete(self as any);\n callbackState.receivers?.clear();\n callbackState.dispose?.();\n };\n });\n }\n }) as unknown as CallbackActorLogic<TEvent, TInput, TEmitted>;\n}\n","import { XSTATE_INIT, XSTATE_STOP } from '../constants';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport { assertValid } from '../validation.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot,\n Subscribable,\n Subscription\n} from '../types';\nimport { createLogic as createBaseLogic } from './logic.ts';\nimport { finalizeTransitionResult } from '../transitionActions.ts';\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\nexport type ObservableSnapshot<\n TContext,\n TInput extends NonReducibleUnknown\n> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\n/**\n * Represents an actor created by `createObservableLogic` or\n * `createEventObservableLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = createObservableLogic<Context, Input>(\n * ({ input, self }) => {\n * self;\n * // ^? ObservableActor<Event, Input>\n *\n * return interval(input.period ?? 1_000);\n * }\n * );\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActor<Event, Input>\n * ```\n *\n * @see {@link createObservableLogic}\n * @see {@link createEventObservableLogic}\n */\nexport type ObservableActorRef<TContext> = ActorRefFromLogic<\n ObservableActorLogic<TContext, any>\n>;\n\ntype ObservableActor<\n TContext,\n TInput extends NonReducibleUnknown = any,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<ObservableActorLogic<TContext, TInput, TEmitted>>;\n\nexport type ObservableLogicFunction<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TContext, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TContext>;\n\nexport interface ObservableLogicConfig<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: ObservableLogicFunction<TContext, TInput, TEmitted>;\n}\n\nexport type EventObservableLogicFunction<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ({\n input,\n system,\n self,\n emit\n}: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActor<TEvent, TInput, TEmitted>;\n emit: (emitted: TEmitted) => void;\n}) => Subscribable<TEvent>;\n\nexport interface EventObservableLogicConfig<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n validator?: ActorLogicValidator;\n schemas?: {\n input?: TInputSchema;\n };\n run: EventObservableLogicFunction<TEvent, TInput, TEmitted>;\n}\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { createObservableLogic, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = createObservableLogic((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nexport function createObservableLogic<\n TContext,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TContext,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: ObservableLogicConfig<TContext, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreator: ObservableLogicFunction<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted>;\nexport function createObservableLogic<\n TContext,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n observableCreatorOrConfig:\n | ObservableLogicFunction<TContext, TInput, TEmitted>\n | ObservableLogicConfig<TContext, TInput, TEmitted>\n): ObservableActorLogic<TContext, TInput, TEmitted> {\n const observableCreator =\n typeof observableCreatorOrConfig === 'function'\n ? observableCreatorOrConfig\n : observableCreatorOrConfig.run;\n const schemas =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.schemas;\n const validator =\n typeof observableCreatorOrConfig === 'function'\n ? undefined\n : observableCreatorOrConfig.validator;\n\n return createBaseLogic<\n TContext | undefined,\n undefined,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n validator,\n schemas,\n context: undefined,\n run: (args, enq) => {\n const { event, input, self, system } = args;\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT: {\n return {\n context: event.data as TContext\n };\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n status: 'error',\n error: (event as any).data,\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'error', error: (event as any).data }\n }\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n status: 'done',\n input: undefined as TInput | undefined,\n effects: {\n observable: { status: 'done' }\n }\n };\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const subscription = observableCreator({\n input,\n system,\n self: self as any,\n emit: ((event: TEmitted) =>\n void runtime.emitEvent!(actorSelf, event)) as (\n emitted: TEmitted\n ) => void\n }).subscribe({\n next: (value) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: (err) => {\n sendSelf({\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n sendSelf({\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n\n return () => subscription.unsubscribe();\n });\n }\n }) as unknown as ObservableActorLogic<TContext, TInput, TEmitted>;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * createEventObservableLogic,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = createEventObservableLogic(\n * () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n > & { schemas: { input: TInputSchema } }\n): ObservableActorLogic<\n TEvent,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n config: EventObservableLogicConfig<TEvent, TInput, TEmitted> & {\n schemas?: undefined;\n }\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservable: EventObservableLogicFunction<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted>;\nexport function createEventObservableLogic<\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n lazyObservableOrConfig:\n | EventObservableLogicFunction<TEvent, TInput, TEmitted>\n | EventObservableLogicConfig<TEvent, TInput, TEmitted>\n): ObservableActorLogic<TEvent, TInput, TEmitted> {\n const lazyObservable =\n typeof lazyObservableOrConfig === 'function'\n ? lazyObservableOrConfig\n : lazyObservableOrConfig.run;\n const validator =\n typeof lazyObservableOrConfig === 'function'\n ? undefined\n : lazyObservableOrConfig.validator;\n\n // TODO: event types\n const logic: ObservableActorLogic<TEvent, TInput, TEmitted> = {\n config: lazyObservableOrConfig,\n validator,\n transition: (state, event, actorScope) => {\n if (state.status !== 'active') {\n return [state, []];\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_OBSERVABLE_COMPLETE:\n return finalizeTransitionResult(\n actorScope,\n state as ObservableSnapshot<TEvent, TInput>,\n [\n {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>,\n []\n ]\n );\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return [\n {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n },\n []\n ];\n default:\n return [state, []];\n }\n },\n initialTransition: (input, _) => {\n if (validator) {\n assertValid(validator, { kind: 'input', logic, input });\n }\n const snapshot = {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n } as ObservableSnapshot<TEvent, TInput>;\n return [snapshot, []];\n },\n getInitialSnapshot: (actorScope, input) =>\n logic.initialTransition(input, actorScope)[0],\n start: (state, { self, system, emit }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self,\n emit: (event) => {\n void emit(event);\n }\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot: any) => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n","import { parseDelayToMilliseconds } from '../delay.ts';\nimport { runStep } from '../runtimeHelpers.ts';\nimport { XSTATE_INIT } from '../constants.ts';\nimport { StandardSchemaV1 } from '../schema.types.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport type { ActorLogicValidator } from '../validation.types.ts';\nimport {\n ActorLogic,\n ActorFromLogic,\n ActorRefFromLogic,\n AnyActor,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\nimport { createLogic as createBaseLogic } from './logic.ts';\n\nexport type AsyncSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n effects?: Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output?: unknown }\n | { status: 'error'; error: unknown }\n >;\n};\n\nconst XSTATE_ASYNC_RESOLVE = 'xstate.async.resolve';\nconst XSTATE_ASYNC_REJECT = 'xstate.async.reject';\n\nexport type AsyncActorLogic<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n AsyncSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\nexport type AsyncActorRef<TOutput> = ActorRefFromLogic<\n AsyncActorLogic<TOutput, unknown>\n>;\n\ntype AsyncActor<\n TOutput,\n TInput = unknown,\n TEmitted extends EventObject = EventObject\n> = ActorFromLogic<AsyncActorLogic<TOutput, TInput, TEmitted>>;\n\nexport interface LogicArgs<TOutput, TInput> {\n /** Data that was provided to the async actor. */\n input: TInput;\n /** The actor system to which the async actor belongs. */\n system: AnyActorSystem;\n /** The async actor. */\n self: AsyncActor<TOutput, TInput>;\n /** Aborted when the async actor is stopped or times out. */\n signal: AbortSignal;\n}\n\nexport interface LogicEnqueue<TEmitted extends EventObject> {\n /** Emits an event that can be observed with `actor.on(...)`. */\n emit: (emitted: TEmitted) => void;\n /**\n * Executes async work as a durable effect keyed by `key`.\n *\n * @experimental The durability semantics (step journaling, replay, and\n * resumption across persistence) are not finalized and may change.\n */\n step: <TStepOutput>(\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>\n ) => Promise<TStepOutput>;\n}\n\nexport type LogicFunction<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = (\n args: LogicArgs<TOutput, TInput>,\n enq: LogicEnqueue<TEmitted>\n) => PromiseLike<TOutput>;\n\ntype AsyncLogicFunctionOutput<\n TLogicFunction extends (...args: any[]) => PromiseLike<any>\n> = Awaited<ReturnType<TLogicFunction>>;\n\nexport interface LogicConfig<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TOutputSchema extends StandardSchemaV1 = StandardSchemaV1\n> {\n /**\n * Stable identifier for this async logic. This identifies the logic, not a\n * particular actor instance.\n */\n id?: string;\n validator?: ActorLogicValidator;\n /** Schemas for inferring async logic types. */\n schemas?: {\n input?: TInputSchema;\n output?: TOutputSchema;\n };\n /** Maximum time this async logic may run before it is aborted and errors. */\n timeout?: number | string;\n /** The async work to execute when the actor starts. */\n run: LogicFunction<TOutput, TInput, TEmitted>;\n}\n\nexport class TimeoutError extends Error {\n constructor(timeout: number | string) {\n super(`Async logic timed out after ${timeout}.`);\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Represents an actor created by `createAsyncLogic`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { createAsyncLogic, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = createAsyncLogic<Output, Input>({\n * run: async ({ input, self }, enq) => {\n * self;\n * // ^? AsyncActor<Output, Input>\n * enq.emit({ type: 'request.start' });\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * }\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? AsyncActor<Output, Input>\n * ```\n *\n * @see {@link createAsyncLogic}\n */\n\n/**\n * An actor logic creator which returns async logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from async actor logic can:\n *\n * - Output the resolved value of the async process\n * - Error with the rejected value of the async process\n * - Abort when stopped or timed out\n *\n * Sending events to async actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const asyncLogic = createAsyncLogic({\n * id: 'fetch-user',\n * timeout: '30s',\n * run: async ({ signal }, enq) => {\n * enq.emit({ type: 'request.start' });\n * const result = await fetch('https://example.com/...', {\n * signal\n * }).then((data) => data.json());\n *\n * return result;\n * }\n * });\n *\n * const asyncActor = createActor(asyncLogic);\n * asyncActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * asyncActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param asyncLogic A config object with a `run` function which returns a\n * Promise, and accepts an object with the following properties:\n *\n * - `input` - Data that was provided to the async actor\n * - `self` - The async actor ref\n * - `system` - The actor system to which the async actor belongs\n * - `signal` - An abort signal for cancellation\n *\n * `run` also receives an `enq` object with the following properties:\n *\n * - `emit` - Emits an event that can be observed with `actor.on(...)`\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema,\n TOutputSchema\n > & {\n schemas: { input: TInputSchema; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TInputSchema extends StandardSchemaV1,\n TEmitted extends EventObject = EventObject,\n TLogicFunction extends LogicFunction<\n any,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n > = LogicFunction<any, StandardSchemaV1.InferOutput<TInputSchema>, TEmitted>\n>(\n asyncLogic: Omit<\n LogicConfig<\n never,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted,\n TInputSchema\n >,\n 'run' | 'schemas'\n > & {\n schemas: { input: TInputSchema; output?: never };\n run: TLogicFunction;\n }\n): AsyncActorLogic<\n AsyncLogicFunctionOutput<TLogicFunction>,\n StandardSchemaV1.InferOutput<TInputSchema>,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n const TOutputSchema extends StandardSchemaV1,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted,\n StandardSchemaV1,\n TOutputSchema\n > & {\n schemas: { input?: never; output: TOutputSchema };\n }\n): AsyncActorLogic<\n StandardSchemaV1.InferOutput<TOutputSchema>,\n TInput,\n TEmitted\n> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: Omit<LogicConfig<TOutput, TInput, TEmitted>, 'schemas'> & {\n schemas?: undefined;\n }\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\nexport function createAsyncLogic<\n TOutput,\n TInput = NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n asyncLogic: LogicConfig<TOutput, TInput, TEmitted>\n): AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string } {\n const config = asyncLogic;\n\n return createBaseLogic<\n undefined,\n TOutput,\n { type: string; [k: string]: unknown },\n TInput,\n TEmitted\n >({\n id: config.id,\n validator: config.validator,\n schemas: config.schemas,\n context: undefined,\n run: ({ event, input, self, system }, enq) => {\n switch (event.type) {\n case XSTATE_ASYNC_RESOLVE: {\n const resolvedValue = (event as any).data ?? (event as any).output;\n return {\n status: 'done',\n output: resolvedValue,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'done', output: resolvedValue }\n }\n };\n }\n case XSTATE_ASYNC_REJECT: {\n const error = (event as any).data ?? (event as any).error;\n return {\n status: 'error',\n error,\n input: undefined as TInput | undefined,\n effects: {\n async: { status: 'error', error }\n }\n };\n }\n }\n\n if (event.type !== XSTATE_INIT) {\n return;\n }\n\n enq.effect((runtime = system) => {\n const actorSelf = self as unknown as AnyActor;\n const sendSelf = (event: AnyEventObject) =>\n void runtime.sendEvent!(actorSelf, actorSelf, event);\n const controller = new AbortController();\n const timeout = config.timeout;\n const timeoutMs = parseDelayToMilliseconds(timeout);\n const timeoutId =\n timeoutMs === undefined\n ? undefined\n : system._clock.setTimeout(() => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controller.abort();\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: new TimeoutError(timeout!)\n });\n }, timeoutMs);\n\n const clearTimeout = () => {\n if (timeoutId !== undefined) {\n system._clock.clearTimeout(timeoutId);\n }\n };\n\n const runBody = () =>\n Promise.resolve(\n config.run(\n {\n input,\n system,\n self: self as any,\n signal: controller.signal\n },\n {\n emit: (event) => void runtime.emitEvent!(actorSelf, event),\n // Steps route through the runtime: a durable host that\n // implements `runStep` owns the step journal; otherwise the\n // built-in behavior memoizes into this actor's own snapshot,\n // self-sending through the same runtime as the other effects.\n step: (key, exec) =>\n runtime.runStep\n ? (Promise.resolve(\n runtime.runStep(actorSelf, key, exec)\n ) as Promise<any>)\n : runStep(actorSelf, key, exec, sendSelf)\n }\n )\n );\n // The whole body is one durable unit: a host that implements\n // `runLogic` journals it by the actor's address — or re-runs the\n // registered logic from (src, input) on a remote executor, ignoring\n // the closure. The default runs it here, unjournaled.\n const resolvedPromise = runtime.runLogic\n ? Promise.resolve(runtime.runLogic(actorSelf, runBody))\n : runBody();\n\n resolvedPromise.then(\n (response) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_RESOLVE,\n data: response\n });\n },\n (errorData) => {\n clearTimeout();\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n sendSelf({\n type: XSTATE_ASYNC_REJECT,\n data: errorData\n });\n }\n );\n\n return () => {\n controller.abort();\n clearTimeout();\n };\n });\n\n return {\n effects: {\n async: { status: 'active' }\n }\n };\n }\n }) as unknown as AsyncActorLogic<TOutput, TInput, TEmitted> & { id?: string };\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorFromLogic } from '../types.ts';\nimport { createLogic } from './logic.ts';\nexport {\n createCallbackLogic,\n type CallbackActorLogic,\n type CallbackActorRef,\n type CallbackLogicConfig,\n type CallbackSnapshot,\n type CallbackLogicFunction\n} from './callback.ts';\nexport {\n createObservableLogic,\n createEventObservableLogic,\n type EventObservableLogicConfig,\n type EventObservableLogicFunction,\n type ObservableActorLogic,\n type ObservableActorRef,\n type ObservableLogicConfig,\n type ObservableLogicFunction,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n createLogic,\n type LogicActorLogic,\n type LogicActorRef,\n type LogicArgs,\n type LogicConfig,\n type LogicEffect,\n type LogicEffectState,\n type LogicEnqueue,\n type LogicFunction,\n type LogicPatch,\n type LogicSnapshot\n} from './logic.ts';\nexport {\n createAsyncLogic,\n type AsyncActorLogic,\n type AsyncActorRef,\n type AsyncSnapshot,\n type LogicArgs as AsyncLogicArgs,\n type LogicConfig as AsyncLogicConfig,\n type LogicEnqueue as AsyncLogicEnqueue,\n type LogicFunction as AsyncLogicFunction,\n TimeoutError\n} from './promise.ts';\nexport {\n createListenerLogic,\n listenerLogic,\n type ListenerActorLogic,\n type ListenerActorRef,\n type ListenerSnapshot,\n type ListenerInput\n} from './listener.ts';\nexport {\n createSubscriptionLogic,\n subscriptionLogic,\n type SubscriptionActorLogic,\n type SubscriptionActorRef,\n type SubscriptionSnapshot,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './subscription.ts';\n\nconst emptyLogic = /* #__PURE__ */ createLogic<undefined, undefined>({\n context: undefined,\n run: () => undefined\n});\n\nexport function createEmptyActor(): ActorFromLogic<typeof emptyLogic> {\n return createActor(emptyLogic);\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_INIT","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_LOGIC_EFFECT_RESOLVE","XSTATE_LOGIC_EFFECT_REJECT","XSTATE_LOGIC_EFFECT_START","createInitEvent","input","type","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","subscriptions","WeakMap","createAttachedLogic","attach","id","initialTransition","_","status","output","undefined","error","state","self","system","target","actor","getSnapshot","subscription","parentSubscription","torndown","teardown","unsubscribe","parent","_parent","subscribe","complete","set","transition","get","delete","getInitialSnapshot","actorScope","getPersistedSnapshot","snapshot","restoreSnapshot","relayMappedToParent","getEvent","_relay","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","on","emittedEvent","descriptor","partialEventTokens","split","eventTokens","tokenIndex","length","partialEventToken","eventToken","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","execEmitEffect","runtime","source","emitEvent","execDeadLetterEffect","deadLetter","reason","detail","createDeadLetterEffect","kind","exec","params","args","createCustomEffect","action","execTerminateEffect","termination","terminateActor","execSendToEffect","Error","assertSendToEvent","delay","scheduleTimer","sendEvent","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","effect","noop","emptyActor","parseDelayToMilliseconds","duration","normalizedDuration","trim","millisecondsMatch","match","parseInt","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","slice","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDurationToMilliseconds","props","enqueueFn","fn","Object","assign","cancel","emit","log","raise","spawn","sendTo","stop","listen","subscribeTo","createEnqueueObject","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","Map","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","getSnapshotActorRef","existing","create","created","setSnapshotActorRef","baseSystem","sourceVersion","previousRef","reusableRef","systemState","sourceSystem","capturedActors","root","_getRootActor","peekedChildren","_peekChildren","children","size","captureRegisteredActors","baseKeyedActors","peek","_peekKeyedActors","call","keyedActors","getKeyedActors","child","values","getSnapshotChildren","sessionId","registryKey","_snapshot","toObserver","nextHandler","errorHandler","completionHandler","isObserver","bind","async","runStep","key","sendSelf","getStepEffect","Promise","resolve","reject","waitForStep","rejectUndeliverableEvent","runtimeTarget","logic","isInternalEventType","getEventBoundaryError","systemIdPrefix","nextSystemId","transitionEffectSignal","transitionEffectTargets","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","Array","from","toString","padStart","join","randomUUID","replaceAll","Date","now","Math","random","createSystemIdPrefix","encodeAddressSegment","includes","getActorIdCounterKey","prefix","address","bumpActorIdCounter","counterKey","counters","_nextActorIds","resolveActorId","requestedId","options","generated","separator","lastIndexOf","index","isSafeInteger","parseGeneratedActorId","src","logicId","getActorIdPrefix","counter","emptyScheduledTimers","freeze","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_isRunning","_keyedActors","actors","reverseKeyedActors","_reverseKeyedActors","_identity","systemId","nextSessionId","scheduler","_clock","_logger","createActorRef","_onRejectedEvent","onRejectedEvent","restoredSnapshot","clock","logger","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","push","targetRef","targetId","schedule","existingId","_timerMap","timer","timers","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","_lastSourceRef","_send","deliverEvent","_register","_unregister","changed","getAll","fromEntries","entries","_set","inspect","observerOrFn","observer","Set","add","_hasInspectionObservers","_sendInspectionEvent","resolvedInspectionEvent","rootId","forEach","spawnActor","startActor","override","stopActor","_stop","stopActorLocally","_terminate","terminateActorLocally","_emit","actorRef","sourceRef","issues","eventOrigin","runLogic","cancelTimer","cancelAllTimers","scheduledTimers","resetScheduledTimers","scheduledId","max","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","actionExecutor","Actor","_address","trigger","_trigger","Proxy","payload","send","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_syncSnapshot","ref","_actorScope","_collectedMicrosteps","_collectedActions","_initialEffects","_deferred","_restored","resolvedOptions","syncSnapshot","_systemRef","current","rootActor","createRuntimeSystem","_sessionId","persistedState","_setSnapshot","_inert","parentRef","_getLogger","defer","_defer","defineProperty","stopChild","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","update","_next","deferred","i","deferredFn","_inspectTransition","microsteps","actions","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","Stopped","handler","listeners","select","selector","equalityFn","is","selected","actorId","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","startedAt","min","nextState","caughtError","invokeId","reportError","toJSON","xstate$type","assertValid","validator","request","check","effectStates","executeLogicEffect","getEffectState","has","cleanup","createLogic","config","calculateTransition","cleanupLogicEffects","trackedEffects","enq","emitted","createEmitEffect","sendBack","sentEvent","raisedEvent","keyOrExec","maybeExec","enqueueEffect","patch","run","context","keys","result","resolveContext","instanceStates","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","XSTATE_ASYNC_RESOLVE","XSTATE_ASYNC_REJECT","TimeoutError","super","name","emptyLogic","asyncLogic","createBaseLogic","schemas","resolvedValue","data","actorSelf","controller","AbortController","timeoutMs","timeoutId","abort","runBody","signal","step","then","response","errorData","callbackOrConfig","callback","callbackState","receivers","receiver","dispose","receive","listener","lazyObservableOrConfig","lazyObservable","_subscription","observableCreatorOrConfig","observableCreator"],"mappings":"mPA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