xstate 5.0.0-beta.9 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +10 -8
  2. package/actions/dist/xstate-actions.cjs.js +19 -5
  3. package/actions/dist/xstate-actions.cjs.mjs +3 -15
  4. package/actions/dist/xstate-actions.development.cjs.js +21 -0
  5. package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
  6. package/actions/dist/xstate-actions.development.esm.js +3 -0
  7. package/actions/dist/xstate-actions.esm.js +3 -2
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +621 -4
  11. package/actors/dist/xstate-actors.cjs.mjs +1 -8
  12. package/actors/dist/xstate-actors.development.cjs.js +624 -0
  13. package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
  14. package/actors/dist/xstate-actors.development.esm.js +615 -0
  15. package/actors/dist/xstate-actors.esm.js +615 -2
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dev/dist/xstate-dev.cjs.js +45 -4
  19. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  20. package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
  21. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  22. package/dev/dist/xstate-dev.esm.js +42 -1
  23. package/dev/dist/xstate-dev.umd.min.js +1 -1
  24. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  25. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  26. package/dist/declarations/src/State.d.ts +47 -73
  27. package/dist/declarations/src/StateMachine.d.ts +29 -57
  28. package/dist/declarations/src/StateNode.d.ts +36 -33
  29. package/dist/declarations/src/actions/assign.d.ts +11 -2
  30. package/dist/declarations/src/actions/cancel.d.ts +7 -3
  31. package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
  32. package/dist/declarations/src/actions/log.d.ts +7 -3
  33. package/dist/declarations/src/actions/raise.d.ts +7 -2
  34. package/dist/declarations/src/actions/send.d.ts +14 -36
  35. package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
  36. package/dist/declarations/src/actions/stopChild.d.ts +18 -0
  37. package/dist/declarations/src/actions.d.ts +8 -48
  38. package/dist/declarations/src/actors/callback.d.ts +91 -8
  39. package/dist/declarations/src/actors/index.d.ts +6 -28
  40. package/dist/declarations/src/actors/observable.d.ts +101 -18
  41. package/dist/declarations/src/actors/promise.d.ts +80 -10
  42. package/dist/declarations/src/actors/transition.d.ts +64 -9
  43. package/dist/declarations/src/constants.d.ts +3 -0
  44. package/dist/declarations/src/createMachine.d.ts +20 -0
  45. package/dist/declarations/src/dev/index.d.ts +6 -6
  46. package/dist/declarations/src/guards.d.ts +41 -8
  47. package/dist/declarations/src/index.d.ts +18 -23
  48. package/dist/declarations/src/interpreter.d.ts +149 -41
  49. package/dist/declarations/src/setup.d.ts +51 -0
  50. package/dist/declarations/src/spawn.d.ts +23 -2
  51. package/dist/declarations/src/stateUtils.d.ts +30 -45
  52. package/dist/declarations/src/system.d.ts +26 -2
  53. package/dist/declarations/src/typegenTypes.d.ts +34 -22
  54. package/dist/declarations/src/types.d.ts +527 -669
  55. package/dist/declarations/src/utils.d.ts +15 -52
  56. package/dist/declarations/src/waitFor.d.ts +2 -2
  57. package/dist/log-22e678c5.esm.js +364 -0
  58. package/dist/log-5e226275.cjs.js +372 -0
  59. package/dist/log-641cd926.development.cjs.js +394 -0
  60. package/dist/log-f196f85f.development.esm.js +386 -0
  61. package/dist/raise-34e25c2c.cjs.js +2368 -0
  62. package/dist/raise-62704519.development.cjs.js +2422 -0
  63. package/dist/raise-89c581c4.development.esm.js +2371 -0
  64. package/dist/raise-8bc422d1.esm.js +2317 -0
  65. package/dist/xstate.cjs.js +728 -4
  66. package/dist/xstate.cjs.mjs +9 -9
  67. package/dist/xstate.development.cjs.js +737 -0
  68. package/dist/xstate.development.cjs.mjs +39 -0
  69. package/dist/xstate.development.esm.js +699 -0
  70. package/dist/xstate.esm.js +561 -770
  71. package/dist/xstate.umd.min.js +1 -1
  72. package/dist/xstate.umd.min.js.map +1 -1
  73. package/guards/dist/xstate-guards.cjs.js +12 -5
  74. package/guards/dist/xstate-guards.cjs.mjs +1 -2
  75. package/guards/dist/xstate-guards.development.cjs.js +14 -0
  76. package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
  77. package/guards/dist/xstate-guards.development.esm.js +2 -0
  78. package/guards/dist/xstate-guards.esm.js +2 -2
  79. package/guards/dist/xstate-guards.umd.min.js +1 -1
  80. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  81. package/package.json +53 -1
  82. package/actions/dist/xstate-actions.cjs.dev.js +0 -32
  83. package/actions/dist/xstate-actions.cjs.prod.js +0 -32
  84. package/actions/dynamicAction.ts +0 -42
  85. package/actors/dist/xstate-actors.cjs.dev.js +0 -22
  86. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  87. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  88. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  89. package/dist/actions-b6357569.cjs.dev.js +0 -4437
  90. package/dist/actions-bd4a184d.cjs.prod.js +0 -4423
  91. package/dist/actions-de434a04.esm.js +0 -4348
  92. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  93. package/dist/declarations/src/Machine.d.ts +0 -4
  94. package/dist/declarations/src/Mailbox.d.ts +0 -12
  95. package/dist/declarations/src/actionTypes.d.ts +0 -16
  96. package/dist/declarations/src/actions/choose.d.ts +0 -3
  97. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  98. package/dist/declarations/src/actions/pure.d.ts +0 -6
  99. package/dist/declarations/src/actions/stop.d.ts +0 -7
  100. package/dist/declarations/src/environment.d.ts +0 -1
  101. package/dist/declarations/src/mapState.d.ts +0 -3
  102. package/dist/declarations/src/memo.d.ts +0 -2
  103. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  104. package/dist/xstate.cjs.dev.js +0 -950
  105. package/dist/xstate.cjs.prod.js +0 -947
  106. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
  107. package/guards/dist/xstate-guards.cjs.prod.js +0 -15
