-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
interpreter.ts
1239 lines (1120 loc) · 33.7 KB
/
interpreter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
StateMachine,
Event,
EventObject,
CancelAction,
DefaultContext,
ActionObject,
StateSchema,
ActivityActionObject,
SpecialTargets,
ActionTypes,
InvokeDefinition,
SendActionObject,
ServiceConfig,
InvokeCallback,
DisposeActivityFunction,
StateValue,
InterpreterOptions,
ActivityDefinition,
SingleOrArray,
Subscribable,
DoneEvent,
Unsubscribable,
MachineOptions,
ActionFunctionMap
} from './types';
import { State, bindActionToState } from './State';
import * as actionTypes from './actionTypes';
import { doneInvoke, error, getActionFunction } from './actions';
import { IS_PRODUCTION } from './environment';
import {
isPromiseLike,
mapContext,
warn,
keys,
isArray,
isFunction,
isString,
isObservable,
uniqueId,
isMachine,
toEventObject,
toSCXMLEvent
} from './utils';
import { Scheduler } from './scheduler';
import { Actor, isActor } from './Actor';
import { isInFinalState } from './stateUtils';
export type StateListener<TContext, TEvent extends EventObject> = (
state: State<TContext, TEvent>,
event: TEvent
) => void;
export type ContextListener<TContext = DefaultContext> = (
context: TContext,
prevContext: TContext | undefined
) => void;
export type EventListener<TEvent extends EventObject = EventObject> = (
event: TEvent
) => void;
export type Listener = () => void;
export interface Clock {
setTimeout(fn: (...args: any[]) => void, timeout: number): any;
clearTimeout(id: any): void;
}
interface SpawnOptions {
name?: string;
autoForward?: boolean;
sync?: boolean;
}
const DEFAULT_SPAWN_OPTIONS = { sync: false, autoForward: false };
/**
* Maintains a stack of the current service in scope.
* This is used to provide the correct service to spawn().
*
* @private
*/
const withServiceScope = (() => {
const serviceStack = [] as Array<Interpreter<any, any>>;
return <T, TService extends Interpreter<any, any>>(
service: TService | undefined,
fn: (service: TService) => T
) => {
service && serviceStack.push(service);
const result = fn(
service || (serviceStack[serviceStack.length - 1] as TService)
);
service && serviceStack.pop();
return result;
};
})();
export class Interpreter<
// tslint:disable-next-line:max-classes-per-file
TContext,
TStateSchema extends StateSchema = any,
TEvent extends EventObject = EventObject
>
implements
Subscribable<State<TContext, TEvent>>,
Actor<State<TContext, TEvent>, TEvent> {
/**
* The default interpreter options:
*
* - `clock` uses the global `setTimeout` and `clearTimeout` functions
* - `logger` uses the global `console.log()` method
*/
public static defaultOptions: InterpreterOptions = (global => ({
execute: true,
deferEvents: true,
clock: {
setTimeout: (fn, ms) => {
return global.setTimeout.call(null, fn, ms);
},
clearTimeout: id => {
return global.clearTimeout.call(null, id);
}
},
logger: global.console.log.bind(console),
devTools: false
}))(typeof window === 'undefined' ? global : window);
/**
* The current state of the interpreted machine.
*/
private _state?: State<TContext, TEvent>;
/**
* The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
*/
public clock: Clock;
public options: Readonly<InterpreterOptions>;
private scheduler: Scheduler = new Scheduler();
private delayedEventsMap: Record<string, number> = {};
private listeners: Set<StateListener<TContext, TEvent>> = new Set();
private contextListeners: Set<ContextListener<TContext>> = new Set();
private stopListeners: Set<Listener> = new Set();
private doneListeners: Set<EventListener> = new Set();
private eventListeners: Set<EventListener> = new Set();
private sendListeners: Set<EventListener> = new Set();
private logger: (...args: any[]) => void;
/**
* Whether the service is started.
*/
public initialized = false;
/**
* The initial state of the machine.
*/
private _initialState?: State<TContext, TEvent>;
// Actor
public parent?: Interpreter<any>;
public id: string;
public children: Map<string | number, Actor> = new Map();
private forwardTo: Set<string> = new Set();
// Dev Tools
private devTools?: any;
/**
* Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.
*
* @param machine The machine to be interpreted
* @param options Interpreter options
*/
constructor(
public machine: StateMachine<TContext, TStateSchema, TEvent>,
options: Partial<InterpreterOptions> = Interpreter.defaultOptions
) {
const resolvedOptions: InterpreterOptions = {
...Interpreter.defaultOptions,
...options
};
const { clock, logger, parent, id } = resolvedOptions;
const resolvedId = id !== undefined ? id : machine.id;
this.id = resolvedId;
this.logger = logger;
this.clock = clock;
this.parent = parent;
this.options = resolvedOptions;
this.scheduler = new Scheduler({
deferEvents: this.options.deferEvents
});
}
public get initialState(): State<TContext, TEvent> {
if (!IS_PRODUCTION) {
warn(
this.initialized,
// tslint:disable-next-line:max-line-length
`Attempted to read initial state from uninitialized service '${this.id}'. Make sure the service is started first.`
);
}
return (
this._initialState ||
withServiceScope(this, () => this.machine.initialState)
);
}
public get state(): State<TContext, TEvent> {
if (!IS_PRODUCTION) {
warn(
this.initialized,
`Attempted to read state from uninitialized service '${this.id}'. Make sure the service is started first.`
);
}
return this._state!;
}
public static interpret = interpret;
/**
* Executes the actions of the given state, with that state's `context` and `event`.
*
* @param state The state whose actions will be executed
* @param actionsConfig The action implementations to use
*/
public execute(
state: State<TContext, TEvent>,
actionsConfig?: MachineOptions<TContext, TEvent>['actions']
): void {
for (const action of state.actions) {
this.exec(action, state.context, state.event, actionsConfig);
}
}
private update(state: State<TContext, TEvent>, event: TEvent): void {
// Update state
this._state = state;
// Execute actions
if (this.options.execute) {
this.execute(this.state);
}
// Dev tools
if (this.devTools) {
this.devTools.send(event, state);
}
// Execute listeners
if (state.event) {
for (const listener of this.eventListeners) {
listener(state.event);
}
}
for (const listener of this.listeners) {
listener(state, state.event);
}
for (const contextListener of this.contextListeners) {
contextListener(
this.state.context,
this.state.history ? this.state.history.context : undefined
);
}
const isDone = isInFinalState(state.configuration || [], this.machine);
if (this.state.configuration && isDone) {
// get final child state node
const finalChildStateNode = state.configuration!.find(
sn => sn.type === 'final' && sn.parent === this.machine
);
const doneData =
finalChildStateNode && finalChildStateNode.data
? mapContext(
finalChildStateNode.data,
state.context,
toEventObject(event)
)
: undefined;
for (const listener of this.doneListeners) {
listener(doneInvoke(this.id, doneData));
}
this.stop();
}
}
/*
* Adds a listener that is notified whenever a state transition happens. The listener is called with
* the next state and the event object that caused the state transition.
*
* @param listener The state listener
*/
public onTransition(
listener: StateListener<TContext, TEvent>
): Interpreter<TContext, TStateSchema, TEvent> {
this.listeners.add(listener);
return this;
}
public subscribe(
nextListener?: (state: State<TContext, TEvent>) => void,
// @ts-ignore
errorListener?: (error: any) => void,
completeListener?: () => void
): Unsubscribable {
if (nextListener) {
this.onTransition(nextListener);
}
if (completeListener) {
this.onDone(completeListener);
}
return {
unsubscribe: () => {
nextListener && this.listeners.delete(nextListener);
completeListener && this.doneListeners.delete(completeListener);
}
};
}
/**
* Adds an event listener that is notified whenever an event is sent to the running interpreter.
* @param listener The event listener
*/
public onEvent(
listener: EventListener
): Interpreter<TContext, TStateSchema, TEvent> {
this.eventListeners.add(listener);
return this;
}
/**
* Adds an event listener that is notified whenever a `send` event occurs.
* @param listener The event listener
*/
public onSend(
listener: EventListener
): Interpreter<TContext, TStateSchema, TEvent> {
this.sendListeners.add(listener);
return this;
}
/**
* Adds a context listener that is notified whenever the state context changes.
* @param listener The context listener
*/
public onChange(
listener: ContextListener<TContext>
): Interpreter<TContext, TStateSchema, TEvent> {
this.contextListeners.add(listener);
return this;
}
/**
* Adds a listener that is notified when the machine is stopped.
* @param listener The listener
*/
public onStop(
listener: Listener
): Interpreter<TContext, TStateSchema, TEvent> {
this.stopListeners.add(listener);
return this;
}
/**
* Adds a state listener that is notified when the statechart has reached its final state.
* @param listener The state listener
*/
public onDone(
listener: EventListener<DoneEvent>
): Interpreter<TContext, TStateSchema, TEvent> {
this.doneListeners.add(listener);
return this;
}
/**
* Removes a listener.
* @param listener The listener to remove
*/
public off(
listener: (...args: any[]) => void
): Interpreter<TContext, TStateSchema, TEvent> {
this.listeners.delete(listener);
this.eventListeners.delete(listener);
this.sendListeners.delete(listener);
this.stopListeners.delete(listener);
this.doneListeners.delete(listener);
this.contextListeners.delete(listener);
return this;
}
/**
* Alias for Interpreter.prototype.start
*/
public init = this.start;
/**
* Starts the interpreter from the given state, or the initial state.
* @param initialState The state to start the statechart from
*/
public start(
initialState?: State<TContext, TEvent> | StateValue
): Interpreter<TContext, TStateSchema, TEvent> {
if (this.initialized) {
// Do not restart the service if it is already started
return this;
}
this.initialized = true;
const resolvedState = withServiceScope(this, () => {
return initialState === undefined
? this.machine.initialState
: initialState instanceof State
? this.machine.resolveState(initialState)
: this.machine.resolveState(State.from(initialState));
});
if (this.options.devTools) {
this.attachDev();
}
this.scheduler.initialize(() => {
this.update(resolvedState, { type: actionTypes.init } as TEvent);
});
return this;
}
/**
* Stops the interpreter and unsubscribe all listeners.
*
* This will also notify the `onStop` listeners.
*/
public stop(): Interpreter<TContext, TStateSchema, TEvent> {
for (const listener of this.listeners) {
this.listeners.delete(listener);
}
for (const listener of this.stopListeners) {
// call listener, then remove
listener();
this.stopListeners.delete(listener);
}
for (const listener of this.contextListeners) {
this.contextListeners.delete(listener);
}
for (const listener of this.doneListeners) {
this.doneListeners.delete(listener);
}
// Stop all children
this.children.forEach(child => {
if (isFunction(child.stop)) {
child.stop();
}
});
// Cancel all delayed events
for (const key of keys(this.delayedEventsMap)) {
this.clock.clearTimeout(this.delayedEventsMap[key]);
}
this.initialized = false;
return this;
}
/**
* Sends an event to the running interpreter to trigger a transition.
*
* An array of events (batched) can be sent as well, which will send all
* batched events to the running interpreter. The listeners will be
* notified only **once** when all events are processed.
*
* @param event The event(s) to send
*/
public send = (
event: SingleOrArray<TEvent | TEvent['type']>,
payload?: Record<string, any> & { type?: never }
): State<TContext, TEvent> => {
if (isArray(event)) {
this.batch(event);
return this.state;
}
const eventObject = toEventObject(event, payload);
if (!this.initialized && this.options.deferEvents) {
// tslint:disable-next-line:no-console
if (!IS_PRODUCTION) {
warn(
false,
`Event "${eventObject.type}" was sent to uninitialized service "${
this.machine.id
}" and is deferred. Make sure .start() is called for this service.\nEvent: ${JSON.stringify(
event
)}`
);
}
} else if (!this.initialized) {
throw new Error(
`Event "${eventObject.type}" was sent to uninitialized service "${
this.machine.id
// tslint:disable-next-line:max-line-length
}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\nEvent: ${JSON.stringify(
eventObject
)}`
);
}
this.scheduler.schedule(() => {
const nextState = this.nextState(eventObject);
this.update(nextState, eventObject);
// Forward copy of event to child interpreters
this.forward(eventObject);
});
return this._state!; // TODO: deprecate (should return void)
// tslint:disable-next-line:semicolon
};
private batch(events: Array<TEvent | TEvent['type']>): void {
if (!this.initialized && this.options.deferEvents) {
// tslint:disable-next-line:no-console
if (!IS_PRODUCTION) {
warn(
false,
`${events.length} event(s) were sent to uninitialized service "${
this.machine.id
}" and are deferred. Make sure .start() is called for this service.\nEvent: ${JSON.stringify(
event
)}`
);
}
} else if (!this.initialized) {
throw new Error(
// tslint:disable-next-line:max-line-length
`${events.length} event(s) were sent to uninitialized service "${this.machine.id}". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.`
);
}
this.scheduler.schedule(() => {
let nextState = this.state;
for (const event of events) {
const { changed } = nextState;
const eventObject = toEventObject(event);
const actions = nextState.actions.map(a =>
bindActionToState(a, nextState)
) as Array<ActionObject<TContext, TEvent>>;
nextState = this.machine.transition(nextState, eventObject);
nextState.actions.unshift(...actions);
nextState.changed = nextState.changed || !!changed;
this.forward(eventObject);
}
this.update(nextState, toEventObject(events[events.length - 1]));
});
}
/**
* Returns a send function bound to this interpreter instance.
*
* @param event The event to be sent by the sender.
*/
public sender(event: Event<TEvent>): () => State<TContext, TEvent> {
return this.send.bind(this, event);
}
public sendTo = (event: TEvent, to: string | number | Actor) => {
const isParent =
this.parent && (to === SpecialTargets.Parent || this.parent.id === to);
const target = isParent
? this.parent
: isActor(to)
? to
: this.children.get(to);
if (!target) {
if (!isParent) {
throw new Error(
`Unable to send event to child '${to}' from service '${this.id}'.`
);
}
// tslint:disable-next-line:no-console
if (!IS_PRODUCTION) {
warn(
false,
`Service '${this.id}' has no parent: unable to send event ${event.type}`
);
}
return;
}
// add SCXML event
const eventWithSCXML = {
...event,
__scxml: toSCXMLEvent(event, { origin: this.id, type: 'external' })
};
target.send(eventWithSCXML);
};
/**
* Returns the next state given the interpreter's current state and the event.
*
* This is a pure method that does _not_ update the interpreter's state.
*
* @param event The event to determine the next state
*/
public nextState(event: TEvent | TEvent['type']): State<TContext, TEvent> {
const eventObject = toEventObject(event);
if (
eventObject.type.indexOf(actionTypes.errorPlatform) === 0 &&
!this.state.nextEvents.some(
nextEvent => nextEvent.indexOf(actionTypes.errorPlatform) === 0
)
) {
throw (eventObject as TEvent).data;
}
const nextState = withServiceScope(this, () => {
return this.machine.transition(
this.state,
eventObject,
this.state.context
);
});
return nextState;
}
private forward(event: TEvent): void {
for (const id of this.forwardTo) {
const child = this.children.get(id);
if (!child) {
throw new Error(
`Unable to forward event '${event}' from interpreter '${this.id}' to nonexistant child '${id}'.`
);
}
child.send(event);
}
}
private defer(sendAction: SendActionObject<TContext, TEvent>): void {
let { delay } = sendAction;
if (isString(delay)) {
if (
!this.machine.options.delays ||
this.machine.options.delays[delay] === undefined
) {
// tslint:disable-next-line:no-console
if (!IS_PRODUCTION) {
warn(
false,
// tslint:disable-next-line:max-line-length
`No delay reference for delay expression '${delay}' was found on machine '${this.machine.id}' on service '${this.id}'.`
);
}
// Do not send anything
return;
} else {
const delayExpr = this.machine.options.delays[delay];
delay =
typeof delayExpr === 'number'
? delayExpr
: delayExpr(this.state.context, this.state.event);
}
}
this.delayedEventsMap[sendAction.id] = this.clock.setTimeout(() => {
if (sendAction.to) {
this.sendTo(sendAction.event, sendAction.to);
} else {
this.send(sendAction.event);
}
}, (delay as number) || 0);
}
private cancel(sendId: string | number): void {
this.clock.clearTimeout(this.delayedEventsMap[sendId]);
delete this.delayedEventsMap[sendId];
}
private exec(
action: ActionObject<TContext, TEvent>,
context: TContext,
event: TEvent,
actionFunctionMap?: ActionFunctionMap<TContext, TEvent>
): void {
const actionOrExec =
getActionFunction(action.type, actionFunctionMap) || action.exec;
const exec = isFunction(actionOrExec)
? actionOrExec
: actionOrExec
? actionOrExec.exec
: action.exec;
if (exec) {
// @ts-ignore (TODO: fix for TypeDoc)
return exec(context, event, { action, state: this.state });
}
switch (action.type) {
case actionTypes.send:
const sendAction = action as SendActionObject<TContext, TEvent>;
if (sendAction.delay) {
this.defer(sendAction);
return;
} else {
if (sendAction.to) {
this.sendTo(sendAction.event, sendAction.to);
} else {
this.send(sendAction.event);
}
}
break;
case actionTypes.cancel:
this.cancel((action as CancelAction).sendId);
break;
case actionTypes.start: {
const activity = (action as ActivityActionObject<TContext, TEvent>)
.activity as InvokeDefinition<TContext, TEvent>;
// If the activity will be stopped right after it's started
// (such as in transient states)
// don't bother starting the activity.
if (!this.state.activities[activity.type]) {
break;
}
// Invoked services
if (activity.type === ActionTypes.Invoke) {
const serviceCreator: ServiceConfig<TContext> | undefined = this
.machine.options.services
? this.machine.options.services[activity.src]
: undefined;
const { id, data } = activity;
if (!IS_PRODUCTION) {
warn(
!('forward' in activity),
// tslint:disable-next-line:max-line-length
`\`forward\` property is deprecated (found in invocation of '${activity.src}' in in machine '${this.machine.id}'). ` +
`Please use \`autoForward\` instead.`
);
}
const autoForward =
'autoForward' in activity
? activity.autoForward
: !!activity.forward;
if (!serviceCreator) {
// tslint:disable-next-line:no-console
if (!IS_PRODUCTION) {
warn(
false,
`No service found for invocation '${activity.src}' in machine '${this.machine.id}'.`
);
}
return;
}
const source = isFunction(serviceCreator)
? serviceCreator(context, event)
: serviceCreator;
if (isPromiseLike(source)) {
this.spawnPromise(Promise.resolve(source), id);
} else if (isFunction(source)) {
this.spawnCallback(source, id);
} else if (isObservable<TEvent>(source)) {
this.spawnObservable(source, id);
} else if (isMachine(source)) {
// TODO: try/catch here
this.spawnMachine(
data
? source.withContext(mapContext(data, context, event as TEvent))
: source,
{
id,
autoForward
}
);
} else {
// service is string
}
} else {
this.spawnActivity(activity);
}
break;
}
case actionTypes.stop: {
this.stopChild(action.activity.id);
break;
}
case actionTypes.log:
const expr = action.expr ? action.expr(context, event) : undefined;
if (action.label) {
this.logger(action.label, expr);
} else {
this.logger(expr);
}
break;
default:
if (!IS_PRODUCTION) {
warn(
false,
`No implementation found for action type '${action.type}'`
);
}
break;
}
return undefined;
}
private stopChild(childId: string): void {
const child = this.children.get(childId);
if (!child) {
return;
}
this.children.delete(childId);
this.forwardTo.delete(childId);
if (isFunction(child.stop)) {
child.stop();
}
}
public spawn<TChildContext>(
entity: Spawnable<TChildContext>,
name: string,
options?: SpawnOptions
): Actor {
if (isPromiseLike(entity)) {
return this.spawnPromise(Promise.resolve(entity), name);
} else if (isFunction(entity)) {
return this.spawnCallback(entity, name);
} else if (isObservable<TEvent>(entity)) {
return this.spawnObservable(entity, name);
} else if (isMachine(entity)) {
return this.spawnMachine(entity, { ...options, id: name });
} else {
throw new Error(
`Unable to spawn entity "${name}" of type "${typeof entity}".`
);
}
}
public spawnMachine<
TChildContext,
TChildStateSchema,
TChildEvents extends EventObject
>(
machine: StateMachine<TChildContext, TChildStateSchema, TChildEvents>,
options: { id?: string; autoForward?: boolean; sync?: boolean } = {}
): Actor<State<TChildContext, TChildEvents>> {
const childService = new Interpreter(machine, {
...this.options, // inherit options from this interpreter
parent: this,
id: options.id || machine.id
});
const resolvedOptions = {
...DEFAULT_SPAWN_OPTIONS,
...options
};
if (resolvedOptions.sync) {
childService.onTransition(state => {
this.send(actionTypes.update as any, { state, id: childService.id });
});
}
childService
.onDone(doneEvent => {
this.send(doneEvent as any);
})
.start();
const actor = childService as Actor<State<TChildContext, TChildEvents>>;
// const actor = {
// id: childService.id,
// send: childService.send,
// state: childService.state,
// subscribe: childService.subscribe,
// toJSON() {
// return { id: childService.id };
// }
// } as Actor<State<TChildContext, TChildEvents>>;
this.children.set(childService.id, actor);
if (resolvedOptions.autoForward) {
this.forwardTo.add(childService.id);
}
return actor;
}
private spawnPromise(promise: Promise<any>, id: string): Actor {
let canceled = false;
promise.then(
response => {
if (!canceled) {
this.send(doneInvoke(id, response) as any);
}
},
errorData => {
if (!canceled) {
const errorEvent = error(id, errorData);
try {
// Send "error.execution" to this (parent).
this.send(errorEvent as any);
} catch (error) {
this.reportUnhandledExceptionOnInvocation(errorData, error, id);
if (this.devTools) {
this.devTools.send(errorEvent, this.state);
}
if (this.machine.strict) {
// it would be better to always stop the state machine if unhandled
// exception/promise rejection happens but because we don't want to
// break existing code so enforce it on strict mode only especially so
// because documentation says that onError is optional
this.stop();
}
}
}
}
);
const actor = {
id,
send: () => void 0,
subscribe: (next, handleError, complete) => {
let unsubscribed = false;
promise.then(
response => {
if (unsubscribed) {
return;
}
next && next(response);
if (unsubscribed) {
return;
}
complete && complete();
},
err => {
if (unsubscribed) {
return;
}
handleError(err);
}
);
return {
unsubscribe: () => (unsubscribed = true)
};
},
stop: () => {
canceled = true;
},
toJSON() {
return { id };
}
};
this.children.set(id, actor);
return actor;
}
private spawnCallback(callback: InvokeCallback, id: string): Actor {
let canceled = false;
const receive = (e: TEvent) => {
if (canceled) {
return;
}
this.send(e);
};
const listeners = new Set<(e: EventObject) => void>();
let callbackStop;
try {
callbackStop = callback(receive, newListener => {
listeners.add(newListener);
});
} catch (err) {
this.send(error(id, err) as any);
}
if (isPromiseLike(callbackStop)) {
// it turned out to be an async function, can't reliably check this before calling `callback`
// because transpiled async functions are not recognizable
return this.spawnPromise(callbackStop as Promise<any>, id);