UNPKG

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