@@ -1,13 +1,68 @@
1
- import { ActorBehavior, ActorContext, ActorSystem, EventObject } from '../types';
1
+ import { ActorLogic, ActorScope, ActorSystem, EventObject, ActorRefFrom, AnyActorSystem, Snapshot, NonReducibleUnknown } from "../types.js";
2
+ export type TransitionSnapshot<TContext> = Snapshot<undefined> & {
3
+ context: TContext;
4
+ };
5
+ export type TransitionActorLogic<TContext, TEvent extends EventObject, TInput extends NonReducibleUnknown> = ActorLogic<TransitionSnapshot<TContext>, TEvent, TInput, AnyActorSystem>;
6
+ export type TransitionActorRef<TContext, TEvent extends EventObject> = ActorRefFrom<TransitionActorLogic<TransitionSnapshot<TContext>, TEvent, unknown>>;
2
7
  /**
3
- * Returns an actor behavior from a transition function and its initial state.
8
+ * Returns actor logic given a transition function and its initial state.
4
9
  *
5
- * A transition function is a function that takes the current state and an event and returns the next state.
10
+ * A transition function is a function that takes the current `state` and received `event` object as arguments, and returns the next state, similar to a reducer.
6
11
  *
7
- * @param transition The transition function that returns the next state given the current state and event.
8
- * @param initialState The initial state of the transition function.
9
- * @returns An actor behavior
12
+ * Actors created from transition logic (“transition actors”) can:
13
+ *
14
+ * - Receive events
15
+ * - Emit snapshots of its state
16
+ *
17
+ * The transition function’s `state` is used as its transition actor’s `context`.
18
+ *
19
+ * Note that the "state" for a transition function is provided by the initial state argument, and is not the same as the State object of an actor or a state within a machine configuration.
20
+ *
21
+ * @param transition The transition function used to describe the transition logic. It should return the next state given the current state and event. It receives the following arguments:
22
+ * - `state` - the current state.
23
+ * - `event` - the received event.
24
+ * - `actorScope` - the actor scope object, with properties like `self` and `system`.
25
+ * @param initialContext The initial state of the transition function, either an object representing the state, or a function which returns a state object. If a function, it will receive as its only argument an object with the following properties:
26
+ * - `input` - the `input` provided to its parent transition actor.
27
+ * - `self` - a reference to its parent transition actor.
28
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
29
+ * @returns Actor logic
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const transitionLogic = fromTransition(
34
+ * (state, event) => {
35
+ * if (event.type === 'increment') {
36
+ * return {
37
+ * ...state,
38
+ * count: state.count + 1,
39
+ * };
40
+ * }
41
+ * return state;
42
+ * },
43
+ * { count: 0 },
44
+ * );
45
+ *
46
+ * const transitionActor = createActor(transitionLogic);
47
+ * transitionActor.subscribe((snapshot) => {
48
+ * console.log(snapshot);
49
+ * });
50
+ * transitionActor.start();
51
+ * // => {
52
+ * // status: 'active',
53
+ * // context: { count: 0 },
54
+ * // ...
55
+ * // }
56
+ *
57
+ * transitionActor.send({ type: 'increment' });
58
+ * // => {
59
+ * // status: 'active',
60
+ * // context: { count: 1 },
61
+ * // ...
62
+ * // }
63
+ * ```
10
64
  */
11
- export declare function fromTransition<TState, TEvent extends EventObject, TSystem extends ActorSystem<any>>(transition: (state: TState, event: TEvent, actorContext: ActorContext<TEvent, TState, TSystem>) => TState, initialState: TState | (({ input }: {
12
- input: any;
13
- }) => TState)): ActorBehavior<TEvent, TState, TState>;
65
+ export declare function fromTransition<TContext, TEvent extends EventObject, TSystem extends ActorSystem<any>, TInput extends NonReducibleUnknown>(transition: (snapshot: TContext, event: TEvent, actorScope: ActorScope<TransitionSnapshot<TContext>, TEvent, TSystem>) => TContext, initialContext: TContext | (({ input, self }: {
66
+ input: TInput;
67
+ self: TransitionActorRef<TContext, TEvent>;
68
+ }) => TContext)): TransitionActorLogic<TContext, TEvent, TInput>;
@@ -3,3 +3,6 @@ export declare const TARGETLESS_KEY = "";
3
3
  export declare const NULL_EVENT = "";
