xstate 4.7.7 → 4.9.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.
package/es/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { matchesState } from './utils.js';
2
2
  export { mapState } from './mapState.js';
3
3
  export { ActionTypes, SpecialTargets } from './types.js';
4
- import { raise, send, sendParent, sendUpdate, log, cancel, start, stop, assign, after, done, respond, forwardTo, escalate } from './actions.js';
4
+ import { raise, send, sendParent, sendUpdate, log, cancel, start, stop, assign, after, done, respond, forwardTo, escalate, choose, pure } from './actions.js';
5
5
  export { assign, doneInvoke, forwardTo, send, sendParent, sendUpdate } from './actions.js';
6
6
  export { State } from './State.js';
7
7
  export { StateNode } from './StateNode.js';
@@ -22,6 +22,8 @@ var actions = {
22
22
  done: done,
23
23
  respond: respond,
24
24
  forwardTo: forwardTo,
25
- escalate: escalate
25
+ escalate: escalate,
26
+ choose: choose,
27
+ pure: pure
26
28
  };
27
29
  export { actions };
@@ -64,7 +64,7 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
64
64
  */
65
65
  constructor(machine: StateMachine<TContext, TStateSchema, TEvent, TTypestate>, options?: Partial<InterpreterOptions>);
66
66
  get initialState(): State<TContext, TEvent>;
67
- get state(): State<TContext, TEvent>;
67
+ get state(): State<TContext, TEvent, any, TTypestate>;
68
68
  static interpret: typeof interpret;
69
69
  /**
70
70
  * Executes the actions of the given state, with that state's `context` and `event`.
@@ -110,12 +110,12 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
110
110
  /**
111
111
  * Alias for Interpreter.prototype.start
112
112
  */
113
- init: (initialState?: string | State<TContext, TEvent, any, any> | import("./types").StateValueMap | undefined) => Interpreter<TContext, TStateSchema, TEvent, any>;
113
+ init: (initialState?: string | State<TContext, TEvent, any, any> | import("./types").StateValueMap | undefined) => Interpreter<TContext, TStateSchema, TEvent, TTypestate>;
114
114
  /**
115
115
  * Starts the interpreter from the given state, or the initial state.
116
116
  * @param initialState The state to start the statechart from
117
117
  */
118
- start(initialState?: State<TContext, TEvent> | StateValue): Interpreter<TContext, TStateSchema, TEvent>;
118
+ start(initialState?: State<TContext, TEvent> | StateValue): Interpreter<TContext, TStateSchema, TEvent, TTypestate>;
119
119
  /**
120
120
  * Stops the interpreter and unsubscribe all listeners.
121
121
  *
@@ -152,6 +152,7 @@ export declare class Interpreter<TContext, TStateSchema extends StateSchema = an
152
152
  private defer;
153
153
  private cancel;
154
154
  private exec;
155
+ private removeChild;
155
156
  private stopChild;
156
157
  spawn(entity: Spawnable, name: string, options?: SpawnOptions): Actor;
157
158
  spawnMachine<TChildContext, TChildStateSchema, TChildEvent extends EventObject>(machine: StateMachine<TChildContext, TChildStateSchema, TChildEvent>, options?: {
package/es/interpreter.js CHANGED
@@ -21,9 +21,7 @@ var DEFAULT_SPAWN_OPTIONS = {
21
21
  * @private
22
22
  */
23
23
 
