deno.land / x / xstate@xstate@4.33.6 / src / actions.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
import { Action, Event, EventObject, SingleOrArray, SendAction, SendActionOptions, CancelAction, ActionObject, ActionType, Assigner, PropertyAssigner, AssignAction, ActionFunction, ActionFunctionMap, ActivityActionObject, ActionTypes, ActivityDefinition, SpecialTargets, RaiseAction, RaiseActionObject, DoneEvent, ErrorPlatformEvent, DoneEventObject, SendExpr, SendActionObject, PureAction, LogExpr, LogAction, LogActionObject, DelayFunctionMap, SCXML, ExprWithMeta, ChooseCondition, ChooseAction, AnyEventObject, Expr, StopAction, StopActionObject, Cast, EventFrom, AnyActorRef, PredictableActionArgumentsExec} from './types';import * as actionTypes from './actionTypes';import { getEventType, isFunction, isString, toEventObject, toSCXMLEvent, flatten, updateContext, warn, toGuard, evaluateGuard, toArray, isArray} from './utils';import { State } from './State';import { StateNode } from './StateNode';import { IS_PRODUCTION } from './environment';
export { actionTypes };
export const initEvent = toSCXMLEvent({ type: actionTypes.init });
export function getActionFunction<TContext, TEvent extends EventObject>( actionType: ActionType, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | undefined { return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined;}
export function toActionObject<TContext, TEvent extends EventObject>( action: Action<TContext, TEvent>, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): ActionObject<TContext, TEvent> { let actionObject: ActionObject<TContext, TEvent>;
if (isString(action) || typeof action === 'number') { const exec = getActionFunction(action, actionFunctionMap); if (isFunction(exec)) { actionObject = { type: action, exec }; } else if (exec) { actionObject = exec; } else { actionObject = { type: action, exec: undefined }; } } else if (isFunction(action)) { actionObject = { // Convert action to string if unnamed type: action.name || action.toString(), exec: action }; } else { const exec = getActionFunction(action.type, actionFunctionMap); if (isFunction(exec)) { actionObject = { ...action, exec }; } else if (exec) { const actionType = exec.type || action.type;
actionObject = { ...exec, ...action, type: actionType } as ActionObject<TContext, TEvent>; } else { actionObject = action as ActionObject<TContext, TEvent>; } } return actionObject;}
export const toActionObjects = <TContext, TEvent extends EventObject>( action?: SingleOrArray<Action<TContext, TEvent>> | undefined, actionFunctionMap?: ActionFunctionMap<TContext, TEvent>): Array<ActionObject<TContext, TEvent>> => { if (!action) { return []; }
const actions = isArray(action) ? action : [action];
return actions.map((subAction) => toActionObject(subAction, actionFunctionMap) );};
export function toActivityDefinition<TContext, TEvent extends EventObject>( action: string | ActivityDefinition<TContext, TEvent>): ActivityDefinition<TContext, TEvent> { const actionObject = toActionObject(action);
return { id: isString(action) ? action : actionObject.id, ...actionObject, type: actionObject.type };}
/** * Raises an event. This places the event in the internal event queue, so that * the event is immediately consumed by the machine in the current step. * * @param eventType The event to raise. */export function raise<TContext, TEvent extends EventObject>( event: Event<TEvent>): RaiseAction<TEvent> | SendAction<TContext, AnyEventObject, TEvent> { if (!isString(event)) { return send(event, { to: SpecialTargets.Internal }); } return { type: actionTypes.raise, event };}
export function resolveRaise<TEvent extends EventObject>( action: RaiseAction<TEvent>): RaiseActionObject<TEvent> { return { type: actionTypes.raise, _event: toSCXMLEvent(action.event) };}
/** * Sends an event. This returns an action that will be read by an interpreter to * send the event in the next step, after the current step is finished executing. * * @param event The event to send. * @param options Options to pass into the send event: * - `id` - The unique send event identifier (used with `cancel()`). * - `delay` - The number of milliseconds to delay the sending of the event. * - `to` - The target of this event (by default, the machine the event was sent from). */export function send< TContext, TEvent extends EventObject, TSentEvent extends EventObject = AnyEventObject>( event: Event<TSentEvent> | SendExpr<TContext, TEvent, TSentEvent>, options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent, TSentEvent> { return { to: options ? options.to : undefined, type: actionTypes.send, event: isFunction(event) ? event : toEventObject<TSentEvent>(event), delay: options ? options.delay : undefined, id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : (getEventType<TSentEvent>(event) as string) };}
export function resolveSend< TContext, TEvent extends EventObject, TSentEvent extends EventObject>( action: SendAction<TContext, TEvent, TSentEvent>, ctx: TContext, _event: SCXML.Event<TEvent>, delaysMap?: DelayFunctionMap<TContext, TEvent>): SendActionObject<TContext, TEvent, TSentEvent> { const meta = { _event };
// TODO: helper function for resolving Expr const resolvedEvent = toSCXMLEvent( isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event );
let resolvedDelay: number | undefined; if (isString(action.delay)) { const configDelay = delaysMap && delaysMap[action.delay]; resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay; } else { resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay; }
const resolvedTarget = isFunction(action.to) ? action.to(ctx, _event.data, meta) : action.to;
return { ...action, to: resolvedTarget, _event: resolvedEvent, event: resolvedEvent.data, delay: resolvedDelay };}
/** * Sends an event to this machine's parent. * * @param event The event to send to the parent machine. * @param options Options to pass into the send event. */export function sendParent< TContext, TEvent extends EventObject, TSentEvent extends EventObject = AnyEventObject>( event: Event<TSentEvent> | SendExpr<TContext, TEvent, TSentEvent>, options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent, TSentEvent> { return send<TContext, TEvent, TSentEvent>(event, { ...options, to: SpecialTargets.Parent });}
type InferEvent<E extends EventObject> = { [T in E['type']]: { type: T } & Extract<E, { type: T }>;}[E['type']];
/** * Sends an event to an actor. * * @param actor The `ActorRef` to send the event to. * @param event The event to send, or an expression that evaluates to the event to send * @param options Send action options * @returns An XState send action object */export function sendTo< TContext, TEvent extends EventObject, TActor extends AnyActorRef>( actor: string | TActor | ((ctx: TContext) => TActor), event: | EventFrom<TActor> | SendExpr< TContext, TEvent, InferEvent<Cast<EventFrom<TActor>, EventObject>> >, options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent, any> { return send<TContext, TEvent, any>(event, { ...options, to: actor });}
/** * Sends an update event to this machine's parent. */export function sendUpdate<TContext, TEvent extends EventObject>(): SendAction< TContext, TEvent, { type: ActionTypes.Update }> { return sendParent<TContext, TEvent, { type: ActionTypes.Update }>( actionTypes.update );}
/** * Sends an event back to the sender of the original event. * * @param event The event to send back to the sender * @param options Options to pass into the send event */export function respond< TContext, TEvent extends EventObject, TSentEvent extends EventObject = AnyEventObject>( event: Event<TEvent> | SendExpr<TContext, TEvent, TSentEvent>, options?: SendActionOptions<TContext, TEvent>) { return send<TContext, TEvent>(event, { ...options, to: (_, __, { _event }) => { return _event.origin!; // TODO: handle when _event.origin is undefined } });}
const defaultLogExpr = <TContext, TEvent extends EventObject>( context: TContext, event: TEvent) => ({ context, event});
/** * * @param expr The expression function to evaluate which will be logged. * Takes in 2 arguments: * - `ctx` - the current state context * - `event` - the event that caused this action to be executed. * @param label The label to give to the logged expression. */export function log<TContext, TEvent extends EventObject>( expr: string | LogExpr<TContext, TEvent> = defaultLogExpr, label?: string): LogAction<TContext, TEvent> { return { type: actionTypes.log, label, expr };}
export const resolveLog = <TContext, TEvent extends EventObject>( action: LogAction<TContext, TEvent>, ctx: TContext, _event: SCXML.Event<TEvent>): LogActionObject<TContext, TEvent> => ({ // TODO: remove .expr from resulting object ...action, value: isString(action.expr) ? action.expr : action.expr(ctx, _event.data, { _event })});
/** * Cancels an in-flight `send(...)` action. A canceled sent action will not * be executed, nor will its event be sent, unless it has already been sent * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`). * * @param sendId The `id` of the `send(...)` action to cancel. */export const cancel = (sendId: string | number): CancelAction => { return { type: actionTypes.cancel, sendId };};
/** * Starts an activity. * * @param activity The activity to start. */export function start<TContext, TEvent extends EventObject>( activity: string | ActivityDefinition<TContext, TEvent>): ActivityActionObject<TContext, TEvent> { const activityDef = toActivityDefinition(activity);
return { type: ActionTypes.Start, activity: activityDef, exec: undefined };}
/** * Stops an activity. * * @param actorRef The activity to stop. */export function stop<TContext, TEvent extends EventObject>( actorRef: | string | ActivityDefinition<TContext, TEvent> | Expr<TContext, TEvent, string | { id: string }>): StopAction<TContext, TEvent> { const activity = isFunction(actorRef) ? actorRef : toActivityDefinition(actorRef);
return { type: ActionTypes.Stop, activity, exec: undefined };}
export function resolveStop<TContext, TEvent extends EventObject>( action: StopAction<TContext, TEvent>, context: TContext, _event: SCXML.Event<TEvent>): StopActionObject { const actorRefOrString = isFunction(action.activity) ? action.activity(context, _event.data) : action.activity; const resolvedActorRef = typeof actorRefOrString === 'string' ? { id: actorRefOrString } : actorRefOrString;
const actionObject = { type: ActionTypes.Stop as const, activity: resolvedActorRef };
return actionObject;}
/** * Updates the current context of the machine. * * @param assignment An object that represents the partial context to update. */export const assign = <TContext, TEvent extends EventObject = EventObject>( assignment: Assigner<TContext, TEvent> | PropertyAssigner<TContext, TEvent>): AssignAction<TContext, TEvent> => { return { type: actionTypes.assign, assignment };};
export function isActionObject<TContext, TEvent extends EventObject>( action: Action<TContext, TEvent>): action is ActionObject<TContext, TEvent> { return typeof action === 'object' && 'type' in action;}
/** * Returns an event type that represents an implicit event that * is sent after the specified `delay`. * * @param delayRef The delay in milliseconds * @param id The state node ID where this event is handled */export function after(delayRef: number | string, id?: string) { const idSuffix = id ? `#${id}` : ''; return `${ActionTypes.After}(${delayRef})${idSuffix}`;}
/** * Returns an event that represents that a final state node * has been reached in the parent state node. * * @param id The final state node's parent state node `id` * @param data The data to pass into the event */export function done(id: string, data?: any): DoneEventObject { const type = `${ActionTypes.DoneState}.${id}`; const eventObject = { type, data };
eventObject.toString = () => type;
return eventObject as DoneEvent;}
/** * Returns an event that represents that an invoked service has terminated. * * An invoked service is terminated when it has reached a top-level final state node, * but not when it is canceled. * * @param id The final state node ID * @param data The data to pass into the event */export function doneInvoke(id: string, data?: any): DoneEvent { const type = `${ActionTypes.DoneInvoke}.${id}`; const eventObject = { type, data };
eventObject.toString = () => type;
return eventObject as DoneEvent;}
export function error(id: string, data?: any): ErrorPlatformEvent & string { const type = `${ActionTypes.ErrorPlatform}.${id}`; const eventObject = { type, data };
eventObject.toString = () => type;
return eventObject as ErrorPlatformEvent & string;}
export function pure<TContext, TEvent extends EventObject>( getActions: ( context: TContext, event: TEvent ) => SingleOrArray<ActionObject<TContext, TEvent>> | undefined): PureAction<TContext, TEvent> { return { type: ActionTypes.Pure, get: getActions };}
/** * Forwards (sends) an event to a specified service. * * @param target The target service to forward the event to. * @param options Options to pass into the send action creator. */export function forwardTo<TContext, TEvent extends EventObject>( target: Required<SendActionOptions<TContext, TEvent>>['to'], options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent, AnyEventObject> { if (!IS_PRODUCTION && (!target || typeof target === 'function')) { const originalTarget = target; target = (...args) => { const resolvedTarget = typeof originalTarget === 'function' ? originalTarget(...args) : originalTarget; if (!resolvedTarget) { throw new Error( `Attempted to forward event to undefined actor. This risks an infinite loop in the sender.` ); } return resolvedTarget; }; } return send<TContext, TEvent>((_, event) => event, { ...options, to: target });}
/** * Escalates an error by sending it as an event to this machine's parent. * * @param errorData The error data to send, or the expression function that * takes in the `context`, `event`, and `meta`, and returns the error data to send. * @param options Options to pass into the send action creator. */export function escalate< TContext, TEvent extends EventObject, TErrorData = any>( errorData: TErrorData | ExprWithMeta<TContext, TEvent, TErrorData>, options?: SendActionOptions<TContext, TEvent>): SendAction<TContext, TEvent, AnyEventObject> { return sendParent<TContext, TEvent>( (context, event, meta) => { return { type: actionTypes.error, data: isFunction(errorData) ? errorData(context, event, meta) : errorData }; }, { ...options, to: SpecialTargets.Parent } );}
export function choose<TContext, TEvent extends EventObject>( conds: Array<ChooseCondition<TContext, TEvent>>): ChooseAction<TContext, TEvent> { return { type: ActionTypes.Choose, conds };}
const pluckAssigns = <TContext, TEvent extends EventObject>( actionBlocks: Array<Array<ActionObject<TContext, TEvent>>>): AssignAction<TContext, TEvent>[] => { const assignActions: AssignAction<TContext, TEvent>[] = [];
for (const block of actionBlocks) { let i = 0; while (i < block.length) { if (block[i].type === actionTypes.assign) { assignActions.push(block[i] as AssignAction<TContext, TEvent>); block.splice(i, 1); continue; } i++; } }
return assignActions;};
export function resolveActions<TContext, TEvent extends EventObject>( machine: StateNode<TContext, any, TEvent, any, any, any>, currentState: State<TContext, TEvent, any, any, any> | undefined, currentContext: TContext, _event: SCXML.Event<TEvent>, actionBlocks: Array<Array<ActionObject<TContext, TEvent>>>, predictableExec?: PredictableActionArgumentsExec, preserveActionOrder: boolean = false): [Array<ActionObject<TContext, TEvent>>, TContext] { const assignActions = preserveActionOrder ? [] : pluckAssigns(actionBlocks);
let updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext;
const preservedContexts: TContext[] | undefined = preserveActionOrder ? [currentContext] : undefined;
const deferredToBlockEnd: Array<ActionObject<TContext, TEvent>> = [];
function handleAction(actionObject: ActionObject<TContext, TEvent>) { switch (actionObject.type) { case actionTypes.raise: { return resolveRaise(actionObject as RaiseAction<TEvent>); } case actionTypes.send: const sendAction = resolveSend( actionObject as SendAction<TContext, TEvent, AnyEventObject>, updatedContext, _event, machine.options.delays as any ) as SendActionObject<TContext, TEvent>; // TODO: fix ActionTypes.Init
if (!IS_PRODUCTION) { // warn after resolving as we can create better contextual message here warn( !isString(actionObject.delay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length `No delay reference for delay expression '${actionObject.delay}' was found on machine '${machine.id}'` ); }
if (predictableExec && sendAction.to !== SpecialTargets.Internal) { deferredToBlockEnd.push(sendAction); }
return sendAction; case actionTypes.log: { const resolved = resolveLog( actionObject as LogAction<TContext, TEvent>, updatedContext, _event ); predictableExec?.(resolved, updatedContext, _event); return resolved; } case actionTypes.choose: { const chooseAction = actionObject as ChooseAction<TContext, TEvent>; const matchedActions = chooseAction.conds.find((condition) => { const guard = toGuard(condition.cond, machine.options.guards as any); return ( !guard || evaluateGuard( machine, guard, updatedContext, _event, (!predictableExec ? currentState : undefined) as any ) ); })?.actions;
if (!matchedActions) { return []; }
const [ resolvedActionsFromChoose, resolvedContextFromChoose ] = resolveActions( machine, currentState, updatedContext, _event, [ toActionObjects( toArray(matchedActions), machine.options.actions as any ) ], predictableExec, preserveActionOrder ); updatedContext = resolvedContextFromChoose; preservedContexts?.push(updatedContext); return resolvedActionsFromChoose; } case actionTypes.pure: { const matchedActions = (actionObject as PureAction< TContext, TEvent >).get(updatedContext, _event.data); if (!matchedActions) { return []; } const [resolvedActionsFromPure, resolvedContext] = resolveActions( machine, currentState, updatedContext, _event, [ toActionObjects( toArray(matchedActions), machine.options.actions as any ) ], predictableExec, preserveActionOrder ); updatedContext = resolvedContext; preservedContexts?.push(updatedContext); return resolvedActionsFromPure; } case actionTypes.stop: { const resolved = resolveStop( actionObject as StopAction<TContext, TEvent>, updatedContext, _event );
predictableExec?.(resolved, currentContext, _event); return resolved; } case actionTypes.assign: { updatedContext = updateContext( updatedContext, _event, [actionObject as AssignAction<TContext, TEvent>], !predictableExec ? currentState : undefined ); preservedContexts?.push(updatedContext); break; } default: let resolvedActionObject = toActionObject( actionObject, machine.options.actions as any ); const { exec } = resolvedActionObject; if (predictableExec) { predictableExec(resolvedActionObject, updatedContext, _event); } else if (exec && preservedContexts) { const contextIndex = preservedContexts.length - 1; resolvedActionObject = { ...resolvedActionObject, exec: (_ctx, ...args) => { exec(preservedContexts[contextIndex], ...args); } }; } return resolvedActionObject; } }
function processBlock(block: ActionObject<TContext, TEvent>[]) { let resolvedActions: Array<ActionObject<TContext, TEvent>> = [];
for (const action of block) { const resolved = handleAction(action); if (resolved) { resolvedActions = resolvedActions.concat(resolved); } }
deferredToBlockEnd.forEach((action) => { predictableExec!(action, updatedContext, _event); }); deferredToBlockEnd.length = 0;
return resolvedActions; }
const resolvedActions = flatten(actionBlocks.map(processBlock)); return [resolvedActions, updatedContext];}
xstate

Version Info

Tagged at
2 years ago