4
4
  export declare const STATE_IDENTIFIER = "#";
5
5
  export declare const WILDCARD = "*";
6
+ export declare const XSTATE_INIT = "xstate.init";
7
+ export declare const XSTATE_ERROR = "xstate.error";
8
+ export declare const XSTATE_STOP = "xstate.stop";
@@ -0,0 +1,20 @@
1
+ import { StateMachine } from "./StateMachine.js";
2
+ import { ResolveTypegenMeta, TypegenConstraint, TypegenDisabled } from "./typegenTypes.js";
3
+ import { AnyActorRef, AnyEventObject, Cast, InternalMachineImplementations, IsNever, MachineConfig, MachineContext, NonReducibleUnknown, ParameterizedObject, Prop, ProvidedActor, StateValue, ToChildren } from "./types.js";
4
+ type TestValue = string | {
5
+ [k: string]: TestValue | undefined;
6
+ };
7
+ type _GroupTestValues<TTestValue extends string | TestValue> = TTestValue extends string ? TTestValue extends `${string}.${string}` ? [never, never] : [TTestValue, never] : [never, TTestValue];
8
+ type GroupTestValues<TTestValue extends string | TestValue> = {
9
+ leafCandidates: _GroupTestValues<TTestValue>[0];
10
+ nonLeaf: _GroupTestValues<TTestValue>[1];
11
+ };
12
+ type FilterLeafValues<TLeafCandidate extends string, TNonLeaf extends {
13
+ [k: string]: TestValue | undefined;
14
+ }> = IsNever<TNonLeaf> extends true ? TLeafCandidate : TLeafCandidate extends string ? TLeafCandidate extends keyof TNonLeaf ? never : TLeafCandidate : never;
15
+ type ToStateValue<TTestValue extends string | TestValue> = FilterLeafValues<GroupTestValues<TTestValue>['leafCandidates'], GroupTestValues<TTestValue>['nonLeaf']> | (IsNever<GroupTestValues<TTestValue>['nonLeaf']> extends false ? {
16
+ [K in keyof GroupTestValues<TTestValue>['nonLeaf']]: ToStateValue<NonNullable<GroupTestValues<TTestValue>['nonLeaf'][K]>>;
17
+ } : never);
18
+ export declare function createMachine<TContext extends MachineContext, TEvent extends AnyEventObject, // TODO: consider using a stricter `EventObject` here
19
+ TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TTag extends string, TInput, TOutput extends NonReducibleUnknown, TTypesMeta extends TypegenConstraint = TypegenDisabled>(config: MachineConfig<TContext, TEvent, TActor, TAction, TGuard, TDelay, TTag, TInput, TOutput, TTypesMeta>, implementations?: InternalMachineImplementations<TContext, ResolveTypegenMeta<TTypesMeta, TEvent, TActor, TAction, TGuard, TDelay, TTag>>): StateMachine<TContext, TEvent, Cast<ToChildren<TActor>, Record<string, AnyActorRef | undefined>>, TActor, TAction, TGuard, TDelay, 'matchesStates' extends keyof TTypesMeta ? ToStateValue<Cast<TTypesMeta['matchesStates'], TestValue>> : StateValue, Prop<ResolveTypegenMeta<TTypesMeta, TEvent, TActor, TAction, TGuard, TDelay, TTag>['resolved'], 'tags'> & string, TInput, TOutput, ResolveTypegenMeta<TTypesMeta, TEvent, TActor, TAction, TGuard, TDelay, TTag>>;
20
+ export {};
@@ -1,14 +1,14 @@
1
- import { AnyInterpreter, DevToolsAdapter } from '../types.ts';
2
- type ServiceListener = (service: AnyInterpreter) => void;
1
+ import { AnyActor, DevToolsAdapter } from "../types.js";
2
+ type ServiceListener = (service: AnyActor) => void;
3
3
  export interface XStateDevInterface {
4
- register: (service: AnyInterpreter) => void;
5
- unregister: (service: AnyInterpreter) => void;
4
+ register: (service: AnyActor) => void;
5
+ unregister: (service: AnyActor) => void;
6
6
  onRegister: (listener: ServiceListener) => {
7
7
  unsubscribe: () => void;
8
8
  };
9
- services: Set<AnyInterpreter>;
9
+ services: Set<AnyActor>;
10
10
  }
11
11
  export declare function getGlobal(): typeof globalThis | undefined;
12
- export declare function registerService(service: AnyInterpreter): void;
12
+ export declare function registerService(service: AnyActor): void;
13
13
  export declare const devToolsAdapter: DevToolsAdapter;
14
14
  export {};