24
- var withServiceScope =
25
- /*#__PURE__*/
26
- function () {
24
+ var withServiceScope = /*#__PURE__*/function () {
27
25
  var serviceStack = [];
28
26
  return function (service, fn) {
29
27
  service && serviceStack.push(service);
@@ -866,6 +864,12 @@ function () {
866
864
  return undefined;
867
865
  };
868
866
 
867
+ Interpreter.prototype.removeChild = function (childId) {
868
+ this.children.delete(childId);
869
+ this.forwardTo.delete(childId);
870
+ delete this.state.children[childId];
871
+ };
872
+
869
873
  Interpreter.prototype.stopChild = function (childId) {
870
874
  var child = this.children.get(childId);
871
875
 
@@ -873,9 +877,7 @@ function () {
873
877
  return;
874
878
  }
875
879
 
876
- this.children.delete(childId);
877
- this.forwardTo.delete(childId);
878
- delete this.state.children[childId];
880
+ this.removeChild(childId);
879
881
 
880
882
  if (isFunction(child.stop)) {
881
883
  child.stop();
@@ -923,11 +925,6 @@ function () {
923
925
  });
924
926
  }
925
927
 
926
- childService.onDone(function (doneEvent) {
927
- _this.send(toSCXMLEvent(doneEvent, {
928
- origin: childService.id
929
- }));
930
- }).start();
931
928
  var actor = childService;
932
929
  this.children.set(childService.id, actor);
933
930
 
@@ -935,6 +932,13 @@ function () {
935
932
  this.forwardTo.add(childService.id);
936
933
  }
937
934
 
935
+ childService.onDone(function (doneEvent) {
936
+ _this.removeChild(childService.id);
937
+
938
+ _this.send(toSCXMLEvent(doneEvent, {
939
+ origin: childService.id
940
+ }));
941
+ }).start();
938
942
  return actor;
939
943
  };
940
944
 
@@ -944,12 +948,16 @@ function () {
944
948
  var canceled = false;
945
949
  promise.then(function (response) {
946
950
  if (!canceled) {
951
+ _this.removeChild(id);
952
+
947
953
  _this.send(toSCXMLEvent(doneInvoke(id, response), {
948
954
  origin: id
949
955
  }));
950
956
  }
951
957
  }, function (errorData) {
952
958
  if (!canceled) {
959
+ _this.removeChild(id);
960
+
953
961
  var errorEvent = error(id, errorData);
954
962
 
955
963
  try {
@@ -1094,10 +1102,14 @@ function () {
1094
1102
  origin: id
1095
1103
  }));
1096
1104
  }, function (err) {
1105
+ _this.removeChild(id);
1106
+
1097
1107
  _this.send(toSCXMLEvent(error(id, err), {
1098
1108
  origin: id
1099
1109
  }));
1100
1110
  }, function () {
1111
+ _this.removeChild(id);
1112
+
1101
1113
  _this.send(toSCXMLEvent(doneInvoke(id), {
1102
1114
  origin: id
1103
1115
  }));
@@ -1212,9 +1224,7 @@ function () {
1212
1224
  */
1213
1225
 
1214
1226
 
1215
- Interpreter.defaultOptions =
1216
- /*#__PURE__*/
1217
- function (global) {
1227
+ Interpreter.defaultOptions = /*#__PURE__*/function (global) {
1218
1228
  return {
1219
1229
  execute: true,
1220
1230
  deferEvents: true,
package/es/json.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { StateNode, ActionObject, Guard, InvokeDefinition } from './';
2
+ interface JSONFunction {
3
+ $function: string;
4
+ }
5
+ export declare function stringifyFunction(fn: Function): JSONFunction;
6
+ interface TransitionConfig {
7
+ target: string[];
8
+ source: string;
9
+ actions: Array<ActionObject<any, any>>;
10
+ cond: Guard<any, any> | undefined;
11
+ eventType: string;
12
+ }
13
+ interface StateNodeConfig {
14
+ type: StateNode['type'];
15
+ id: string;
16
+ key: string;
17
+ initial?: string;
18
+ entry: Array<ActionObject<any, any>>;
19
+ exit: Array<ActionObject<any, any>>;
20
+ on: {
21
+ [key: string]: TransitionConfig[];
22
+ };
23
+ invoke: Array<InvokeDefinition<any, any>>;
24
+ states: Record<string, StateNodeConfig>;
25
+ }
26
+ export declare function machineToJSON(stateNode: StateNode): StateNodeConfig;
27
+ export declare function stringify(machine: StateNode): string;
28
+ export declare function parse(machineString: string): StateNodeConfig;
29
+ export declare function jsonify<T extends Record<string, any>>(value: T): T;
30
+ export {};
31
+ //# sourceMappingURL=json.d.ts.map
package/es/registry.js CHANGED
@@ -1,6 +1,4 @@
1
- var children =
2
- /*#__PURE__*/
3
- new Map();
1
+ var children = /*#__PURE__*/new Map();
4
2
  var sessionIdIndex = 0;
5
3
  var registry = {
6
4
  bookId: function () {
package/es/types.d.ts CHANGED
@@ -50,7 +50,11 @@ export interface AssignMeta<TContext, TEvent extends EventObject> {
50
50
  _event: SCXML.Event<TEvent>;
51
51
  }
52
52
  export declare type ActionFunction<TContext, TEvent extends EventObject> = (context: TContext, event: TEvent, meta: ActionMeta<TContext, TEvent>) => any | void;
53
- export declare type Action<TContext, TEvent extends EventObject> = ActionType | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | AssignAction<Required<TContext>, TEvent> | SendAction<TContext, TEvent> | RaiseAction<AnyEventObject>;
53
+ export interface ChooseConditon<TContext, TEvent extends EventObject> {
54
+ cond?: Condition<TContext, TEvent>;
55
+ actions: Actions<TContext, TEvent>;
56
+ }
57
+ export declare type Action<TContext, TEvent extends EventObject> = ActionType | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | AssignAction<Required<TContext>, TEvent> | SendAction<TContext, AnyEventObject> | RaiseAction<AnyEventObject> | ChooseAction<TContext, TEvent>;
54
58
  export declare type Actions<TContext, TEvent extends EventObject> = SingleOrArray<Action<TContext, TEvent>>;
55
59
  export declare type StateKey = string | State<any>;
56
60
  export interface StateValueMap {
@@ -124,7 +128,7 @@ export declare type InvokeCallback = (callback: Sender<any>, onReceive: Receiver
124
128
  * @param context The current machine `context`
125
129
  * @param event The event that invoked the service
126
130
  */
127
- export declare type InvokeCreator<TContext, TFinalContext = any> = (context: TContext, event: AnyEventObject) => PromiseLike<TFinalContext> | StateMachine<TFinalContext, any, any> | Subscribable<any> | InvokeCallback;
131
+ export declare type InvokeCreator<TContext, TEvent = AnyEventObject, TFinalContext = any> = (context: TContext, event: TEvent) => PromiseLike<TFinalContext> | StateMachine<TFinalContext, any, any> | Subscribable<any> | InvokeCallback;
128
132
  export interface InvokeDefinition<TContext, TEvent extends EventObject> extends ActivityDefinition<TContext, TEvent> {
129
133
  /**
130
134
  * The source of the machine to be invoked, or the machine itself.
@@ -171,21 +175,28 @@ export declare type StatesConfig<TContext, TStateSchema extends StateSchema, TEv
171
175
  export declare type StatesDefinition<TContext, TStateSchema extends StateSchema, TEvent extends EventObject> = {
172
176
  [K in keyof TStateSchema['states']]: StateNodeDefinition<TContext, TStateSchema['states'][K], TEvent>;
173
177
  };
174
- export declare type TransitionConfigTargetShortcut<TContext, TEvent extends EventObject> = string | undefined | StateNode<TContext, any, TEvent>;
178
+ export declare type TransitionConfigTarget<TContext, TEvent extends EventObject> = string | undefined | StateNode<TContext, any, TEvent>;
179
+ export declare type TransitionConfigOrTarget<TContext, TEvent extends EventObject> = SingleOrArray<TransitionConfigTarget<TContext, TEvent> | TransitionConfig<TContext, TEvent>>;
175
180
  declare type TransitionsConfigMap<TContext, TEvent extends EventObject> = {
176
- [K in TEvent['type'] | NullEvent['type'] | '*']?: SingleOrArray<TransitionConfigTargetShortcut<TContext, TEvent> | (TransitionConfig<TContext, K extends TEvent['type'] ? Extract<TEvent, {
181
+ [K in TEvent['type']]?: TransitionConfigOrTarget<TContext, TEvent extends {
177
182
  type: K;
178
- }> : EventObject> & {
179
- event?: undefined;
180
- })>;
183
+ } ? TEvent : never>;
184
+ } & {
185
+ ''?: TransitionConfigOrTarget<TContext, TEvent>;
186
+ } & {
187
+ '*'?: TransitionConfigOrTarget<TContext, TEvent>;
181
188
  };
182
189
  declare type TransitionsConfigArray<TContext, TEvent extends EventObject> = Array<{
183
- [K in TEvent['type'] | NullEvent['type'] | '*']: TransitionConfig<TContext, K extends TEvent['type'] ? Extract<TEvent, {
190
+ [K in TEvent['type']]: TransitionConfig<TContext, TEvent extends {
184
191
  type: K;
185
- }> : EventObject> & {
192
+ } ? TEvent : never> & {
186
193
  event: K;
187
194
  };
188
- }[TEvent['type'] | NullEvent['type'] | '*']>;
195
+ }[TEvent['type']] | (TransitionConfig<TContext, TEvent> & {
196
+ event: '';
197
+ }) | (TransitionConfig<TContext, TEvent> & {
198
+ event: '*';
199
+ })>;
189
200
  export declare type TransitionsConfig<TContext, TEvent extends EventObject> = TransitionsConfigMap<TContext, TEvent> | TransitionsConfigArray<TContext, TEvent>;
190
201
  export declare type InvokeConfig<TContext, TEvent extends EventObject> = {
191
202
  /**
@@ -196,7 +207,7 @@ export declare type InvokeConfig<TContext, TEvent extends EventObject> = {
196
207
  /**
197
208
  * The source of the machine to be invoked, or the machine itself.
198
209
  */
199
- src: string | StateMachine<any, any, any> | InvokeCreator<any, any>;
210
+ src: string | StateMachine<any, any, any> | InvokeCreator<TContext, TEvent, any>;
200
211
  /**
201
212
  * If `true`, events sent to the parent service will be forwarded to the invoked service.
202
213
  *
@@ -345,14 +356,15 @@ export interface StateNodeDefinition<TContext, TStateSchema extends StateSchema,
345
356
  id: string;
346
357
  version: string | undefined;
347
358
  key: string;
359
+ context: TContext;
348
360
  type: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';
349
361
  initial: StateNodeConfig<TContext, TStateSchema, TEvent>['initial'];
350
362
  history: boolean | 'shallow' | 'deep' | undefined;
351
363
  states: StatesDefinition<TContext, TStateSchema, TEvent>;
352
364
  on: TransitionDefinitionMap<TContext, TEvent>;
353
365
  transitions: Array<TransitionDefinition<TContext, TEvent>>;
354
- onEntry: Array<ActionObject<TContext, TEvent>>;
355
- onExit: Array<ActionObject<TContext, TEvent>>;
366
+ entry: Array<ActionObject<TContext, TEvent>>;
367
+ exit: Array<ActionObject<TContext, TEvent>>;
356
368
  activities: Array<ActivityDefinition<TContext, TEvent>>;
357
369
  meta: any;
358
370
  order: number;
@@ -478,7 +490,8 @@ export declare enum ActionTypes {
478
490
  ErrorPlatform = "error.platform",
479
491
  ErrorCustom = "xstate.error",
480
492
  Update = "xstate.update",
481
- Pure = "xstate.pure"
493
+ Pure = "xstate.pure",
494
+ Choose = "xstate.choose"
482
495
  }
483
496
  export interface RaiseAction<TEvent extends EventObject> {
484
497
  type: ActionTypes.Raise;
@@ -576,6 +589,10 @@ export interface PureAction<TContext, TEvent extends EventObject> extends Action
576
589
  type: ActionTypes.Pure;
577
590
  get: (context: TContext, event: TEvent) => SingleOrArray<ActionObject<TContext, TEvent>> | undefined;
578
591
  }
592
+ export interface ChooseAction<TContext, TEvent extends EventObject> extends ActionObject<TContext, TEvent> {
593
+ type: ActionTypes.Choose;
594
+ conds: Array<ChooseConditon<TContext, TEvent>>;
595
+ }
579
596
  export interface TransitionDefinition<TContext, TEvent extends EventObject> extends TransitionConfig<TContext, TEvent> {
580
597
  target: Array<StateNode<TContext, any, TEvent>> | undefined;
581
598
  source: StateNode<TContext, any, TEvent>;
package/es/types.js CHANGED
@@ -20,6 +20,7 @@ var ActionTypes;
20
20
  ActionTypes["ErrorCustom"] = "xstate.error";
21
21
  ActionTypes["Update"] = "xstate.update";
22
22
  ActionTypes["Pure"] = "xstate.pure";
23
+ ActionTypes["Choose"] = "xstate.choose";
23
24
  })(ActionTypes || (ActionTypes = {}));
24
25
 
25
26
  var SpecialTargets;
package/es/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Event, StateValue, ActionType, Action, EventObject, PropertyMapper, Mapper, EventType, HistoryValue, AssignAction, Condition, Guard, Subscribable, StateMachine, ConditionPredicate, SCXML, StateLike, EventData, TransitionConfig, TransitionConfigTargetShortcut, NullEvent, SingleOrArray } from './types';
1
+ import { Event, StateValue, ActionType, Action, EventObject, PropertyMapper, Mapper, EventType, HistoryValue, AssignAction, Condition, Subscribable, StateMachine, ConditionPredicate, SCXML, StateLike, EventData, TransitionConfig, TransitionConfigTarget, NullEvent, SingleOrArray, Guard } from './types';
2
2
  import { StateNode } from './StateNode';
3
3
  import { State } from '.';
4
4
  import { Actor } from './Actor';
@@ -59,9 +59,10 @@ export declare function isActor(value: any): value is Actor;
59
59
  export declare const uniqueId: () => string;
60
60
  export declare function toEventObject<TEvent extends EventObject>(event: Event<TEvent>, payload?: EventData): TEvent;
61
61
  export declare function toSCXMLEvent<TEvent extends EventObject>(event: Event<TEvent> | SCXML.Event<TEvent>, scxmlEvent?: Partial<SCXML.Event<TEvent>>): SCXML.Event<TEvent>;
62
- export declare function toTransitionConfigArray<TContext, TEvent extends EventObject>(event: TEvent['type'] | NullEvent['type'] | '*', configLike: SingleOrArray<TransitionConfig<TContext, TEvent> | TransitionConfigTargetShortcut<TContext, TEvent>>): Array<TransitionConfig<TContext, TEvent> & {
62
+ export declare function toTransitionConfigArray<TContext, TEvent extends EventObject>(event: TEvent['type'] | NullEvent['type'] | '*', configLike: SingleOrArray<TransitionConfig<TContext, TEvent> | TransitionConfigTarget<TContext, TEvent>>): Array<TransitionConfig<TContext, TEvent> & {
63
63
  event: TEvent['type'] | NullEvent['type'] | '*';
64
64
  }>;
65
65
  export declare function normalizeTarget<TContext, TEvent extends EventObject>(target: SingleOrArray<string | StateNode<TContext, any, TEvent>> | undefined): Array<string | StateNode<TContext, any, TEvent>> | undefined;
66
66
  export declare function reportUnhandledExceptionOnInvocation(originalError: any, currentError: any, id: string): void;
67
+ export declare function evaluateGuard<TContext, TEvent extends EventObject>(machine: StateNode<TContext, any, TEvent>, guard: Guard<TContext, TEvent>, context: TContext, _event: SCXML.Event<TEvent>, state: State<TContext, TEvent>): boolean;
67
68
  //# sourceMappingURL=utils.d.ts.map
package/es/utils.js CHANGED
@@ -482,9 +482,7 @@ function isObservable(value) {
482
482
  }
483
483
  }
484
484
 
485
- var symbolObservable =
486
- /*#__PURE__*/
487
- function () {
485
+ var symbolObservable = /*#__PURE__*/function () {
488
486
  return typeof Symbol === 'function' && Symbol.observable || '@@observable';
489
487
  }();
490
488
 
@@ -496,9 +494,7 @@ function isMachine(value) {
496
494
  }
497
495
  }
498
496
 
499
- var uniqueId =
500
- /*#__PURE__*/
501
- function () {
497
+ var uniqueId = /*#__PURE__*/function () {
502
498
  var currentId = 0;
503
499
  return function () {
504
500
  currentId++;
@@ -571,4 +567,25 @@ function reportUnhandledExceptionOnInvocation(originalError, currentError, id) {
571
567
  }
572
568
  }
573
569
 
574
- export { flatten, getEventType, isArray, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
570
+ function evaluateGuard(machine, guard, context, _event, state) {
571
+ var guards = machine.options.guards;
572
+ var guardMeta = {
573
+ state: state,
574
+ cond: guard,
575
+ _event: _event
576
+ }; // TODO: do not hardcode!
577
+
578
+ if (guard.type === DEFAULT_GUARD_TYPE) {
579
+ return guard.predicate(context, _event.data, guardMeta);
580
+ }
581
+
582
+ var condFn = guards[guard.type];
583
+
584
+ if (!condFn) {
585
+ throw new Error("Guard '" + guard.type + "' is not implemented on machine '" + machine.id + "'.");
586
+ }
587
+
588
+ return condFn(context, _event.data, guardMeta);
589
+ }
590
+
591
+ export { evaluateGuard, flatten, getEventType, isArray, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };
package/lib/State.js CHANGED
@@ -97,6 +97,7 @@ var State = /** @class */ (function () {
97
97
  * @param configuration
98
98
  */
99
99
  function State(config) {
100
+ var _this = this;
100
101
  this.actions = [];
101
102
  this.activities = constants_1.EMPTY_ACTIVITY_MAP;
102
103
  this.meta = {};
@@ -120,7 +121,7 @@ var State = /** @class */ (function () {
120
121
  this.done = !!config.done;
121
122
  Object.defineProperty(this, 'nextEvents', {
122
123
  get: function () {
123
- return stateUtils_1.nextEvents(config.configuration);
124
+ return stateUtils_1.nextEvents(_this.configuration);
124
125
  }
125
126
  });
126
127
  }
@@ -125,7 +125,7 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
125
125
  * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.
126
126
  * @param context Custom context (will override predefined context)
127
127
  */
128
- withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext | undefined): StateNode<TContext, TStateSchema, TEvent>;
128
+ withConfig(options: Partial<MachineOptions<TContext, TEvent>>, context?: TContext | undefined): StateNode<TContext, TStateSchema, TEvent, TTypestate>;
129
129
  /**
130
130
  * Clones this state machine with custom context.
131
131
  *
@@ -182,7 +182,6 @@ declare class StateNode<TContext = any, TStateSchema extends StateSchema = any,
182
182
  * this state node, it does not escape.
183
183
  */
184
184
  private escapes;
185
- private evaluateGuard;
186
185
  private getActions;
187
186
  /**
188
187
  * Determines the next state given the current `state` and sent `event`.
package/lib/StateNode.js CHANGED
@@ -191,9 +191,7 @@ var StateNode = /** @class */ (function () {
191
191
  // TODO: deprecate (entry)
192
192
  this.onEntry = utils_1.toArray(this.config.entry || this.config.onEntry).map(function (action) { return actions_1.toActionObject(action); });
193
193
  // TODO: deprecate (exit)
194
- this.onExit = utils_1.toArray(this.config.exit || this.config.onExit).map(function (action) {
195
- return actions_1.toActionObject(action);
196
- });
194
+ this.onExit = utils_1.toArray(this.config.exit || this.config.onExit).map(function (action) { return actions_1.toActionObject(action); });
197
195
  this.meta = this.config.meta;
198
196
  this.data =
199
197
  this.type === 'final'
@@ -263,14 +261,15 @@ var StateNode = /** @class */ (function () {
263
261
  id: this.id,
264
262
  key: this.key,
265
263
  version: this.version,
264
+ context: this.context,
266
265
  type: this.type,
267
266
  initial: this.initial,
268
267
  history: this.history,
269
268
  states: utils_1.mapValues(this.states, function (state) { return state.definition; }),
270
269
  on: this.on,
271
270
  transitions: this.transitions,
272
- onEntry: this.onEntry,
273
- onExit: this.onExit,
271
+ entry: this.onEntry,
272
+ exit: this.onExit,
274
273
  activities: this.activities || [],
275
274
  meta: this.meta,
276
275
  order: this.order || -1,
@@ -514,12 +513,11 @@ var StateNode = /** @class */ (function () {
514
513
  var guardPassed = false;
515
514
  try {
516
515
  guardPassed =
517
- !cond || this.evaluateGuard(cond, resolvedContext, _event, state);
516
+ !cond ||
517
+ utils_1.evaluateGuard(this.machine, cond, resolvedContext, _event, state);
518
518
  }
519
519
  catch (err) {
520
- throw new Error("Unable to evaluate guard '" + (cond.name ||
521
- cond
522
- .type) + "' in transition for event '" + eventName + "' in state node '" + this.id + "':\n" + err.message);
520
+ throw new Error("Unable to evaluate guard '" + (cond.name || cond.type) + "' in transition for event '" + eventName + "' in state node '" + this.id + "':\n" + err.message);
523
521
  }
524
522
  if (guardPassed && isInState) {
525
523
  if (candidate.target !== undefined) {
@@ -597,23 +595,6 @@ var StateNode = /** @class */ (function () {
597
595
  }
598
596
  return true;
599
597
  };
600
- StateNode.prototype.evaluateGuard = function (guard, context, _event, state) {
601
- var guards = this.machine.options.guards;
602
- var guardMeta = {
603
- state: state,
604
- cond: guard,
605
- _event: _event
606
- };
607
- // TODO: do not hardcode!
608
- if (guard.type === constants_1.DEFAULT_GUARD_TYPE) {
609
- return guard.predicate(context, _event.data, guardMeta);
610
- }
611
- var condFn = guards[guard.type];
612
- if (!condFn) {
613
- throw new Error("Guard '" + guard.type + "' is not implemented on machine '" + this.machine.id + "'.");
614
- }
615
- return condFn(context, _event.data, guardMeta);
616
- };
617
598
  StateNode.prototype.getActions = function (transition, currentContext, _event, prevState) {
618
599
  var e_4, _a, e_5, _b;
619
600
  var prevConfig = stateUtils_1.getConfiguration([], prevState ? this.getStateNodes(prevState.value) : [this]);
@@ -661,16 +642,17 @@ var StateNode = /** @class */ (function () {
661
642
  return events;
662
643
  }
663
644
  var parent = sn.parent;
645
+ if (!parent.parent) {
646
+ return events;
647
+ }
664
648
  events.push(actions_1.done(sn.id, sn.data), // TODO: deprecate - final states should not emit done events for their own state.
665
649
  actions_1.done(parent.id, sn.data ? utils_1.mapContext(sn.data, currentContext, _event) : undefined));
666
- if (parent.parent) {
667
- var grandparent = parent.parent;
668
- if (grandparent.type === 'parallel') {
669
- if (stateUtils_1.getChildren(grandparent).every(function (parentNode) {
670
- return stateUtils_1.isInFinalState(transition.configuration, parentNode);
671
- })) {
672
- events.push(actions_1.done(grandparent.id, grandparent.data));
673
- }
650
+ var grandparent = parent.parent;
651
+ if (grandparent.type === 'parallel') {
652
+ if (stateUtils_1.getChildren(grandparent).every(function (parentNode) {
653
+ return stateUtils_1.isInFinalState(transition.configuration, parentNode);
654
+ })) {
655
+ events.push(actions_1.done(grandparent.id, grandparent.data));
674
656
  }
675
657
  }
676
658
  return events;
@@ -747,7 +729,6 @@ var StateNode = /** @class */ (function () {
747
729
  };
748
730
  StateNode.prototype.resolveTransition = function (stateTransition, currentState, _event, context) {
749
731
  var e_6, _a;
750
- var _this = this;
751
732
  if (_event === void 0) { _event = actions_1.initEvent; }
752
733
  if (context === void 0) { context = this.machine.context; }
753
734
  var configuration = stateTransition.configuration;
@@ -786,34 +767,7 @@ var StateNode = /** @class */ (function () {
786
767
  }
787
768
  finally { if (e_6) throw e_6.error; }
788
769
  }
789
- var _b = __read(utils_1.partition(actions, function (action) {
790
- return action.type === actionTypes.assign;
791
- }), 2), assignActions = _b[0], otherActions = _b[1];
792
- var updatedContext = assignActions.length
793
- ? utils_1.updateContext(currentContext, _event, assignActions, currentState)
794
- : currentContext;
795
- var resolvedActions = utils_1.flatten(otherActions.map(function (actionObject) {
796
- switch (actionObject.type) {
797
- case actionTypes.raise:
798
- return actions_1.resolveRaise(actionObject);
799
- case actionTypes.send:
800
- var sendAction = actions_1.resolveSend(actionObject, updatedContext, _event, _this.machine.options.delays); // TODO: fix ActionTypes.Init
801
- if (!environment_1.IS_PRODUCTION) {
802
- // warn after resolving as we can create better contextual message here
803
- utils_1.warn(!utils_1.isString(actionObject.delay) ||
804
- typeof sendAction.delay === 'number',
805
- // tslint:disable-next-line:max-line-length
806
- "No delay reference for delay expression '" + actionObject.delay + "' was found on machine '" + _this.machine.id + "'");
807
- }
808
- return sendAction;
809
- case actionTypes.log:
810
- return actions_1.resolveLog(actionObject, updatedContext, _event);
811
- case actionTypes.pure:
812
- return (actionObject.get(updatedContext, _event.data) || []);
813
- default:
814
- return actions_1.toActionObject(actionObject, _this.options.actions);
815
- }
816
- }));
770
+ var _b = __read(actions_1.resolveActions(this, currentState, currentContext, _event, actions), 2), resolvedActions = _b[0], updatedContext = _b[1];
817
771
  var _c = __read(utils_1.partition(resolvedActions, function (action) {
818
772
  return action.type === actionTypes.raise ||
819
773
  (action.type === actionTypes.send &&
@@ -875,8 +829,8 @@ var StateNode = /** @class */ (function () {
875
829
  children: children,
876
830
  done: isDone
877
831
  });
878
- nextState.changed =
879
- _event.name === actionTypes.update || !!assignActions.length;
832
+ var didUpdateContext = currentContext !== updatedContext;
833
+ nextState.changed = _event.name === actionTypes.update || didUpdateContext;
880
834
  // Dispose of penultimate histories to prevent memory leaks
881
835
  var history = nextState.history;
882
836
  if (history) {
@@ -903,7 +857,7 @@ var StateNode = /** @class */ (function () {
903
857
  var changed = maybeNextState.changed ||
904
858
  (history
905
859
  ? !!maybeNextState.actions.length ||
906
- !!assignActions.length ||
860
+ didUpdateContext ||
907
861
  typeof history.value !== typeof maybeNextState.value ||
908
862
  !State_1.stateValuesEqual(maybeNextState.value, history.value)
909
863
  : undefined);
@@ -1326,7 +1280,13 @@ var StateNode = /** @class */ (function () {
1326
1280
  : true;
1327
1281
  var guards = this.machine.options.guards;
1328
1282
  var target = this.resolveTarget(normalizedTarget);
1329
- return __assign(__assign({}, transitionConfig), { actions: actions_1.toActionObjects(utils_1.toArray(transitionConfig.actions)), cond: utils_1.toGuard(transitionConfig.cond, guards), target: target, source: this, internal: internal, eventType: transitionConfig.event });
1283
+ var transition = __assign(__assign({}, transitionConfig), { actions: actions_1.toActionObjects(utils_1.toArray(transitionConfig.actions)), cond: utils_1.toGuard(transitionConfig.cond, guards), target: target, source: this, internal: internal, eventType: transitionConfig.event });
1284
+ Object.defineProperty(transition, 'toJSON', {
1285
+ value: function () { return (__assign(__assign({}, transition), { target: transition.target
1286
+ ? transition.target.map(function (t) { return "#" + t.id; })
1287
+ : undefined, source: "#{this.id}" })); }
1288
+ });
1289
+ return transition;
1330
1290
  };
1331
1291
  StateNode.prototype.formatTransitions = function () {
1332
1292
  var e_9, _a;
@@ -15,5 +15,6 @@ export declare const errorExecution = ActionTypes.ErrorExecution;
15
15
  export declare const errorPlatform = ActionTypes.ErrorPlatform;
16
16
  export declare const error = ActionTypes.ErrorCustom;
17
17
  export declare const update = ActionTypes.Update;
18
+ export declare const choose = ActionTypes.Choose;
18
19
  export declare const pure = ActionTypes.Pure;
19
20
  //# sourceMappingURL=actionTypes.d.ts.map
@@ -18,4 +18,5 @@ exports.errorExecution = types_1.ActionTypes.ErrorExecution;
18
18
  exports.errorPlatform = types_1.ActionTypes.ErrorPlatform;
19
19
  exports.error = types_1.ActionTypes.ErrorCustom;
20
20
  exports.update = types_1.ActionTypes.Update;
21
+ exports.choose = types_1.ActionTypes.Choose;
21
22
  exports.pure = types_1.ActionTypes.Pure;
package/lib/actions.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- import { Action, Event, EventObject, SingleOrArray, SendAction, SendActionOptions, CancelAction, ActionObject, ActionType, Assigner, PropertyAssigner, AssignAction, ActionFunction, ActionFunctionMap, ActivityActionObject, ActionTypes, ActivityDefinition, RaiseAction, RaiseActionObject, DoneEvent, ErrorPlatformEvent, DoneEventObject, SendExpr, SendActionObject, PureAction, LogExpr, LogAction, LogActionObject, DelayFunctionMap, SCXML, ExprWithMeta } from './types';
1
+ import { Action, Event, EventObject, SingleOrArray, SendAction, SendActionOptions, CancelAction, ActionObject, ActionType, Assigner, PropertyAssigner, AssignAction, ActionFunction, ActionFunctionMap, ActivityActionObject, ActionTypes, ActivityDefinition, RaiseAction, RaiseActionObject, DoneEvent, ErrorPlatformEvent, DoneEventObject, SendExpr, SendActionObject, PureAction, LogExpr, LogAction, LogActionObject, DelayFunctionMap, SCXML, ExprWithMeta, ChooseConditon, ChooseAction } from './types';
2
2
  import * as actionTypes from './actionTypes';
3
+ import { State } from './State';
4
+ import { StateNode } from './StateNode';
3
5
  export { actionTypes };
4
6
  export declare const initEvent: SCXML.Event<{
5
- type: ActionTypes.Init;
7
+ type: ActionTypes;
6
8
  }>;
7
9
  export declare function getActionFunction<TContext, TEvent extends EventObject>(actionType: ActionType, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | undefined;
8
10
  export declare function toActionObject<TContext, TEvent extends EventObject>(action: Action<TContext, TEvent>, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent>;
9
- export declare const toActionObjects: <TContext, TEvent extends EventObject>(action?: string | RaiseAction<import("./types").AnyEventObject> | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | AssignAction<Required<TContext>, TEvent> | SendAction<TContext, TEvent> | Action<TContext, TEvent>[] | undefined, actionFunctionMap?: Record<string, ActionFunction<TContext, TEvent> | ActionObject<TContext, TEvent>> | undefined) => ActionObject<TContext, TEvent>[];
11
+ export declare const toActionObjects: <TContext, TEvent extends EventObject>(action?: string | RaiseAction<import("./types").AnyEventObject> | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | AssignAction<Required<TContext>, TEvent> | SendAction<TContext, import("./types").AnyEventObject> | ChooseAction<TContext, TEvent> | Action<TContext, TEvent>[] | undefined, actionFunctionMap?: Record<string, ActionFunction<TContext, TEvent> | ActionObject<TContext, TEvent>> | undefined) => ActionObject<TContext, TEvent>[];
10
12
  export declare function toActivityDefinition<TContext, TEvent extends EventObject>(action: string | ActivityDefinition<TContext, TEvent>): ActivityDefinition<TContext, TEvent>;
11
13
  /**
12
14
  * Raises an event. This places the event in the internal event queue, so that
@@ -126,4 +128,6 @@ export declare function forwardTo<TContext, TEvent extends EventObject>(target:
126
128
  * @param options Options to pass into the send action creator.
127
129
  */
128
130
  export declare function escalate<TContext, TEvent extends EventObject, TErrorData = any>(errorData: TErrorData | ExprWithMeta<TContext, TEvent, TErrorData>, options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent>;
131
+ export declare function choose<TContext, TEvent extends EventObject>(conds: Array<ChooseConditon<TContext, TEvent>>): ChooseAction<TContext, TEvent>;
132
+ export declare function resolveActions<TContext, TEvent extends EventObject>(machine: StateNode<TContext, any, TEvent>, currentState: State<TContext, TEvent> | undefined, currentContext: TContext, _event: SCXML.Event<TEvent>, actions: Array<ActionObject<TContext, TEvent>>): [Array<ActionObject<TContext, TEvent>>, TContext];
129
133
  //# sourceMappingURL=actions.d.ts.map