UNPKG

8.27 kBTypeScriptView Raw
1import { symbolObservable } from "./symbolObservable.js";
2import { AnyActorSystem, Clock } from "./system.js";
3import type { AnyActorLogic, AnyActorRef, ConditionalRequired, EmittedFrom, EventFromLogic, InputFrom, IsNotNever, Snapshot, SnapshotFrom } from "./types.js";
4import { ActorOptions, ActorRef, EventObject, InteropSubscribable, Observer, Subscription } from "./types.js";
5export declare const $$ACTOR_TYPE = 1;
6export type SnapshotListener<TLogic extends AnyActorLogic> = (snapshot: SnapshotFrom<TLogic>) => void;
7export type EventListener<TEvent extends EventObject = EventObject> = (event: TEvent) => void;
8export type Listener = () => void;
9export type ErrorListener = (error: any) => void;
10export declare enum ProcessingStatus {
11 NotStarted = 0,
12 Running = 1,
13 Stopped = 2
14}
15/**
16 * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.
17 */
18export declare class Actor<TLogic extends AnyActorLogic> implements ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<TLogic>> {
19 logic: TLogic;
20 /**
21 * The current internal state of the actor.
22 */
23 private _snapshot;
24 /**
25 * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
26 */
27 clock: Clock;
28 options: Readonly<ActorOptions<TLogic>>;
29 /**
30 * The unique identifier for this actor relative to its parent.
31 */
32 id: string;
33 private mailbox;
34 private observers;
35 private eventListeners;
36 private logger;
37 _parent?: AnyActorRef;
38 ref: ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<TLogic>>;
39 private _actorScope;
40 private _systemId;
41 /**
42 * The globally unique process ID for this invocation.
43 */
44 sessionId: string;
45 /**
46 * The system to which this actor belongs.
47 */
48 system: AnyActorSystem;
49 private _doneEvent?;
50 src: string | AnyActorLogic;
51 /**
52 * Creates a new actor instance for the given logic with the provided options, if any.
53 *
54 * @param logic The logic to create an actor from
55 * @param options Actor options
56 */
57 constructor(logic: TLogic, options?: ActorOptions<TLogic>);
58 private _initState;
59 private _deferred;
60 private update;
61 /**
62 * Subscribe an observer to an actor’s snapshot values.
63 *
64 * @remarks
65 * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
66 * - A plain function that receives the latest snapshot, or
67 * - An observer object whose `.next(snapshot)` method receives the latest snapshot
68 *
69 * @example
70 * ```ts
71 * // Observer as a plain function
72 * const subscription = actor.subscribe((snapshot) => {
73 * console.log(snapshot);
74 * });
75 * ```
76 *
77 * @example
78 * ```ts
79 * // Observer as an object
80 * const subscription = actor.subscribe({
81 * next(snapshot) {
82 * console.log(snapshot);
83 * },
84 * error(err) {
85 * // ...
86 * },
87 * complete() {
88 * // ...
89 * },
90 * });
91 * ```
92 *
93 * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:
94 *
95 * @example
96 * ```ts
97 * const subscription = actor.subscribe((snapshot) => {
98 * // ...
99 * });
100 *
101 * // Unsubscribe the observer
102 * subscription.unsubscribe();
103 * ```
104 *
105 * When the actor is stopped, all of its observers will automatically be unsubscribed.
106 *
107 * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot
108 */
109 subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;
110 subscribe(nextListener?: (snapshot: SnapshotFrom<TLogic>) => void, errorListener?: (error: any) => void, completeListener?: () => void): Subscription;
111 on<TType extends EmittedFrom<TLogic>['type']>(type: TType, handler: (emitted: EmittedFrom<TLogic> & {
112 type: TType;
113 }) => void): Subscription;
114 /**
115 * Starts the Actor from the initial state
116 */
117 start(): this;
118 private _process;
119 private _stop;
120 /**
121 * Stops the Actor and unsubscribe all listeners.
122 */
123 stop(): this;
124 private _complete;
125 private _reportError;
126 private _error;
127 private _stopProcedure;
128 /**
129 * Sends an event to the running Actor to trigger a transition.
130 *
131 * @param event The event to send
132 */
133 send(event: EventFromLogic<TLogic>): void;
134 private attachDevTools;
135 toJSON(): {
136 xstate$$type: number;
137 id: string;
138 };
139 /**
140 * Obtain the internal state of the actor, which can be persisted.
141 *
142 * @remarks
143 * The internal state can be persisted from any actor, not only machines.
144 *
145 * Note that the persisted state is not the same as the snapshot from {@link Actor.getSnapshot}. Persisted state represents the internal state of the actor, while snapshots represent the actor's last emitted value.
146 *
147 * Can be restored with {@link ActorOptions.state}
148 *
149 * @see https://stately.ai/docs/persistence
150 */
151 getPersistedSnapshot(): Snapshot<unknown>;
152 [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>>;
153 /**
154 * Read an actor’s snapshot synchronously.
155 *
156 * @remarks
157 * The snapshot represent an actor's last emitted value.
158 *
159 * When an actor receives an event, its internal state may change.
160 * An actor may emit a snapshot when a state transition occurs.
161 *
162 * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.
163 *
164 * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
165 * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
166 */
167 getSnapshot(): SnapshotFrom<TLogic>;
168}
169type RequiredOptions<TLogic extends AnyActorLogic> = undefined extends InputFrom<TLogic> ? never : 'input';
170/**
171 * Creates a new actor instance for the given actor logic with the provided options, if any.
172 *
173 * @remarks
174 * When you create an actor from actor logic via `createActor(logic)`, you implicitly create an actor system where the created actor is the root actor.
175 * Any actors spawned from this root actor and its descendants are part of that actor system.
176 *
177 * @example
178 * ```ts
179 * import { createActor } from 'xstate';
180 * import { someActorLogic } from './someActorLogic.ts';
181 *
182 * // Creating the actor, which implicitly creates an actor system with itself as the root actor
183 * const actor = createActor(someActorLogic);
184 *
185 * actor.subscribe((snapshot) => {
186 * console.log(snapshot);
187 * });
188 *
189 * // Actors must be started by calling `actor.start()`, which will also start the actor system.
190 * actor.start();
191 *
192 * // Actors can receive events
193 * actor.send({ type: 'someEvent' });
194 *
195 * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
196 * actor.stop();
197 * ```
198 *
199 * @param logic - The actor logic to create an actor from. For a state machine actor logic creator, see {@link createMachine}. Other actor logic creators include {@link fromCallback}, {@link fromEventObservable}, {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.
200 * @param options - Actor options
201 */
202export declare function createActor<TLogic extends AnyActorLogic>(logic: TLogic, ...[options]: ConditionalRequired<[
203 options?: ActorOptions<TLogic> & {
204 [K in RequiredOptions<TLogic>]: unknown;
205 }
206], IsNotNever<RequiredOptions<TLogic>>>): Actor<TLogic>;
207/**
208 * Creates a new Interpreter instance for the given machine with the provided options, if any.
209 *
210 * @deprecated Use `createActor` instead
211 */
212export declare const interpret: typeof createActor;
213/**
214 * @deprecated Use `Actor` instead.
215 */
216export type Interpreter = typeof Actor;
217export {};