@@ -1,8 +1,41 @@
1
- import type { EventObject, StateValue, BooleanGuardDefinition, GuardConfig, GuardDefinition, SCXML, GuardPredicate, MachineContext } from './types.ts';
2
- import type { State } from './State.ts';
3
- export declare function stateIn<TContext extends MachineContext, TEvent extends EventObject>(stateValue: StateValue): GuardDefinition<TContext, TEvent>;
4
- export declare function not<TContext extends MachineContext, TEvent extends EventObject>(guard: GuardConfig<TContext, TEvent>): BooleanGuardDefinition<TContext, TEvent>;
5
- export declare function and<TContext extends MachineContext, TEvent extends EventObject>(guards: Array<GuardConfig<TContext, TEvent>>): BooleanGuardDefinition<TContext, TEvent>;
6
- export declare function or<TContext extends MachineContext, TEvent extends EventObject>(guards: Array<GuardConfig<TContext, TEvent>>): BooleanGuardDefinition<TContext, TEvent>;
7
- export declare function evaluateGuard<TContext extends MachineContext, TEvent extends EventObject>(guard: GuardDefinition<TContext, TEvent>, context: TContext, _event: SCXML.Event<TEvent>, state: State<TContext, TEvent>): boolean;
8
- export declare function toGuardDefinition<TContext extends MachineContext, TEvent extends EventObject>(guardConfig: GuardConfig<TContext, TEvent>, getPredicate?: (guardType: string) => GuardPredicate<TContext, TEvent>): GuardDefinition<TContext, TEvent>;
1
+ import type { EventObject, StateValue, MachineContext, ParameterizedObject, AnyMachineSnapshot, NoRequiredParams, NoInfer, WithDynamicParams, Identity, Elements } from "./types.js";
2
+ type SingleGuardArg<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TGuardArg> = [TGuardArg] extends [{
3
+ type: string;
4
+ }] ? Identity<TGuardArg> : [TGuardArg] extends [string] ? TGuardArg : GuardPredicate<TContext, TExpressionEvent, TParams, ParameterizedObject>;
5
+ type NormalizeGuardArg<TGuardArg> = TGuardArg extends {
6
+ type: string;
7
+ } ? Identity<TGuardArg> & {
8
+ params: unknown;
9
+ } : TGuardArg extends string ? {
10
+ type: TGuardArg;
11
+ params: undefined;
12
+ } : '_out_TGuard' extends keyof TGuardArg ? TGuardArg['_out_TGuard'] & ParameterizedObject : never;
13
+ type NormalizeGuardArgArray<TArg extends unknown[]> = Elements<{
14
+ [K in keyof TArg]: NormalizeGuardArg<TArg[K]>;
15
+ }>;
16
+ export type GuardPredicate<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TGuard extends ParameterizedObject> = {
17
+ (args: GuardArgs<TContext, TExpressionEvent>, params: TParams): boolean;
18
+ _out_TGuard?: TGuard;
19
+ };
20
+ export interface GuardArgs<TContext extends MachineContext, TExpressionEvent extends EventObject> {
21
+ context: TContext;
22
+ event: TExpressionEvent;
23
+ }
24
+ export type Guard<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TGuard extends ParameterizedObject> = NoRequiredParams<TGuard> | WithDynamicParams<TContext, TExpressionEvent, TGuard> | GuardPredicate<TContext, TExpressionEvent, TParams, TGuard>;
25
+ export type UnknownGuard = UnknownReferencedGuard | UnknownInlineGuard;
26
+ type UnknownReferencedGuard = Guard<MachineContext, EventObject, ParameterizedObject['params'], ParameterizedObject>;
27
+ type UnknownInlineGuard = Guard<MachineContext, EventObject, undefined, ParameterizedObject>;
28
+ export declare function stateIn<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined>(stateValue: StateValue): GuardPredicate<TContext, TExpressionEvent, TParams, any>;
29
+ export declare function not<TContext extends MachineContext, TExpressionEvent extends EventObject, TArg>(guard: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg>): GuardPredicate<TContext, TExpressionEvent, unknown, NormalizeGuardArg<NoInfer<TArg>>>;
30
+ export declare function and<TContext extends MachineContext, TExpressionEvent extends EventObject, TArg extends unknown[]>(guards: readonly [
31
+ ...{
32
+ [K in keyof TArg]: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg[K]>;
33
+ }
34
+ ]): GuardPredicate<TContext, TExpressionEvent, unknown, NormalizeGuardArgArray<NoInfer<TArg>>>;
35
+ export declare function or<TContext extends MachineContext, TExpressionEvent extends EventObject, TArg extends unknown[]>(guards: readonly [
36
+ ...{
37
+ [K in keyof TArg]: SingleGuardArg<TContext, TExpressionEvent, unknown, TArg[K]>;
38
+ }
39
+ ]): GuardPredicate<TContext, TExpressionEvent, unknown, NormalizeGuardArgArray<NoInfer<TArg>>>;
40
+ export declare function evaluateGuard<TContext extends MachineContext, TExpressionEvent extends EventObject>(guard: UnknownGuard | UnknownInlineGuard, context: TContext, event: TExpressionEvent, snapshot: AnyMachineSnapshot): boolean;
41
+ export {};
@@ -1,26 +1,21 @@
1
- import { doneInvoke, forwardTo, sendParent, sendTo } from './actions.ts';
2
- export { assign } from './actions/assign.ts';
3
- export { cancel } from './actions/cancel.ts';
4
- export { choose } from './actions/choose.ts';
5
- export { log } from './actions/log.ts';
6
- export { pure } from './actions/pure.ts';
7
- export { raise } from './actions/raise.ts';
8
- export { stop } from './actions/stop.ts';
9
- import { interpret, Interpreter, ActorStatus } from './interpreter.ts';
10
- import { createMachine } from './Machine.ts';
11
- import { mapState } from './mapState.ts';
12
- import { State } from './State.ts';
13
- import { StateNode } from './StateNode.ts';
14
- export { SimulatedClock } from './SimulatedClock.ts';
15
- export { StateMachine } from './StateMachine.ts';
16
- export { getStateNodes } from './stateUtils.ts';
17
- export { waitFor } from './waitFor.ts';
18
- export * from './typegenTypes.ts';
19
- export * from './types.ts';
20
- export { matchesState, pathToStateValue, toObserver, toSCXMLEvent } from './utils.ts';
21
- export { StateNode, State, mapState, sendTo, sendParent, forwardTo, interpret, Interpreter, ActorStatus as InterpreterStatus, doneInvoke, createMachine };
22
- export { fromPromise, fromObservable, fromCallback, fromEventObservable, fromTransition } from './actors/index.ts';
23
- export { stateIn, not, and, or } from './guards.ts';
1
+ export * from "./actions.js";
2
+ export * from "./actors/index.js";
3
+ export { SimulatedClock } from "./SimulatedClock.js";
4
+ export { type Spawner } from "./spawn.js";
5
+ export { StateMachine } from "./StateMachine.js";
6
+ export { getStateNodes } from "./stateUtils.js";
7
+ export * from "./typegenTypes.js";
8
+ export * from "./types.js";
9
+ export { waitFor } from "./waitFor.js";
10
+ import { Actor, createActor, interpret, Interpreter } from "./interpreter.js";
11
+ import { createMachine } from "./createMachine.js";
12
+ export { type MachineSnapshot, isMachineSnapshot } from "./State.js";
13
+ import { StateNode } from "./StateNode.js";
14
+ export { matchesState, pathToStateValue, toObserver, getAllOwnEventDescriptors as __unsafe_getAllOwnEventDescriptors } from "./utils.js";
15
+ export { Actor, createActor, createMachine, interpret, StateNode, type Interpreter };
16
+ export type { InspectedActorEvent, InspectedEventEvent, InspectedSnapshotEvent, InspectionEvent } from "./system.js";
17
+ export { and, not, or, stateIn } from "./guards.js";
18
+ export { setup } from "./setup.js";
24
19
  declare global {
25
20
  interface SymbolConstructor {
26
21
  readonly observable: symbol;
@@ -1,8 +1,9 @@
1
- import { symbolObservable } from './symbolObservable.ts';
2
- import { AreAllImplementationsAssumedToBeProvided, MissingImplementationsError } from './typegenTypes.ts';
3
- import type { ActorSystem, AnyActorBehavior, AnyStateMachine, EventFromBehavior, InterpreterFrom, PersistedStateFrom, RaiseActionObject, SnapshotFrom } from './types.ts';
4
- import { ActorRef, DoneEvent, EventObject, InteropSubscribable, InterpreterOptions, Observer, SCXML, SendActionObject, Subscription } from './types.ts';
5
- export type SnapshotListener<TBehavior extends AnyActorBehavior> = (state: SnapshotFrom<TBehavior>) => void;
1
+ import { symbolObservable } from "./symbolObservable.js";
2
+ import { AreAllImplementationsAssumedToBeProvided, MissingImplementationsError } from "./typegenTypes.js";
3
+ import type { ActorSystem, AnyActorLogic, AnyStateMachine, EventFromLogic, SnapshotFrom, Snapshot } from "./types.js";
4
+ import { ActorRef, EventObject, InteropSubscribable, ActorOptions, Observer, Subscription } from "./types.js";
5
+ export declare const $$ACTOR_TYPE = 1;
6
+ export type SnapshotListener<TLogic extends AnyActorLogic> = (snapshot: SnapshotFrom<TLogic>) => void;
6
7
  export type EventListener<TEvent extends EventObject = EventObject> = (event: TEvent) => void;
7
8
  export type Listener = () => void;
8
9
  export type ErrorListener = (error: any) => void;
@@ -10,22 +11,25 @@ export interface Clock {
10
11
  setTimeout(fn: (...args: any[]) => void, timeout: number): any;
11
12
  clearTimeout(id: any): void;
12
13
  }
13
- export declare enum ActorStatus {
14
+ export declare enum ProcessingStatus {
14
15
  NotStarted = 0,
15
16
  Running = 1,
16
17
  Stopped = 2
17
18
  }
18
- export declare class Interpreter<TBehavior extends AnyActorBehavior, TEvent extends EventObject = EventFromBehavior<TBehavior>> implements ActorRef<TEvent, SnapshotFrom<TBehavior>> {
19
- behavior: TBehavior;
19
+ /**
20
+ * 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.
21
+ */
22
+ export declare class Actor<TLogic extends AnyActorLogic> implements ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>> {
23
+ logic: TLogic;
20
24
  /**
21
- * The current state of the interpreted behavior.
25
+ * The current internal state of the actor.
22
26
  */
23
- private _state;
27
+ private _snapshot;
24
28
  /**
25
29
  * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
26
30
  */
27
31
  clock: Clock;
28
- options: Readonly<InterpreterOptions<TBehavior>>;
32
+ options: Readonly<ActorOptions<TLogic>>;
29
33
  /**
30
34
  * The unique identifier for this actor relative to its parent.
31
35
  */
@@ -34,72 +38,176 @@ export declare class Interpreter<TBehavior extends AnyActorBehavior, TEvent exte
34
38
  private delayedEventsMap;
35
39
  private observers;
36
40
  private logger;
37
- /**
38
- * Whether the service is started.
39
- */
40
- status: ActorStatus;
41
- _parent?: ActorRef<any>;
42
- ref: ActorRef<TEvent>;
43
- private _actorContext;
41
+ _parent?: ActorRef<any, any>;
42
+ _syncSnapshot?: boolean;
43
+ ref: ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>>;
44
+ private _actorScope;
44
45
  private _systemId;
45
46
  /**
46
47
  * The globally unique process ID for this invocation.
47
48
  */
48
49
  sessionId: string;
50
+ /**
51
+ * The system to which this actor belongs.
52
+ */
49
53
  system: ActorSystem<any>;
50
54
  private _doneEvent?;
51
- src?: string;
55
+ src: string | AnyActorLogic;
52
56
  /**
53
- * Creates a new Interpreter instance (i.e., service) for the given behavior with the provided options, if any.
57
+ * Creates a new actor instance for the given logic with the provided options, if any.
54
58
  *
55
- * @param behavior The behavior to be interpreted
56
- * @param options Interpreter options
59
+ * @param logic The logic to create an actor from
60
+ * @param options Actor options
57
61
  */
58
- constructor(behavior: TBehavior, options?: InterpreterOptions<TBehavior>);
62
+ constructor(logic: TLogic, options?: ActorOptions<TLogic>);
59
63
  private _initState;
60
64
  private _deferred;
61
65
  private update;
62
- subscribe(observer: Observer<SnapshotFrom<TBehavior>>): Subscription;
63
- subscribe(nextListener?: (state: SnapshotFrom<TBehavior>) => void, errorListener?: (error: any) => void, completeListener?: () => void): Subscription;
64
66
  /**
65
- * Adds a state listener that is notified when the statechart has reached its final state.
66
- * @param listener The state listener
67
+ * Subscribe an observer to an actor’s snapshot values.
68
+ *
69
+ * @remarks
70
+ * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
71
+ * - A plain function that receives the latest snapshot, or
72
+ * - An observer object whose `.next(snapshot)` method receives the latest snapshot
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * // Observer as a plain function
77
+ * const subscription = actor.subscribe((snapshot) => {
78
+ * console.log(snapshot);
79
+ * });
80
+ * ```
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * // Observer as an object
85
+ * const subscription = actor.subscribe({
86
+ * next(snapshot) {
87
+ * console.log(snapshot);
88
+ * },
89
+ * error(err) {
90
+ * // ...
91
+ * },
92
+ * complete() {
93
+ * // ...
94
+ * },
95
+ * });
96
+ * ```
97
+ *
98
+ * 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:
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const subscription = actor.subscribe((snapshot) => {
103
+ * // ...
104
+ * });
105
+ *
106
+ * // Unsubscribe the observer
107
+ * subscription.unsubscribe();
108
+ * ```
109
+ *
110
+ * When the actor is stopped, all of its observers will automatically be unsubscribed.
111
+ *
112
+ * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot
67
113
  */
68
- onDone(listener: EventListener<DoneEvent>): this;
114
+ subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;
115
+ subscribe(nextListener?: (snapshot: SnapshotFrom<TLogic>) => void, errorListener?: (error: any) => void, completeListener?: () => void): Subscription;
69
116
  /**
70
- * Starts the interpreter from the initial state
117
+ * Starts the Actor from the initial state
71
118
  */
72
119
  start(): this;
73
120
  private _process;
74
121
  private _stop;
75
122
  /**
76
- * Stops the interpreter and unsubscribe all listeners.
123
+ * Stops the Actor and unsubscribe all listeners.
77
124
  */
78
125
  stop(): this;
79
126
  private _complete;
127
+ private _reportError;
80
128
  private _error;
81
129
  private _stopProcedure;
82
130
  /**
83
- * Sends an event to the running interpreter to trigger a transition.
131
+ * Sends an event to the running Actor to trigger a transition.
84
132
  *
85
133
  * @param event The event to send
86
134
  */
87
- send(event: TEvent | SCXML.Event<TEvent>): void;
88
- delaySend(sendAction: SendActionObject | RaiseActionObject<any, any, any>): void;
89
- cancel(sendId: string | number): void;
135
+ send(event: EventFromLogic<TLogic>): void;
90
136
  private attachDevTools;
91
137
  toJSON(): {
138
+ xstate$$type: number;
92
139
  id: string;
93
140
  };
94
- getPersistedState(): PersistedStateFrom<TBehavior> | undefined;
95
- [Symbol.observable](): InteropSubscribable<SnapshotFrom<TBehavior>>;
96
- getSnapshot(): SnapshotFrom<TBehavior>;
141
+ /**
142
+ * Obtain the internal state of the actor, which can be persisted.
143
+ *
144
+ * @remarks
145
+ * The internal state can be persisted from any actor, not only machines.
146
+ *
147
+ * 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.
148
+ *
149
+ * Can be restored with {@link ActorOptions.state}
150
+ *
151
+ * @see https://stately.ai/docs/persistence
152
+ */
153
+ getPersistedSnapshot(): Snapshot<unknown>;
154
+ [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>>;
155
+ /**
156
+ * Read an actor’s snapshot synchronously.
157
+ *
158
+ * @remarks
159
+ * The snapshot represent an actor's last emitted value.
160
+ *
161
+ * When an actor receives an event, its internal state may change.
162
+ * An actor may emit a snapshot when a state transition occurs.
163
+ *
164
+ * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.
165
+ *
166
+ * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
167
+ * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
168
+ */
169
+ getSnapshot(): SnapshotFrom<TLogic>;
97
170
  }
171
+ /**
172
+ * Creates a new actor instance for the given actor logic with the provided options, if any.
173
+ *
174
+ * @remarks
175
+ * 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.
176
+ * Any actors spawned from this root actor and its descendants are part of that actor system.
177
+ *
178
+ * @example
179
+ * ```ts
180
+ * import { createActor } from 'xstate';
181
+ * import { someActorLogic } from './someActorLogic.ts';
182
+ *
183
+ * // Creating the actor, which implicitly creates an actor system with itself as the root actor
184
+ * const actor = createActor(someActorLogic);
185
+ *
186
+ * actor.subscribe((snapshot) => {
187
+ * console.log(snapshot);
188
+ * });
189
+ *
190
+ * // Actors must be started by calling `actor.start()`, which will also start the actor system.
191
+ * actor.start();
192
+ *
193
+ * // Actors can receive events
194
+ * actor.send({ type: 'someEvent' });
195
+ *
196
+ * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
197
+ * actor.stop();
198
+ * ```
199
+ *
200
+ * @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}.
201
+ * @param options - Actor options
202
+ */
203
+ export declare function createActor<TLogic extends AnyActorLogic>(logic: TLogic extends AnyStateMachine ? AreAllImplementationsAssumedToBeProvided<TLogic['__TResolvedTypesMeta']> extends true ? TLogic : MissingImplementationsError<TLogic['__TResolvedTypesMeta']> : TLogic, options?: ActorOptions<TLogic>): Actor<TLogic>;
98
204
  /**
99
205
  * Creates a new Interpreter instance for the given machine with the provided options, if any.
100
206
  *
101
- * @param machine The machine to interpret
102
- * @param options Interpreter options
207
+ * @deprecated Use `createActor` instead
208
+ */
209
+ export declare const interpret: typeof createActor;
210
+ /**
211
+ * @deprecated Use `Actor` instead.
103
212
  */
104
- export declare function interpret<TMachine extends AnyStateMachine>(machine: AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends true ? TMachine : MissingImplementationsError<TMachine['__TResolvedTypesMeta']>, options?: InterpreterOptions<TMachine>): InterpreterFrom<TMachine>;
105
- export declare function interpret<TBehavior extends AnyActorBehavior>(behavior: TBehavior, options?: InterpreterOptions<TBehavior>): Interpreter<TBehavior>;
213
+ export type Interpreter = typeof Actor;
@@ -0,0 +1,51 @@
1
+ import { StateMachine } from "./StateMachine.js";
2
+ import { GuardPredicate } from "./guards.js";
3
+ import { ResolveTypegenMeta, TypegenDisabled } from "./typegenTypes.js";
4
+ import { ActionFunction, AnyActorLogic, AnyActorRef, AnyEventObject, Cast, ConditionalRequired, DelayConfig, Invert, IsNever, MachineConfig, MachineContext, NonReducibleUnknown, ParameterizedObject, SetupTypes, StateSchema, ToChildren, UnknownActorLogic, Values } from "./types.js";
5
+ type ToParameterizedObject<TParameterizedMap extends Record<string, ParameterizedObject['params'] | undefined>> = Values<{
6
+ [K in keyof TParameterizedMap & string]: {
7
+ type: K;
8
+ params: TParameterizedMap[K];
9
+ };
10
+ }>;
11
+ type DefaultToAnyActors<TActors extends Record<string, AnyActorLogic>> = IsNever<keyof TActors> extends true ? Record<string, AnyActorLogic> : TActors;
12
+ type ToProvidedActor<TChildrenMap extends Record<string, string>, TActors extends Record<Values<TChildrenMap>, AnyActorLogic>, TResolvedActors extends Record<string, AnyActorLogic> = DefaultToAnyActors<TActors>> = Values<{
13
+ [K in keyof TResolvedActors & string]: {
14
+ src: K;
15
+ logic: TResolvedActors[K];
16
+ id: IsNever<TChildrenMap> extends true ? string | undefined : K extends keyof Invert<TChildrenMap> ? Invert<TChildrenMap>[K] : string | undefined;
17
+ };
18
+ }>;
19
+ type _GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = S extends any ? T['states'][S] extends {
20
+ type: 'history';
21
+ } ? [never, never] : T extends {
22
+ type: 'parallel';
23
+ } ? [S, never] : 'states' extends keyof T['states'][S] ? [S, never] : [never, S] : never;
24
+ type GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {
25
+ nonLeaf: _GroupStateKeys<T, S & string>[0];
26
+ leaf: _GroupStateKeys<T, S & string>[1];
27
+ };
28
+ type ToStateValue<T extends StateSchema> = T extends {
29
+ states: Record<infer S, any>;
30
+ } ? IsNever<S> extends true ? {} : GroupStateKeys<T, S>['leaf'] | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false ? ConditionalRequired<{
31
+ [K in GroupStateKeys<T, S>['nonLeaf']]?: ToStateValue<T['states'][K]>;
32
+ }, T extends {
33
+ type: 'parallel';
34
+ } ? true : false> : never) : {};
35
+ export declare function setup<TContext extends MachineContext, TEvent extends AnyEventObject, // TODO: consider using a stricter `EventObject` here
36
+ TActors extends Record<Values<TChildrenMap>, UnknownActorLogic>, TActions extends Record<string, ParameterizedObject['params'] | undefined>, TGuards extends Record<string, ParameterizedObject['params'] | undefined>, TDelay extends string, TTag extends string, TInput, TOutput extends NonReducibleUnknown, TChildrenMap extends Record<string, string> = never>({ actors, actions, guards, delays }: {
37
+ types?: SetupTypes<TContext, TEvent, TChildrenMap, TTag, TInput, TOutput>;
38
+ actors?: TActors;
39
+ actions?: {
40
+ [K in keyof TActions]: ActionFunction<TContext, TEvent, TEvent, TActions[K], ToProvidedActor<TChildrenMap, TActors>, ToParameterizedObject<TActions>, ToParameterizedObject<TGuards>, TDelay>;
41
+ };
42
+ guards?: {
43
+ [K in keyof TGuards]: GuardPredicate<TContext, TEvent, TGuards[K], ToParameterizedObject<TGuards>>;
44
+ };
45
+ delays?: {
46
+ [K in TDelay]: DelayConfig<TContext, TEvent, ToParameterizedObject<TActions>['params'], TEvent>;
47
+ };
48
+ }): {
49
+ createMachine: <const TConfig extends MachineConfig<TContext, TEvent, ToProvidedActor<TChildrenMap, TActors>, ToParameterizedObject<TActions>, ToParameterizedObject<TGuards>, TDelay, TTag, TInput, TOutput, ResolveTypegenMeta<TypegenDisabled, TEvent, ToProvidedActor<TChildrenMap, TActors>, ToParameterizedObject<TActions>, ToParameterizedObject<TGuards>, TDelay, TTag>>>(config: TConfig) => StateMachine<TContext, TEvent, Cast<ToChildren<ToProvidedActor<TChildrenMap, TActors>>, Record<string, AnyActorRef | undefined>>, ToProvidedActor<TChildrenMap, TActors>, ToParameterizedObject<TActions>, ToParameterizedObject<TGuards>, TDelay, ToStateValue<TConfig>, TTag, TInput, TOutput, ResolveTypegenMeta<TypegenDisabled, TEvent, ToProvidedActor<TChildrenMap, TActors>, ToParameterizedObject<TActions>, ToParameterizedObject<TGuards>, TDelay, TTag>>;
50
+ };
51
+ export {};
@@ -1,2 +1,23 @@
1
- import { InvokeActionObject, AnyStateMachine, Spawner, ActorRef, MachineContext, EventObject, SCXML } from './index.ts';
2
- export declare function createSpawner<TContext extends MachineContext, TEvent extends EventObject>(self: ActorRef<any, any> | undefined, machine: AnyStateMachine, context: TContext, _event: SCXML.Event<TEvent>, mutCapturedActions: InvokeActionObject[]): Spawner;
1
+ import { ActorRefFrom, AnyActorScope, AnyActorLogic, AnyActorRef, AnyEventObject, AnyMachineSnapshot, InputFrom, IsLiteralString, ProvidedActor, RequiredActorOptions, IsNotNever, ConditionalRequired } from "./types.js";
2
+ type SpawnOptions<TActor extends ProvidedActor, TSrc extends TActor['src']> = TActor extends {
3
+ src: TSrc;
4
+ } ? ConditionalRequired<[
5
+ options?: {
6
+ id?: TActor['id'];
7
+ systemId?: string;
8
+ input?: InputFrom<TActor['logic']>;
9
+ syncSnapshot?: boolean;
10
+ } & {
11
+ [K in RequiredActorOptions<TActor>]: unknown;
12
+ }
13
+ ], IsNotNever<RequiredActorOptions<TActor>>> : never;
14
+ export type Spawner<TActor extends ProvidedActor> = IsLiteralString<TActor['src']> extends true ? <TSrc extends TActor['src']>(logic: TSrc, ...[options]: SpawnOptions<TActor, TSrc>) => ActorRefFrom<(TActor & {
15
+ src: TSrc;
16
+ })['logic']> : <TLogic extends AnyActorLogic | string>(src: TLogic, options?: {
17
+ id?: string;
18
+ systemId?: string;
19
+ input?: unknown;
20
+ syncSnapshot?: boolean;
21
+ }) => TLogic extends string ? AnyActorRef : ActorRefFrom<TLogic>;
22
+ export declare function createSpawner(actorScope: AnyActorScope, { machine, context }: AnyMachineSnapshot, event: AnyEventObject, spawnedChildren: Record<string, AnyActorRef>): Spawner<any>;
23
+ export {};