xstate 5.0.0-beta.10 → 5.0.0-beta.12

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 (57) hide show
  1. package/actions/dist/xstate-actions.cjs.js +29 -5
  2. package/actions/dist/{xstate-actions.cjs.dev.js → xstate-actions.development.cjs.js} +2 -2
  3. package/actions/dist/xstate-actions.development.esm.js +2 -0
  4. package/actions/dist/xstate-actions.esm.js +2 -2
  5. package/actions/dist/xstate-actions.umd.min.js +1 -1
  6. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  7. package/actors/dist/xstate-actors.cjs.js +20 -5
  8. package/actors/dist/{xstate-actors.cjs.dev.js → xstate-actors.development.cjs.js} +2 -2
  9. package/actors/dist/xstate-actors.development.esm.js +2 -0
  10. package/actors/dist/xstate-actors.esm.js +2 -2
  11. package/actors/dist/xstate-actors.umd.min.js +1 -1
  12. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  13. package/dev/dist/xstate-dev.cjs.js +45 -4
  14. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  15. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  16. package/dev/dist/xstate-dev.esm.js +42 -1
  17. package/dev/dist/xstate-dev.umd.min.js +1 -1
  18. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  19. package/dist/actions-b34f6ce7.esm.js +3292 -0
  20. package/dist/actions-c8b9504d.development.esm.js +3327 -0
  21. package/dist/actions-d9c19f35.development.cjs.js +3409 -0
  22. package/dist/actions-e4c704f3.cjs.js +3374 -0
  23. package/dist/declarations/src/interpreter.d.ts +1 -6
  24. package/dist/declarations/src/types.d.ts +1 -0
  25. package/dist/declarations/src/utils.d.ts +0 -1
  26. package/dist/declarations/src/waitFor.d.ts +1 -1
  27. package/dist/xstate.cjs.js +802 -4
  28. package/dist/xstate.development.cjs.js +808 -0
  29. package/dist/xstate.development.esm.js +770 -0
  30. package/dist/xstate.esm.js +543 -662
  31. package/dist/xstate.umd.min.js +1 -1
  32. package/dist/xstate.umd.min.js.map +1 -1
  33. package/guards/dist/xstate-guards.cjs.js +13 -5
  34. package/guards/dist/{xstate-guards.cjs.prod.js → xstate-guards.development.cjs.js} +2 -2
  35. package/guards/dist/xstate-guards.development.esm.js +2 -0
  36. package/guards/dist/xstate-guards.esm.js +2 -2
  37. package/guards/dist/xstate-guards.umd.min.js +1 -1
  38. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  39. package/package.json +52 -1
  40. package/actions/dist/xstate-actions.cjs.prod.js +0 -31
  41. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  42. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  43. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  44. package/dist/actions-109712d3.cjs.dev.js +0 -4357
  45. package/dist/actions-67f1d04e.esm.js +0 -4270
  46. package/dist/actions-d0262a43.cjs.prod.js +0 -4333
  47. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  48. package/dist/declarations/src/Mailbox.d.ts +0 -12
  49. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  50. package/dist/declarations/src/environment.d.ts +0 -1
  51. package/dist/declarations/src/memo.d.ts +0 -2
  52. package/dist/declarations/src/spawn.d.ts +0 -2
  53. package/dist/declarations/src/system.d.ts +0 -2
  54. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  55. package/dist/xstate.cjs.dev.js +0 -933
  56. package/dist/xstate.cjs.prod.js +0 -930
  57. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
@@ -0,0 +1,3327 @@
1
+ import { devToolsAdapter } from '../dev/dist/xstate-dev.development.esm.js';
2
+
3
+ // https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887
4
+
5
+ // TODO: replace in v5 with:
6
+ // export type IndexByType<T extends { type: string }> = { [E in T as E['type']]: E; };
7
+
8
+ /**
9
+ * The full definition of an event, with a string `type`.
10
+ */
11
+
12
+ // TODO: do not accept machines without all implementations
13
+ // we should also accept a raw machine as a behavior here
14
+ // or just make machine a behavior
15
+
16
+ // TODO: narrow this to behaviors from machine
17
+
18
+ // TODO: fix last param
19
+
20
+ /**
21
+ * Extracts action objects that have no extra properties.
22
+ */
23
+
24
+ /**
25
+ * The string or object representing the state value relative to the parent state node.
26
+ *
27
+ * - For a child atomic state node, this is a string, e.g., `"pending"`.
28
+ * - For complex state nodes, this is an object, e.g., `{ success: "someChildState" }`.
29
+ */
30
+
31
+ // TODO: remove once TS fixes this type-widening issue
32
+
33
+ // TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something
34
+
35
+ let ActionTypes = /*#__PURE__*/function (ActionTypes) {
36
+ ActionTypes["Stop"] = "xstate.stop";
37
+ ActionTypes["Raise"] = "xstate.raise";
38
+ ActionTypes["Send"] = "xstate.send";
39
+ ActionTypes["Cancel"] = "xstate.cancel";
40
+ ActionTypes["Assign"] = "xstate.assign";
41
+ ActionTypes["After"] = "xstate.after";
42
+ ActionTypes["DoneState"] = "done.state";
43
+ ActionTypes["DoneInvoke"] = "done.invoke";
44
+ ActionTypes["Log"] = "xstate.log";
45
+ ActionTypes["Init"] = "xstate.init";
46
+ ActionTypes["Invoke"] = "xstate.invoke";
47
+ ActionTypes["ErrorExecution"] = "error.execution";
48
+ ActionTypes["ErrorCommunication"] = "error.communication";
49
+ ActionTypes["ErrorPlatform"] = "error.platform";
50
+ ActionTypes["ErrorCustom"] = "xstate.error";
51
+ ActionTypes["Pure"] = "xstate.pure";
52
+ ActionTypes["Choose"] = "xstate.choose";
53
+ return ActionTypes;
54
+ }({});
55
+ let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
56
+ SpecialTargets["Parent"] = "#_parent";
57
+ SpecialTargets["Internal"] = "#_internal";
58
+ return SpecialTargets;
59
+ }({});
60
+
61
+ // xstate-specific action types
62
+ const stop$1 = ActionTypes.Stop;
63
+ const raise$1 = ActionTypes.Raise;
64
+ const send$1 = ActionTypes.Send;
65
+ const cancel$1 = ActionTypes.Cancel;
66
+ const assign$1 = ActionTypes.Assign;
67
+ const after$1 = ActionTypes.After;
68
+ const doneState = ActionTypes.DoneState;
69
+ const log$1 = ActionTypes.Log;
70
+ const init = ActionTypes.Init;
71
+ const invoke$1 = ActionTypes.Invoke;
72
+ const errorExecution = ActionTypes.ErrorExecution;
73
+ const errorPlatform = ActionTypes.ErrorPlatform;
74
+ const error$1 = ActionTypes.ErrorCustom;
75
+ const choose$1 = ActionTypes.Choose;
76
+ const pure$1 = ActionTypes.Pure;
77
+
78
+ var actionTypes = /*#__PURE__*/Object.freeze({
79
+ __proto__: null,
80
+ stop: stop$1,
81
+ raise: raise$1,
82
+ send: send$1,
83
+ cancel: cancel$1,
84
+ assign: assign$1,
85
+ after: after$1,
86
+ doneState: doneState,
87
+ log: log$1,
88
+ init: init,
89
+ invoke: invoke$1,
90
+ errorExecution: errorExecution,
91
+ errorPlatform: errorPlatform,
92
+ error: error$1,
93
+ choose: choose$1,
94
+ pure: pure$1
95
+ });
96
+
97
+ const STATE_DELIMITER = '.';
98
+ const TARGETLESS_KEY = '';
99
+ const NULL_EVENT = '';
100
+ const STATE_IDENTIFIER = '#';
101
+ const WILDCARD = '*';
102
+
103
+ function matchesState(parentStateId, childStateId, delimiter = STATE_DELIMITER) {
104
+ const parentStateValue = toStateValue(parentStateId, delimiter);
105
+ const childStateValue = toStateValue(childStateId, delimiter);
106
+ if (isString(childStateValue)) {
107
+ if (isString(parentStateValue)) {
108
+ return childStateValue === parentStateValue;
109
+ }
110
+
111
+ // Parent more specific than child
112
+ return false;
113
+ }
114
+ if (isString(parentStateValue)) {
115
+ return parentStateValue in childStateValue;
116
+ }
117
+ return Object.keys(parentStateValue).every(key => {
118
+ if (!(key in childStateValue)) {
119
+ return false;
120
+ }
121
+ return matchesState(parentStateValue[key], childStateValue[key]);
122
+ });
123
+ }
124
+ function toStatePath(stateId, delimiter) {
125
+ try {
126
+ if (isArray(stateId)) {
127
+ return stateId;
128
+ }
129
+ return stateId.toString().split(delimiter);
130
+ } catch (e) {
131
+ throw new Error(`'${stateId}' is not a valid state path.`);
132
+ }
133
+ }
134
+ function isStateLike(state) {
135
+ return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state;
136
+ }
137
+ function toStateValue(stateValue, delimiter) {
138
+ if (isStateLike(stateValue)) {
139
+ return stateValue.value;
140
+ }
141
+ if (isArray(stateValue)) {
142
+ return pathToStateValue(stateValue);
143
+ }
144
+ if (typeof stateValue !== 'string') {
145
+ return stateValue;
146
+ }
147
+ const statePath = toStatePath(stateValue, delimiter);
148
+ return pathToStateValue(statePath);
149
+ }
150
+ function pathToStateValue(statePath) {
151
+ if (statePath.length === 1) {
152
+ return statePath[0];
153
+ }
154
+ const value = {};
155
+ let marker = value;
156
+ for (let i = 0; i < statePath.length - 1; i++) {
157
+ if (i === statePath.length - 2) {
158
+ marker[statePath[i]] = statePath[i + 1];
159
+ } else {
160
+ marker[statePath[i]] = {};
161
+ marker = marker[statePath[i]];
162
+ }
163
+ }
164
+ return value;
165
+ }
166
+ function mapValues(collection, iteratee) {
167
+ const result = {};
168
+ const collectionKeys = Object.keys(collection);
169
+ for (let i = 0; i < collectionKeys.length; i++) {
170
+ const key = collectionKeys[i];
171
+ result[key] = iteratee(collection[key], key, collection, i);
172
+ }
173
+ return result;
174
+ }
175
+ function flatten(array) {
176
+ return [].concat(...array);
177
+ }
178
+ function toArrayStrict(value) {
179
+ if (isArray(value)) {
180
+ return value;
181
+ }
182
+ return [value];
183
+ }
184
+ function toArray(value) {
185
+ if (value === undefined) {
186
+ return [];
187
+ }
188
+ return toArrayStrict(value);
189
+ }
190
+ function mapContext(mapper, context, event) {
191
+ if (isFunction(mapper)) {
192
+ return mapper({
193
+ context,
194
+ event
195
+ });
196
+ }
197
+ const result = {};
198
+ const args = {
199
+ context,
200
+ event
201
+ };
202
+ for (const key of Object.keys(mapper)) {
203
+ const subMapper = mapper[key];
204
+ if (isFunction(subMapper)) {
205
+ result[key] = subMapper(args);
206
+ } else {
207
+ result[key] = subMapper;
208
+ }
209
+ }
210
+ return result;
211
+ }
212
+ function isPromiseLike(value) {
213
+ if (value instanceof Promise) {
214
+ return true;
215
+ }
216
+ // Check if shape matches the Promise/A+ specification for a "thenable".
217
+ if (value !== null && (isFunction(value) || typeof value === 'object') && isFunction(value.then)) {
218
+ return true;
219
+ }
220
+ return false;
221
+ }
222
+ function isArray(value) {
223
+ return Array.isArray(value);
224
+ }
225
+
226
+ // tslint:disable-next-line:ban-types
227
+ function isFunction(value) {
228
+ return typeof value === 'function';
229
+ }
230
+ function isString(value) {
231
+ return typeof value === 'string';
232
+ }
233
+ function isErrorEvent(event) {
234
+ return typeof event.type === 'string' && (event.type === errorExecution || event.type.startsWith(errorPlatform));
235
+ }
236
+ function toTransitionConfigArray(event, configLike) {
237
+ const transitions = toArrayStrict(configLike).map(transitionLike => {
238
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
239
+ return {
240
+ target: transitionLike,
241
+ event
242
+ };
243
+ }
244
+ return {
245
+ ...transitionLike,
246
+ event
247
+ };
248
+ });
249
+ return transitions;
250
+ }
251
+ function normalizeTarget(target) {
252
+ if (target === undefined || target === TARGETLESS_KEY) {
253
+ return undefined;
254
+ }
255
+ return toArray(target);
256
+ }
257
+ function toInvokeConfig(invocable, id) {
258
+ if (typeof invocable === 'object') {
259
+ if ('src' in invocable) {
260
+ return invocable;
261
+ }
262
+ if ('transition' in invocable) {
263
+ return {
264
+ id,
265
+ src: invocable
266
+ };
267
+ }
268
+ }
269
+ return {
270
+ id,
271
+ src: invocable
272
+ };
273
+ }
274
+ function toObserver(nextHandler, errorHandler, completionHandler) {
275
+ const noop = () => {};
276
+ const isObserver = typeof nextHandler === 'object';
277
+ const self = isObserver ? nextHandler : null;
278
+ return {
279
+ next: ((isObserver ? nextHandler.next : nextHandler) || noop).bind(self),
280
+ error: ((isObserver ? nextHandler.error : errorHandler) || noop).bind(self),
281
+ complete: ((isObserver ? nextHandler.complete : completionHandler) || noop).bind(self)
282
+ };
283
+ }
284
+ function createInvokeId(stateNodeId, index) {
285
+ return `${stateNodeId}:invocation[${index}]`;
286
+ }
287
+ function resolveReferencedActor(referenced) {
288
+ return referenced ? 'transition' in referenced ? {
289
+ src: referenced,
290
+ input: undefined
291
+ } : referenced : undefined;
292
+ }
293
+
294
+ function createDynamicAction(action, resolve) {
295
+ return {
296
+ type: action.type,
297
+ params: action.params,
298
+ resolve
299
+ };
300
+ }
301
+ function isDynamicAction(action) {
302
+ return typeof action === 'object' && action !== null && 'resolve' in action;
303
+ }
304
+
305
+ /**
306
+ * Sends an event. This returns an action that will be read by an interpreter to
307
+ * send the event in the next step, after the current step is finished executing.
308
+ *
309
+ * @deprecated Use the `sendTo(...)` action creator instead.
310
+ *
311
+ * @param eventOrExpr The event to send.
312
+ * @param options Options to pass into the send event:
313
+ * - `id` - The unique send event identifier (used with `cancel()`).
314
+ * - `delay` - The number of milliseconds to delay the sending of the event.
315
+ * - `to` - The target of this event (by default, the machine the event was sent from).
316
+ */
317
+ function send(eventOrExpr, options) {
318
+ return createDynamicAction({
319
+ type: send$1,
320
+ params: {
321
+ to: options ? options.to : undefined,
322
+ delay: options ? options.delay : undefined,
323
+ event: eventOrExpr,
324
+ id: options && options.id !== undefined ? options.id : isFunction(eventOrExpr) ? eventOrExpr.name : eventOrExpr.type
325
+ }
326
+ }, (event, {
327
+ actorContext,
328
+ state
329
+ }) => {
330
+ const params = {
331
+ to: options ? options.to : undefined,
332
+ delay: options ? options.delay : undefined,
333
+ event: eventOrExpr,
334
+ // TODO: don't auto-generate IDs here like that
335
+ // there is too big chance of the ID collision
336
+ id: options && options.id !== undefined ? options.id : isFunction(eventOrExpr) ? eventOrExpr.name : eventOrExpr.type
337
+ };
338
+ const args = {
339
+ context: state.context,
340
+ event,
341
+ self: actorContext?.self ?? null,
342
+ system: actorContext?.system
343
+ };
344
+ const delaysMap = state.machine.options.delays;
345
+
346
+ // TODO: helper function for resolving Expr
347
+ if (typeof eventOrExpr === 'string') {
348
+ throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`);
349
+ }
350
+ const resolvedEvent = isFunction(eventOrExpr) ? eventOrExpr(args) : eventOrExpr;
351
+ let resolvedDelay;
352
+ if (isString(params.delay)) {
353
+ const configDelay = delaysMap && delaysMap[params.delay];
354
+ resolvedDelay = isFunction(configDelay) ? configDelay(args) : configDelay;
355
+ } else {
356
+ resolvedDelay = isFunction(params.delay) ? params.delay(args) : params.delay;
357
+ }
358
+ const resolvedTarget = isFunction(params.to) ? params.to(args) : params.to;
359
+ let targetActorRef;
360
+ if (typeof resolvedTarget === 'string') {
361
+ if (resolvedTarget === SpecialTargets.Parent) {
362
+ targetActorRef = actorContext?.self._parent;
363
+ } else if (resolvedTarget === SpecialTargets.Internal) {
364
+ targetActorRef = actorContext?.self;
365
+ } else if (resolvedTarget.startsWith('#_')) {
366
+ // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor
367
+ // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.
368
+ targetActorRef = state.children[resolvedTarget.slice(2)];
369
+ } else {
370
+ targetActorRef = state.children[resolvedTarget];
371
+ }
372
+ if (!targetActorRef) {
373
+ throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${state.machine.id}'.`);
374
+ }
375
+ } else {
376
+ targetActorRef = resolvedTarget || actorContext?.self;
377
+ }
378
+ const resolvedAction = {
379
+ type: send$1,
380
+ params: {
381
+ ...params,
382
+ to: targetActorRef,
383
+ event: resolvedEvent,
384
+ delay: resolvedDelay,
385
+ internal: resolvedTarget === SpecialTargets.Internal
386
+ },
387
+ execute: actorCtx => {
388
+ const sendAction = resolvedAction;
389
+ if (typeof sendAction.params.delay === 'number') {
390
+ actorCtx.self.delaySend(sendAction);
391
+ return;
392
+ } else {
393
+ const target = sendAction.params.to;
394
+ const sentEvent = sendAction.params.event;
395
+ actorCtx.defer(() => {
396
+ target.send(sentEvent.type === error$1 ? {
397
+ type: `${error(actorCtx.self.id)}`,
398
+ data: sentEvent.data
399
+ } : sendAction.params.event);
400
+ });
401
+ }
402
+ }
403
+ };
404
+ return [state, resolvedAction];
405
+ });
406
+ }
407
+
408
+ /**
409
+ * Sends an event to this machine's parent.
410
+ *
411
+ * @param event The event to send to the parent machine.
412
+ * @param options Options to pass into the send event.
413
+ */
414
+ function sendParent(event, options) {
415
+ return send(event, {
416
+ ...options,
417
+ to: SpecialTargets.Parent
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Forwards (sends) an event to a specified service.
423
+ *
424
+ * @param target The target service to forward the event to.
425
+ * @param options Options to pass into the send action creator.
426
+ */
427
+ function forwardTo(target, options) {
428
+ if ((!target || typeof target === 'function')) {
429
+ const originalTarget = target;
430
+ target = (...args) => {
431
+ const resolvedTarget = typeof originalTarget === 'function' ? originalTarget(...args) : originalTarget;
432
+ if (!resolvedTarget) {
433
+ throw new Error(`Attempted to forward event to undefined actor. This risks an infinite loop in the sender.`);
434
+ }
435
+ return resolvedTarget;
436
+ };
437
+ }
438
+ return send(({
439
+ event
440
+ }) => event, {
441
+ ...options,
442
+ to: target
443
+ });
444
+ }
445
+
446
+ /**
447
+ * Escalates an error by sending it as an event to this machine's parent.
448
+ *
449
+ * @param errorData The error data to send, or the expression function that
450
+ * takes in the `context`, `event`, and `meta`, and returns the error data to send.
451
+ * @param options Options to pass into the send action creator.
452
+ */
453
+ function escalate(errorData, options) {
454
+ return sendParent(arg => {
455
+ return {
456
+ type: error$1,
457
+ data: isFunction(errorData) ? errorData(arg) : errorData
458
+ };
459
+ }, {
460
+ ...options,
461
+ to: SpecialTargets.Parent
462
+ });
463
+ }
464
+
465
+ /**
466
+ * Sends an event to an actor.
467
+ *
468
+ * @param actor The `ActorRef` to send the event to.
469
+ * @param event The event to send, or an expression that evaluates to the event to send
470
+ * @param options Send action options
471
+ * @returns An XState send action object
472
+ */
473
+ function sendTo(actor, event, options) {
474
+ return send(event, {
475
+ ...options,
476
+ to: actor
477
+ });
478
+ }
479
+
480
+ class Mailbox {
481
+ constructor(_process) {
482
+ this._process = _process;
483
+ this._active = false;
484
+ this._current = null;
485
+ this._last = null;
486
+ }
487
+ start() {
488
+ this._active = true;
489
+ this.flush();
490
+ }
491
+ clear() {
492
+ // we can't set _current to null because we might be currently processing
493
+ // and enqueue following clear shouldnt start processing the enqueued item immediately
494
+ if (this._current) {
495
+ this._current.next = null;
496
+ this._last = this._current;
497
+ }
498
+ }
499
+
500
+ // TODO: rethink this design
501
+ prepend(event) {
502
+ if (!this._current) {
503
+ this.enqueue(event);
504
+ return;
505
+ }
506
+
507
+ // we know that something is already queued up
508
+ // so the mailbox is already flushing or it's inactive
509
+ // therefore the only thing that we need to do is to reassign `this._current`
510
+ this._current = {
511
+ value: event,
512
+ next: this._current
513
+ };
514
+ }
515
+ enqueue(event) {
516
+ const enqueued = {
517
+ value: event,
518
+ next: null
519
+ };
520
+ if (this._current) {
521
+ this._last.next = enqueued;
522
+ this._last = enqueued;
523
+ return;
524
+ }
525
+ this._current = enqueued;
526
+ this._last = enqueued;
527
+ if (this._active) {
528
+ this.flush();
529
+ }
530
+ }
531
+ flush() {
532
+ while (this._current) {
533
+ // atm the given _process is responsible for implementing proper try/catch handling
534
+ // we assume here that this won't throw in a way that can affect this mailbox
535
+ const consumed = this._current;
536
+ this._process(consumed.value);
537
+ // something could have been prepended in the meantime
538
+ // so we need to be defensive here to avoid skipping over a prepended item
539
+ if (consumed === this._current) {
540
+ this._current = this._current.next;
541
+ }
542
+ }
543
+ this._last = null;
544
+ }
545
+ }
546
+
547
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
548
+
549
+ /**
550
+ * Returns an actor behavior from a transition function and its initial state.
551
+ *
552
+ * A transition function is a function that takes the current state and an event and returns the next state.
553
+ *
554
+ * @param transition The transition function that returns the next state given the current state and event.
555
+ * @param initialState The initial state of the transition function.
556
+ * @returns An actor behavior
557
+ */
558
+ function fromTransition(transition, initialState) {
559
+ const behavior = {
560
+ config: transition,
561
+ transition: (state, event, actorContext) => {
562
+ return transition(state, event, actorContext);
563
+ },
564
+ getInitialState: (_, input) => {
565
+ return typeof initialState === 'function' ? initialState({
566
+ input
567
+ }) : initialState;
568
+ },
569
+ getSnapshot: state => state,
570
+ getPersistedState: state => state,
571
+ restoreState: state => state
572
+ };
573
+ return behavior;
574
+ }
575
+
576
+ function fromPromise(
577
+ // TODO: add types
578
+ promiseCreator) {
579
+ const resolveEventType = '$$xstate.resolve';
580
+ const rejectEventType = '$$xstate.reject';
581
+
582
+ // TODO: add event types
583
+ const behavior = {
584
+ config: promiseCreator,
585
+ transition: (state, event) => {
586
+ if (state.status !== 'active') {
587
+ return state;
588
+ }
589
+ switch (event.type) {
590
+ case resolveEventType:
591
+ return {
592
+ ...state,
593
+ status: 'done',
594
+ data: event.data,
595
+ input: undefined
596
+ };
597
+ case rejectEventType:
598
+ return {
599
+ ...state,
600
+ status: 'error',
601
+ data: event.data,
602
+ input: undefined
603
+ };
604
+ case stopSignalType:
605
+ return {
606
+ ...state,
607
+ status: 'canceled',
608
+ input: undefined
609
+ };
610
+ default:
611
+ return state;
612
+ }
613
+ },
614
+ start: (state, {
615
+ self
616
+ }) => {
617
+ // TODO: determine how to allow customizing this so that promises
618
+ // can be restarted if necessary
619
+ if (state.status !== 'active') {
620
+ return;
621
+ }
622
+ const resolvedPromise = Promise.resolve(promiseCreator({
623
+ input: state.input
624
+ }));
625
+ resolvedPromise.then(response => {
626
+ // TODO: remove this condition once dead letter queue lands
627
+ if (self._state.status !== 'active') {
628
+ return;
629
+ }
630
+ self.send({
631
+ type: resolveEventType,
632
+ data: response
633
+ });
634
+ }, errorData => {
635
+ // TODO: remove this condition once dead letter queue lands
636
+ if (self._state.status !== 'active') {
637
+ return;
638
+ }
639
+ self.send({
640
+ type: rejectEventType,
641
+ data: errorData
642
+ });
643
+ });
644
+ },
645
+ getInitialState: (_, input) => {
646
+ return {
647
+ status: 'active',
648
+ data: undefined,
649
+ input
650
+ };
651
+ },
652
+ getSnapshot: state => state.data,
653
+ getStatus: state => state,
654
+ getPersistedState: state => state,
655
+ restoreState: state => state
656
+ };
657
+ return behavior;
658
+ }
659
+
660
+ // TODO: this likely shouldn't accept TEvent, observable actor doesn't accept external events
661
+ function fromObservable(observableCreator) {
662
+ const nextEventType = '$$xstate.next';
663
+ const errorEventType = '$$xstate.error';
664
+ const completeEventType = '$$xstate.complete';
665
+
666
+ // TODO: add event types
667
+ const behavior = {
668
+ config: observableCreator,
669
+ transition: (state, event, {
670
+ self,
671
+ id,
672
+ defer
673
+ }) => {
674
+ if (state.status !== 'active') {
675
+ return state;
676
+ }
677
+ switch (event.type) {
678
+ case nextEventType:
679
+ // match the exact timing of events sent by machines
680
+ // send actions are not executed immediately
681
+ defer(() => {
682
+ self._parent?.send({
683
+ type: `xstate.snapshot.${id}`,
684
+ data: event.data
685
+ });
686
+ });
687
+ return {
688
+ ...state,
689
+ data: event.data
690
+ };
691
+ case errorEventType:
692
+ return {
693
+ ...state,
694
+ status: 'error',
695
+ input: undefined,
696
+ data: event.data,
697
+ subscription: undefined
698
+ };
699
+ case completeEventType:
700
+ return {
701
+ ...state,
702
+ status: 'done',
703
+ input: undefined,
704
+ subscription: undefined
705
+ };
706
+ case stopSignalType:
707
+ state.subscription.unsubscribe();
708
+ return {
709
+ ...state,
710
+ status: 'canceled',
711
+ input: undefined,
712
+ subscription: undefined
713
+ };
714
+ default:
715
+ return state;
716
+ }
717
+ },
718
+ getInitialState: (_, input) => {
719
+ return {
720
+ subscription: undefined,
721
+ status: 'active',
722
+ data: undefined,
723
+ input
724
+ };
725
+ },
726
+ start: (state, {
727
+ self
728
+ }) => {
729
+ if (state.status === 'done') {
730
+ // Do not restart a completed observable
731
+ return;
732
+ }
733
+ state.subscription = observableCreator({
734
+ input: state.input
735
+ }).subscribe({
736
+ next: value => {
737
+ self.send({
738
+ type: nextEventType,
739
+ data: value
740
+ });
741
+ },
742
+ error: err => {
743
+ self.send({
744
+ type: errorEventType,
745
+ data: err
746
+ });
747
+ },
748
+ complete: () => {
749
+ self.send({
750
+ type: completeEventType
751
+ });
752
+ }
753
+ });
754
+ },
755
+ getSnapshot: state => state.data,
756
+ getPersistedState: ({
757
+ status,
758
+ data,
759
+ input
760
+ }) => ({
761
+ status,
762
+ data,
763
+ input
764
+ }),
765
+ getStatus: state => state,
766
+ restoreState: state => ({
767
+ ...state,
768
+ subscription: undefined
769
+ })
770
+ };
771
+ return behavior;
772
+ }
773
+
774
+ /**
775
+ * Creates an event observable behavior that listens to an observable
776
+ * that delivers event objects.
777
+ *
778
+ *
779
+ * @param lazyObservable A function that creates an observable
780
+ * @returns An event observable behavior
781
+ */
782
+
783
+ function fromEventObservable(lazyObservable) {
784
+ const errorEventType = '$$xstate.error';
785
+ const completeEventType = '$$xstate.complete';
786
+
787
+ // TODO: event types
788
+ const behavior = {
789
+ config: lazyObservable,
790
+ transition: (state, event) => {
791
+ if (state.status !== 'active') {
792
+ return state;
793
+ }
794
+ switch (event.type) {
795
+ case errorEventType:
796
+ return {
797
+ ...state,
798
+ status: 'error',
799
+ input: undefined,
800
+ data: event.data,
801
+ subscription: undefined
802
+ };
803
+ case completeEventType:
804
+ return {
805
+ ...state,
806
+ status: 'done',
807
+ input: undefined,
808
+ subscription: undefined
809
+ };
810
+ case stopSignalType:
811
+ state.subscription.unsubscribe();
812
+ return {
813
+ ...state,
814
+ status: 'canceled',
815
+ input: undefined,
816
+ subscription: undefined
817
+ };
818
+ default:
819
+ return state;
820
+ }
821
+ },
822
+ getInitialState: (_, input) => {
823
+ return {
824
+ subscription: undefined,
825
+ status: 'active',
826
+ data: undefined,
827
+ input
828
+ };
829
+ },
830
+ start: (state, {
831
+ self
832
+ }) => {
833
+ if (state.status === 'done') {
834
+ // Do not restart a completed observable
835
+ return;
836
+ }
837
+ state.subscription = lazyObservable({
838
+ input: state.input
839
+ }).subscribe({
840
+ next: value => {
841
+ self._parent?.send(value);
842
+ },
843
+ error: err => {
844
+ self.send({
845
+ type: errorEventType,
846
+ data: err
847
+ });
848
+ },
849
+ complete: () => {
850
+ self.send({
851
+ type: completeEventType
852
+ });
853
+ }
854
+ });
855
+ },
856
+ getSnapshot: _ => undefined,
857
+ getPersistedState: ({
858
+ status,
859
+ data,
860
+ input
861
+ }) => ({
862
+ status,
863
+ data,
864
+ input
865
+ }),
866
+ getStatus: state => state,
867
+ restoreState: state => ({
868
+ ...state,
869
+ subscription: undefined
870
+ })
871
+ };
872
+ return behavior;
873
+ }
874
+
875
+ function fromCallback(invokeCallback) {
876
+ const behavior = {
877
+ config: invokeCallback,
878
+ start: (_state, {
879
+ self
880
+ }) => {
881
+ self.send({
882
+ type: startSignalType
883
+ });
884
+ },
885
+ transition: (state, event, {
886
+ self,
887
+ id
888
+ }) => {
889
+ if (event.type === startSignalType) {
890
+ const sender = eventForParent => {
891
+ if (state.canceled) {
892
+ return;
893
+ }
894
+ self._parent?.send(eventForParent);
895
+ };
896
+ const receiver = newListener => {
897
+ state.receivers.add(newListener);
898
+ };
899
+ state.dispose = invokeCallback(sender, receiver, {
900
+ input: state.input
901
+ });
902
+ if (isPromiseLike(state.dispose)) {
903
+ state.dispose.then(resolved => {
904
+ self._parent?.send(doneInvoke(id, resolved));
905
+ state.canceled = true;
906
+ }, errorData => {
907
+ state.canceled = true;
908
+ self._parent?.send(error(id, errorData));
909
+ });
910
+ }
911
+ return state;
912
+ }
913
+ if (event.type === stopSignalType) {
914
+ state.canceled = true;
915
+ if (isFunction(state.dispose)) {
916
+ state.dispose();
917
+ }
918
+ return state;
919
+ }
920
+ if (isSignal(event.type)) {
921
+ // TODO: unrecognized signal
922
+ return state;
923
+ }
924
+ if (!isSignal(event.type)) {
925
+ state.receivers.forEach(receiver => receiver(event));
926
+ }
927
+ return state;
928
+ },
929
+ getInitialState: (_, input) => {
930
+ return {
931
+ canceled: false,
932
+ receivers: new Set(),
933
+ dispose: undefined,
934
+ input
935
+ };
936
+ },
937
+ getSnapshot: () => undefined,
938
+ getPersistedState: ({
939
+ input
940
+ }) => input
941
+ };
942
+ return behavior;
943
+ }
944
+
945
+ const startSignalType = 'xstate.init';
946
+ const stopSignalType = 'xstate.stop';
947
+ const startSignal = {
948
+ type: 'xstate.init'
949
+ };
950
+ const stopSignal = {
951
+ type: 'xstate.stop'
952
+ };
953
+ /**
954
+ * An object that expresses the behavior of an actor in reaction to received events,
955
+ * as well as an optionally emitted stream of values.
956
+ *
957
+ * @template TReceived The received event
958
+ * @template TSnapshot The emitted value
959
+ */
960
+
961
+ function isSignal(eventType) {
962
+ return eventType === startSignalType || eventType === stopSignalType;
963
+ }
964
+ function isActorRef(item) {
965
+ return !!item && typeof item === 'object' && typeof item.send === 'function';
966
+ }
967
+
968
+ // TODO: refactor the return type, this could be written in a better way
969
+ // but it's best to avoid unneccessary breaking changes now
970
+ // @deprecated use `interpret(behavior)` instead
971
+ function toActorRef(actorRefLike) {
972
+ return {
973
+ subscribe: () => ({
974
+ unsubscribe: () => void 0
975
+ }),
976
+ id: 'anonymous',
977
+ sessionId: '',
978
+ getSnapshot: () => undefined,
979
+ [symbolObservable]: function () {
980
+ return this;
981
+ },
982
+ status: ActorStatus.Running,
983
+ stop: () => void 0,
984
+ ...actorRefLike
985
+ };
986
+ }
987
+ const emptyBehavior = fromTransition(_ => undefined, undefined);
988
+ function createEmptyActor() {
989
+ return interpret(emptyBehavior);
990
+ }
991
+
992
+ function createSystem() {
993
+ let sessionIdCounter = 0;
994
+ const children = new Map();
995
+ const keyedActors = new Map();
996
+ const reverseKeyedActors = new WeakMap();
997
+ const system = {
998
+ _bookId: () => `x:${sessionIdCounter++}`,
999
+ _register: (sessionId, actorRef) => {
1000
+ children.set(sessionId, actorRef);
1001
+ return sessionId;
1002
+ },
1003
+ _unregister: actorRef => {
1004
+ children.delete(actorRef.sessionId);
1005
+ const systemId = reverseKeyedActors.get(actorRef);
1006
+ if (systemId !== undefined) {
1007
+ keyedActors.delete(systemId);
1008
+ reverseKeyedActors.delete(actorRef);
1009
+ }
1010
+ },
1011
+ get: systemId => {
1012
+ return keyedActors.get(systemId);
1013
+ },
1014
+ _set: (systemId, actorRef) => {
1015
+ const existing = keyedActors.get(systemId);
1016
+ if (existing && existing !== actorRef) {
1017
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
1018
+ }
1019
+ keyedActors.set(systemId, actorRef);
1020
+ reverseKeyedActors.set(actorRef, systemId);
1021
+ }
1022
+ };
1023
+ return system;
1024
+ }
1025
+
1026
+ let ActorStatus = /*#__PURE__*/function (ActorStatus) {
1027
+ ActorStatus[ActorStatus["NotStarted"] = 0] = "NotStarted";
1028
+ ActorStatus[ActorStatus["Running"] = 1] = "Running";
1029
+ ActorStatus[ActorStatus["Stopped"] = 2] = "Stopped";
1030
+ return ActorStatus;
1031
+ }({});
1032
+ const defaultOptions = {
1033
+ deferEvents: true,
1034
+ clock: {
1035
+ setTimeout: (fn, ms) => {
1036
+ return setTimeout(fn, ms);
1037
+ },
1038
+ clearTimeout: id => {
1039
+ return clearTimeout(id);
1040
+ }
1041
+ },
1042
+ logger: console.log.bind(console),
1043
+ devTools: false
1044
+ };
1045
+ class Interpreter {
1046
+ /**
1047
+ * The current state of the interpreted behavior.
1048
+ */
1049
+
1050
+ /**
1051
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
1052
+ */
1053
+
1054
+ /**
1055
+ * The unique identifier for this actor relative to its parent.
1056
+ */
1057
+
1058
+ /**
1059
+ * Whether the service is started.
1060
+ */
1061
+
1062
+ // Actor Ref
1063
+
1064
+ // TODO: add typings for system
1065
+
1066
+ /**
1067
+ * The globally unique process ID for this invocation.
1068
+ */
1069
+
1070
+ /**
1071
+ * Creates a new Interpreter instance (i.e., service) for the given behavior with the provided options, if any.
1072
+ *
1073
+ * @param behavior The behavior to be interpreted
1074
+ * @param options Interpreter options
1075
+ */
1076
+ constructor(behavior, options) {
1077
+ this.behavior = behavior;
1078
+ this._state = void 0;
1079
+ this.clock = void 0;
1080
+ this.options = void 0;
1081
+ this.id = void 0;
1082
+ this.mailbox = new Mailbox(this._process.bind(this));
1083
+ this.delayedEventsMap = {};
1084
+ this.observers = new Set();
1085
+ this.logger = void 0;
1086
+ this.status = ActorStatus.NotStarted;
1087
+ this._parent = void 0;
1088
+ this.ref = void 0;
1089
+ this._actorContext = void 0;
1090
+ this._systemId = void 0;
1091
+ this.sessionId = void 0;
1092
+ this.system = void 0;
1093
+ this._doneEvent = void 0;
1094
+ this.src = void 0;
1095
+ this._deferred = [];
1096
+ const resolvedOptions = {
1097
+ ...defaultOptions,
1098
+ ...options
1099
+ };
1100
+ const {
1101
+ clock,
1102
+ logger,
1103
+ parent,
1104
+ id,
1105
+ systemId
1106
+ } = resolvedOptions;
1107
+ const self = this;
1108
+ this.system = parent?.system ?? createSystem();
1109
+ if (systemId) {
1110
+ this._systemId = systemId;
1111
+ this.system._set(systemId, this);
1112
+ }
1113
+ this.sessionId = this.system._bookId();
1114
+ this.id = id ?? this.sessionId;
1115
+ this.logger = logger;
1116
+ this.clock = clock;
1117
+ this._parent = parent;
1118
+ this.options = resolvedOptions;
1119
+ this.src = resolvedOptions.src;
1120
+ this.ref = this;
1121
+ this._actorContext = {
1122
+ self,
1123
+ id: this.id,
1124
+ sessionId: this.sessionId,
1125
+ logger: this.logger,
1126
+ defer: fn => {
1127
+ this._deferred.push(fn);
1128
+ },
1129
+ system: this.system,
1130
+ stopChild: child => {
1131
+ if (child._parent !== this) {
1132
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
1133
+ }
1134
+ child._stop();
1135
+ }
1136
+ };
1137
+
1138
+ // Ensure that the send method is bound to this interpreter instance
1139
+ // if destructured
1140
+ this.send = this.send.bind(this);
1141
+ this._initState();
1142
+ }
1143
+ _initState() {
1144
+ this._state = this.options.state ? this.behavior.restoreState ? this.behavior.restoreState(this.options.state, this._actorContext) : this.options.state : this.behavior.getInitialState(this._actorContext, this.options?.input);
1145
+ }
1146
+
1147
+ // array of functions to defer
1148
+
1149
+ update(state) {
1150
+ // Update state
1151
+ this._state = state;
1152
+ const snapshot = this.getSnapshot();
1153
+
1154
+ // Execute deferred effects
1155
+ let deferredFn;
1156
+ while (deferredFn = this._deferred.shift()) {
1157
+ deferredFn(state);
1158
+ }
1159
+ for (const observer of this.observers) {
1160
+ observer.next?.(snapshot);
1161
+ }
1162
+ const status = this.behavior.getStatus?.(state);
1163
+ switch (status?.status) {
1164
+ case 'done':
1165
+ this._stopProcedure();
1166
+ this._doneEvent = doneInvoke(this.id, status.data);
1167
+ this._parent?.send(this._doneEvent);
1168
+ this._complete();
1169
+ break;
1170
+ case 'error':
1171
+ this._stopProcedure();
1172
+ this._parent?.send(error(this.id, status.data));
1173
+ this._error(status.data);
1174
+ break;
1175
+ }
1176
+ }
1177
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
1178
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
1179
+ this.observers.add(observer);
1180
+ if (this.status === ActorStatus.Stopped) {
1181
+ observer.complete?.();
1182
+ this.observers.delete(observer);
1183
+ }
1184
+ return {
1185
+ unsubscribe: () => {
1186
+ this.observers.delete(observer);
1187
+ }
1188
+ };
1189
+ }
1190
+
1191
+ /**
1192
+ * Starts the interpreter from the initial state
1193
+ */
1194
+ start() {
1195
+ if (this.status === ActorStatus.Running) {
1196
+ // Do not restart the service if it is already started
1197
+ return this;
1198
+ }
1199
+ this.system._register(this.sessionId, this);
1200
+ if (this._systemId) {
1201
+ this.system._set(this._systemId, this);
1202
+ }
1203
+ this.status = ActorStatus.Running;
1204
+ if (this.behavior.start) {
1205
+ this.behavior.start(this._state, this._actorContext);
1206
+ }
1207
+
1208
+ // TODO: this notifies all subscribers but usually this is redundant
1209
+ // there is no real change happening here
1210
+ // we need to rethink if this needs to be refactored
1211
+ this.update(this._state);
1212
+ if (this.options.devTools) {
1213
+ this.attachDevTools();
1214
+ }
1215
+ this.mailbox.start();
1216
+ return this;
1217
+ }
1218
+ _process(event) {
1219
+ try {
1220
+ const nextState = this.behavior.transition(this._state, event, this._actorContext);
1221
+ this.update(nextState);
1222
+ if (event.type === stopSignalType) {
1223
+ this._stopProcedure();
1224
+ this._complete();
1225
+ }
1226
+ } catch (err) {
1227
+ // TODO: properly handle errors
1228
+ if (this.observers.size > 0) {
1229
+ this.observers.forEach(observer => {
1230
+ observer.error?.(err);
1231
+ });
1232
+ this.stop();
1233
+ } else {
1234
+ throw err;
1235
+ }
1236
+ }
1237
+ }
1238
+ _stop() {
1239
+ if (this.status === ActorStatus.Stopped) {
1240
+ return this;
1241
+ }
1242
+ this.mailbox.clear();
1243
+ if (this.status === ActorStatus.NotStarted) {
1244
+ this.status = ActorStatus.Stopped;
1245
+ return this;
1246
+ }
1247
+ this.mailbox.enqueue({
1248
+ type: stopSignalType
1249
+ });
1250
+ return this;
1251
+ }
1252
+
1253
+ /**
1254
+ * Stops the interpreter and unsubscribe all listeners.
1255
+ */
1256
+ stop() {
1257
+ if (this._parent) {
1258
+ throw new Error('A non-root actor cannot be stopped directly.');
1259
+ }
1260
+ return this._stop();
1261
+ }
1262
+ _complete() {
1263
+ for (const observer of this.observers) {
1264
+ observer.complete?.();
1265
+ }
1266
+ this.observers.clear();
1267
+ }
1268
+ _error(data) {
1269
+ for (const observer of this.observers) {
1270
+ observer.error?.(data);
1271
+ }
1272
+ this.observers.clear();
1273
+ }
1274
+ _stopProcedure() {
1275
+ if (this.status !== ActorStatus.Running) {
1276
+ // Interpreter already stopped; do nothing
1277
+ return this;
1278
+ }
1279
+
1280
+ // Cancel all delayed events
1281
+ for (const key of Object.keys(this.delayedEventsMap)) {
1282
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
1283
+ }
1284
+
1285
+ // TODO: mailbox.reset
1286
+ this.mailbox.clear();
1287
+ // TODO: after `stop` we must prepare ourselves for receiving events again
1288
+ // events sent *after* stop signal must be queued
1289
+ // it seems like this should be the common behavior for all of our consumers
1290
+ // so perhaps this should be unified somehow for all of them
1291
+ this.mailbox = new Mailbox(this._process.bind(this));
1292
+ this.status = ActorStatus.Stopped;
1293
+ this.system._unregister(this);
1294
+ return this;
1295
+ }
1296
+
1297
+ /**
1298
+ * Sends an event to the running interpreter to trigger a transition.
1299
+ *
1300
+ * @param event The event to send
1301
+ */
1302
+ send(event) {
1303
+ if (typeof event === 'string') {
1304
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
1305
+ }
1306
+ if (this.status === ActorStatus.Stopped) {
1307
+ // do nothing
1308
+ {
1309
+ const eventString = JSON.stringify(event);
1310
+ console.warn(`Event "${event.type.toString()}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.\nEvent: ${eventString}`);
1311
+ }
1312
+ return;
1313
+ }
1314
+ if (this.status !== ActorStatus.Running && !this.options.deferEvents) {
1315
+ throw new Error(`Event "${event.type}" was sent to uninitialized actor "${this.id
1316
+ // tslint:disable-next-line:max-line-length
1317
+ }". Make sure .start() is called for this actor, or set { deferEvents: true } in the actor options.\nEvent: ${JSON.stringify(event)}`);
1318
+ }
1319
+ this.mailbox.enqueue(event);
1320
+ }
1321
+
1322
+ // TODO: make private (and figure out a way to do this within the machine)
1323
+ delaySend(sendAction) {
1324
+ this.delayedEventsMap[sendAction.params.id] = this.clock.setTimeout(() => {
1325
+ if ('to' in sendAction.params && sendAction.params.to) {
1326
+ sendAction.params.to.send(sendAction.params.event);
1327
+ } else {
1328
+ this.send(sendAction.params.event);
1329
+ }
1330
+ }, sendAction.params.delay);
1331
+ }
1332
+
1333
+ // TODO: make private (and figure out a way to do this within the machine)
1334
+ cancel(sendId) {
1335
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
1336
+ delete this.delayedEventsMap[sendId];
1337
+ }
1338
+ attachDevTools() {
1339
+ const {
1340
+ devTools
1341
+ } = this.options;
1342
+ if (devTools) {
1343
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
1344
+ resolvedDevToolsAdapter(this);
1345
+ }
1346
+ }
1347
+ toJSON() {
1348
+ return {
1349
+ id: this.id
1350
+ };
1351
+ }
1352
+ getPersistedState() {
1353
+ return this.behavior.getPersistedState?.(this._state);
1354
+ }
1355
+ [symbolObservable]() {
1356
+ return this;
1357
+ }
1358
+ getSnapshot() {
1359
+ return this.behavior.getSnapshot ? this.behavior.getSnapshot(this._state) : this._state;
1360
+ }
1361
+ }
1362
+
1363
+ /**
1364
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
1365
+ *
1366
+ * @param machine The machine to interpret
1367
+ * @param options Interpreter options
1368
+ */
1369
+
1370
+ function interpret(behavior, options) {
1371
+ const interpreter = new Interpreter(behavior, options);
1372
+ return interpreter;
1373
+ }
1374
+
1375
+ /**
1376
+ * Stops an actor.
1377
+ *
1378
+ * @param actorRef The actor to stop.
1379
+ */
1380
+
1381
+ function stop(actorRef) {
1382
+ const actor = actorRef;
1383
+ return createDynamicAction({
1384
+ type: stop$1,
1385
+ params: {
1386
+ actor
1387
+ }
1388
+ }, (event, {
1389
+ state
1390
+ }) => {
1391
+ const actorRefOrString = isFunction(actor) ? actor({
1392
+ context: state.context,
1393
+ event
1394
+ }) : actor;
1395
+ const actorRef = typeof actorRefOrString === 'string' ? state.children[actorRefOrString] : actorRefOrString;
1396
+ return [state, {
1397
+ type: 'xstate.stop',
1398
+ params: {
1399
+ actor: actorRef
1400
+ },
1401
+ execute: actorCtx => {
1402
+ if (!actorRef) {
1403
+ return;
1404
+ }
1405
+ if (actorRef.status !== ActorStatus.Running) {
1406
+ actorCtx.stopChild(actorRef);
1407
+ return;
1408
+ }
1409
+ actorCtx.defer(() => {
1410
+ actorCtx.stopChild(actorRef);
1411
+ });
1412
+ }
1413
+ }];
1414
+ });
1415
+ }
1416
+
1417
+ const defaultLogExpr = ({
1418
+ context,
1419
+ event
1420
+ }) => ({
1421
+ context,
1422
+ event
1423
+ });
1424
+
1425
+ /**
1426
+ *
1427
+ * @param expr The expression function to evaluate which will be logged.
1428
+ * Takes in 2 arguments:
1429
+ * - `ctx` - the current state context
1430
+ * - `event` - the event that caused this action to be executed.
1431
+ * @param label The label to give to the logged expression.
1432
+ */
1433
+
1434
+ function log(expr = defaultLogExpr, label) {
1435
+ return createDynamicAction({
1436
+ type: log$1,
1437
+ params: {
1438
+ label,
1439
+ expr
1440
+ }
1441
+ }, (event, {
1442
+ state,
1443
+ actorContext
1444
+ }) => {
1445
+ const resolvedValue = typeof expr === 'function' ? expr({
1446
+ context: state.context,
1447
+ event,
1448
+ self: actorContext?.self ?? {},
1449
+ system: actorContext?.system
1450
+ }) : expr;
1451
+ return [state, {
1452
+ type: 'xstate.log',
1453
+ params: {
1454
+ label,
1455
+ value: resolvedValue
1456
+ },
1457
+ execute: actorCtx => {
1458
+ if (label) {
1459
+ actorCtx.logger?.(label, resolvedValue);
1460
+ } else {
1461
+ actorCtx.logger?.(resolvedValue);
1462
+ }
1463
+ }
1464
+ }];
1465
+ });
1466
+ }
1467
+
1468
+ /**
1469
+ * Cancels an in-flight `send(...)` action. A canceled sent action will not
1470
+ * be executed, nor will its event be sent, unless it has already been sent
1471
+ * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
1472
+ *
1473
+ * @param sendId The `id` of the `send(...)` action to cancel.
1474
+ */
1475
+
1476
+ function cancel(sendId) {
1477
+ return createDynamicAction({
1478
+ type: cancel$1,
1479
+ params: {
1480
+ sendId
1481
+ }
1482
+ }, (event, {
1483
+ state,
1484
+ actorContext
1485
+ }) => {
1486
+ const resolvedSendId = isFunction(sendId) ? sendId({
1487
+ context: state.context,
1488
+ event,
1489
+ self: actorContext?.self ?? {},
1490
+ system: actorContext?.system
1491
+ }) : sendId;
1492
+ return [state, {
1493
+ type: 'xstate.cancel',
1494
+ params: {
1495
+ sendId: resolvedSendId
1496
+ },
1497
+ execute: actorCtx => {
1498
+ const interpreter = actorCtx.self;
1499
+ interpreter.cancel(resolvedSendId);
1500
+ }
1501
+ }];
1502
+ });
1503
+ }
1504
+
1505
+ const cache = new WeakMap();
1506
+ function memo(object, key, fn) {
1507
+ let memoizedData = cache.get(object);
1508
+ if (!memoizedData) {
1509
+ memoizedData = {
1510
+ [key]: fn()
1511
+ };
1512
+ cache.set(object, memoizedData);
1513
+ } else if (!(key in memoizedData)) {
1514
+ memoizedData[key] = fn();
1515
+ }
1516
+ return memoizedData[key];
1517
+ }
1518
+
1519
+ function stateIn(stateValue) {
1520
+ return {
1521
+ type: 'xstate.guard:in',
1522
+ params: {
1523
+ stateValue
1524
+ },
1525
+ predicate: ({
1526
+ state
1527
+ }) => {
1528
+ if (isString(stateValue) && isStateId(stateValue)) {
1529
+ return state.configuration.some(sn => sn.id === stateValue.slice(1));
1530
+ }
1531
+ return state.matches(stateValue);
1532
+ }
1533
+ };
1534
+ }
1535
+ function not(guard) {
1536
+ return {
1537
+ type: 'xstate.boolean',
1538
+ params: {
1539
+ op: 'not'
1540
+ },
1541
+ children: [toGuardDefinition(guard)],
1542
+ predicate: ({
1543
+ evaluate,
1544
+ guard,
1545
+ context,
1546
+ event,
1547
+ state
1548
+ }) => {
1549
+ return !evaluate(guard.children[0], context, event, state);
1550
+ }
1551
+ };
1552
+ }
1553
+ function and(guards) {
1554
+ return {
1555
+ type: 'xstate.boolean',
1556
+ params: {
1557
+ op: 'and'
1558
+ },
1559
+ children: guards.map(guard => toGuardDefinition(guard)),
1560
+ predicate: ({
1561
+ evaluate,
1562
+ guard,
1563
+ context,
1564
+ event,
1565
+ state
1566
+ }) => {
1567
+ return guard.children.every(childGuard => {
1568
+ return evaluate(childGuard, context, event, state);
1569
+ });
1570
+ }
1571
+ };
1572
+ }
1573
+ function or(guards) {
1574
+ return {
1575
+ type: 'xstate.boolean',
1576
+ params: {
1577
+ op: 'or'
1578
+ },
1579
+ children: guards.map(guard => toGuardDefinition(guard)),
1580
+ predicate: ({
1581
+ evaluate,
1582
+ guard,
1583
+ context,
1584
+ event,
1585
+ state
1586
+ }) => {
1587
+ return guard.children.some(childGuard => {
1588
+ return evaluate(childGuard, context, event, state);
1589
+ });
1590
+ }
1591
+ };
1592
+ }
1593
+ function evaluateGuard(guard, context, event, state) {
1594
+ const {
1595
+ machine
1596
+ } = state;
1597
+ const predicate = machine?.options?.guards?.[guard.type] ?? guard.predicate;
1598
+ if (!predicate) {
1599
+ throw new Error(`Guard '${guard.type}' is not implemented.'.`);
1600
+ }
1601
+ return predicate({
1602
+ context,
1603
+ event,
1604
+ state,
1605
+ guard,
1606
+ evaluate: evaluateGuard
1607
+ });
1608
+ }
1609
+ function toGuardDefinition(guardConfig, getPredicate) {
1610
+ if (isString(guardConfig)) {
1611
+ return {
1612
+ type: guardConfig,
1613
+ predicate: getPredicate?.(guardConfig) || undefined,
1614
+ params: {
1615
+ type: guardConfig
1616
+ }
1617
+ };
1618
+ }
1619
+ if (isFunction(guardConfig)) {
1620
+ return {
1621
+ type: guardConfig.name,
1622
+ predicate: guardConfig,
1623
+ params: {
1624
+ type: guardConfig.name,
1625
+ name: guardConfig.name
1626
+ }
1627
+ };
1628
+ }
1629
+ return {
1630
+ type: guardConfig.type,
1631
+ params: guardConfig.params || guardConfig,
1632
+ children: guardConfig.children?.map(childGuard => toGuardDefinition(childGuard, getPredicate)),
1633
+ predicate: getPredicate?.(guardConfig.type) || guardConfig.predicate
1634
+ };
1635
+ }
1636
+
1637
+ function getOutput(configuration, context, event) {
1638
+ const machine = configuration[0].machine;
1639
+ const finalChildStateNode = configuration.find(stateNode => stateNode.type === 'final' && stateNode.parent === machine.root);
1640
+ return finalChildStateNode && finalChildStateNode.output ? mapContext(finalChildStateNode.output, context, event) : undefined;
1641
+ }
1642
+ const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1643
+ function getChildren(stateNode) {
1644
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1645
+ }
1646
+ function getProperAncestors(stateNode, toStateNode) {
1647
+ const ancestors = [];
1648
+
1649
+ // add all ancestors
1650
+ let m = stateNode.parent;
1651
+ while (m && m !== toStateNode) {
1652
+ ancestors.push(m);
1653
+ m = m.parent;
1654
+ }
1655
+ return ancestors;
1656
+ }
1657
+ function getConfiguration(stateNodes) {
1658
+ const configuration = new Set(stateNodes);
1659
+ const configurationSet = new Set(stateNodes);
1660
+ const adjList = getAdjList(configurationSet);
1661
+
1662
+ // add descendants
1663
+ for (const s of configuration) {
1664
+ // if previously active, add existing child nodes
1665
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1666
+ getInitialStateNodes(s).forEach(sn => configurationSet.add(sn));
1667
+ } else {
1668
+ if (s.type === 'parallel') {
1669
+ for (const child of getChildren(s)) {
1670
+ if (child.type === 'history') {
1671
+ continue;
1672
+ }
1673
+ if (!configurationSet.has(child)) {
1674
+ for (const initialStateNode of getInitialStateNodes(child)) {
1675
+ configurationSet.add(initialStateNode);
1676
+ }
1677
+ }
1678
+ }
1679
+ }
1680
+ }
1681
+ }
1682
+
1683
+ // add all ancestors
1684
+ for (const s of configurationSet) {
1685
+ let m = s.parent;
1686
+ while (m) {
1687
+ configurationSet.add(m);
1688
+ m = m.parent;
1689
+ }
1690
+ }
1691
+ return configurationSet;
1692
+ }
1693
+ function getValueFromAdj(baseNode, adjList) {
1694
+ const childStateNodes = adjList.get(baseNode);
1695
+ if (!childStateNodes) {
1696
+ return {}; // todo: fix?
1697
+ }
1698
+
1699
+ if (baseNode.type === 'compound') {
1700
+ const childStateNode = childStateNodes[0];
1701
+ if (childStateNode) {
1702
+ if (isAtomicStateNode(childStateNode)) {
1703
+ return childStateNode.key;
1704
+ }
1705
+ } else {
1706
+ return {};
1707
+ }
1708
+ }
1709
+ const stateValue = {};
1710
+ for (const childStateNode of childStateNodes) {
1711
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1712
+ }
1713
+ return stateValue;
1714
+ }
1715
+ function getAdjList(configuration) {
1716
+ const adjList = new Map();
1717
+ for (const s of configuration) {
1718
+ if (!adjList.has(s)) {
1719
+ adjList.set(s, []);
1720
+ }
1721
+ if (s.parent) {
1722
+ if (!adjList.has(s.parent)) {
1723
+ adjList.set(s.parent, []);
1724
+ }
1725
+ adjList.get(s.parent).push(s);
1726
+ }
1727
+ }
1728
+ return adjList;
1729
+ }
1730
+ function getStateValue(rootNode, configuration) {
1731
+ const config = getConfiguration(configuration);
1732
+ return getValueFromAdj(rootNode, getAdjList(config));
1733
+ }
1734
+ function isInFinalState(configuration, stateNode = configuration[0].machine.root) {
1735
+ if (stateNode.type === 'compound') {
1736
+ return getChildren(stateNode).some(s => s.type === 'final' && configuration.includes(s));
1737
+ }
1738
+ if (stateNode.type === 'parallel') {
1739
+ return getChildren(stateNode).every(sn => isInFinalState(configuration, sn));
1740
+ }
1741
+ return false;
1742
+ }
1743
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
1744
+ function getCandidates(stateNode, receivedEventType) {
1745
+ const candidates = stateNode.transitions.filter(transition => {
1746
+ const {
1747
+ eventType
1748
+ } = transition;
1749
+ // First, check the trivial case: event names are exactly equal
1750
+ if (eventType === receivedEventType) {
1751
+ return true;
1752
+ }
1753
+
1754
+ // Then, check if transition is a wildcard transition,
1755
+ // which matches any non-transient events
1756
+ if (eventType === WILDCARD) {
1757
+ return true;
1758
+ }
1759
+ if (!eventType.endsWith('.*')) {
1760
+ return false;
1761
+ }
1762
+ if (/.*\*.+/.test(eventType)) {
1763
+ console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${eventType}" event.`);
1764
+ }
1765
+ const partialEventTokens = eventType.split('.');
1766
+ const eventTokens = receivedEventType.split('.');
1767
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1768
+ const partialEventToken = partialEventTokens[tokenIndex];
1769
+ const eventToken = eventTokens[tokenIndex];
1770
+ if (partialEventToken === '*') {
1771
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
1772
+ if (!isLastToken) {
1773
+ console.warn(`Infix wildcards in transition events are not allowed. Check the "${eventType}" event.`);
1774
+ }
1775
+ return isLastToken;
1776
+ }
1777
+ if (partialEventToken !== eventToken) {
1778
+ return false;
1779
+ }
1780
+ }
1781
+ return true;
1782
+ });
1783
+ return candidates;
1784
+ }
1785
+
1786
+ /**
1787
+ * All delayed transitions from the config.
1788
+ */
1789
+ function getDelayedTransitions(stateNode) {
1790
+ const afterConfig = stateNode.config.after;
1791
+ if (!afterConfig) {
1792
+ return [];
1793
+ }
1794
+ const mutateEntryExit = (delay, i) => {
1795
+ const delayRef = isFunction(delay) ? `${stateNode.id}:delay[${i}]` : delay;
1796
+ const eventType = after(delayRef, stateNode.id);
1797
+ stateNode.entry.push(raise({
1798
+ type: eventType
1799
+ }, {
1800
+ delay
1801
+ }));
1802
+ stateNode.exit.push(cancel(eventType));
1803
+ return eventType;
1804
+ };
1805
+ const delayedTransitions = isArray(afterConfig) ? afterConfig.map((transition, i) => {
1806
+ const eventType = mutateEntryExit(transition.delay, i);
1807
+ return {
1808
+ ...transition,
1809
+ event: eventType
1810
+ };
1811
+ }) : Object.keys(afterConfig).flatMap((delay, i) => {
1812
+ const configTransition = afterConfig[delay];
1813
+ const resolvedTransition = isString(configTransition) ? {
1814
+ target: configTransition
1815
+ } : configTransition;
1816
+ const resolvedDelay = !isNaN(+delay) ? +delay : delay;
1817
+ const eventType = mutateEntryExit(resolvedDelay, i);
1818
+ return toArray(resolvedTransition).map(transition => ({
1819
+ ...transition,
1820
+ event: eventType,
1821
+ delay: resolvedDelay
1822
+ }));
1823
+ });
1824
+ return delayedTransitions.map(delayedTransition => {
1825
+ const {
1826
+ delay
1827
+ } = delayedTransition;
1828
+ return {
1829
+ ...formatTransition(stateNode, delayedTransition),
1830
+ delay
1831
+ };
1832
+ });
1833
+ }
1834
+ function formatTransition(stateNode, transitionConfig) {
1835
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1836
+ const reenter = transitionConfig.reenter ?? false;
1837
+ const {
1838
+ guards
1839
+ } = stateNode.machine.options;
1840
+ const target = resolveTarget(stateNode, normalizedTarget);
1841
+
1842
+ // TODO: should this be part of a lint rule instead?
1843
+ if (transitionConfig.cond) {
1844
+ throw new Error(`State "${stateNode.id}" has declared \`cond\` for one of its transitions. This property has been renamed to \`guard\`. Please update your code.`);
1845
+ }
1846
+ const transition = {
1847
+ ...transitionConfig,
1848
+ actions: toActionObjects(toArray(transitionConfig.actions)),
1849
+ guard: transitionConfig.guard ? toGuardDefinition(transitionConfig.guard, guardType => guards[guardType]) : undefined,
1850
+ target,
1851
+ source: stateNode,
1852
+ reenter,
1853
+ eventType: transitionConfig.event,
1854
+ toJSON: () => ({
1855
+ ...transition,
1856
+ source: `#${stateNode.id}`,
1857
+ target: target ? target.map(t => `#${t.id}`) : undefined
1858
+ })
1859
+ };
1860
+ return transition;
1861
+ }
1862
+ function formatTransitions(stateNode) {
1863
+ const transitionConfigs = [];
1864
+ if (Array.isArray(stateNode.config.on)) {
1865
+ transitionConfigs.push(...stateNode.config.on);
1866
+ } else if (stateNode.config.on) {
1867
+ const {
1868
+ [WILDCARD]: wildcardConfigs = [],
1869
+ ...namedTransitionConfigs
1870
+ } = stateNode.config.on;
1871
+ for (const eventType of Object.keys(namedTransitionConfigs)) {
1872
+ if (eventType === NULL_EVENT) {
1873
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1874
+ }
1875
+ const eventTransitionConfigs = toTransitionConfigArray(eventType, namedTransitionConfigs[eventType]);
1876
+ transitionConfigs.push(...eventTransitionConfigs);
1877
+ // TODO: add dev-mode validation for unreachable transitions
1878
+ }
1879
+
1880
+ transitionConfigs.push(...toTransitionConfigArray(WILDCARD, wildcardConfigs));
1881
+ }
1882
+ const doneConfig = stateNode.config.onDone ? toTransitionConfigArray(String(done(stateNode.id)), stateNode.config.onDone) : [];
1883
+ const invokeConfig = stateNode.invoke.flatMap(invokeDef => {
1884
+ const settleTransitions = [];
1885
+ if (invokeDef.onDone) {
1886
+ settleTransitions.push(...toTransitionConfigArray(`done.invoke.${invokeDef.id}`, invokeDef.onDone));
1887
+ }
1888
+ if (invokeDef.onError) {
1889
+ settleTransitions.push(...toTransitionConfigArray(`error.platform.${invokeDef.id}`, invokeDef.onError));
1890
+ }
1891
+ if (invokeDef.onSnapshot) {
1892
+ settleTransitions.push(...toTransitionConfigArray(`xstate.snapshot.${invokeDef.id}`, invokeDef.onSnapshot));
1893
+ }
1894
+ return settleTransitions;
1895
+ });
1896
+ const delayedTransitions = stateNode.after;
1897
+ const formattedTransitions = [...doneConfig, ...invokeConfig, ...transitionConfigs].flatMap(transitionConfig => toArray(transitionConfig).map(transition => formatTransition(stateNode, transition)));
1898
+ for (const delayedTransition of delayedTransitions) {
1899
+ formattedTransitions.push(delayedTransition);
1900
+ }
1901
+ return formattedTransitions;
1902
+ }
1903
+ function formatInitialTransition(stateNode, _target) {
1904
+ if (isString(_target) || isArray(_target)) {
1905
+ const targets = toArray(_target).map(t => {
1906
+ // Resolve state string keys (which represent children)
1907
+ // to their state node
1908
+ const descStateNode = isString(t) ? isStateId(t) ? stateNode.machine.getStateNodeById(t) : stateNode.states[t] : t;
1909
+ if (!descStateNode) {
1910
+ throw new Error(`Initial state node "${t}" not found on parent state node #${stateNode.id}`);
1911
+ }
1912
+ if (!isDescendant(descStateNode, stateNode)) {
1913
+ throw new Error(`Invalid initial target: state node #${descStateNode.id} is not a descendant of #${stateNode.id}`);
1914
+ }
1915
+ return descStateNode;
1916
+ });
1917
+ const resolvedTarget = resolveTarget(stateNode, targets);
1918
+ const transition = {
1919
+ source: stateNode,
1920
+ actions: [],
1921
+ eventType: null,
1922
+ reenter: false,
1923
+ target: resolvedTarget,
1924
+ toJSON: () => ({
1925
+ ...transition,
1926
+ source: `#${stateNode.id}`,
1927
+ target: resolvedTarget ? resolvedTarget.map(t => `#${t.id}`) : undefined
1928
+ })
1929
+ };
1930
+ return transition;
1931
+ }
1932
+ return formatTransition(stateNode, {
1933
+ target: toArray(_target.target).map(t => {
1934
+ if (isString(t)) {
1935
+ return isStateId(t) ? t : `${stateNode.machine.delimiter}${t}`;
1936
+ }
1937
+ return t;
1938
+ }),
1939
+ actions: _target.actions,
1940
+ event: null
1941
+ });
1942
+ }
1943
+ function resolveTarget(stateNode, targets) {
1944
+ if (targets === undefined) {
1945
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1946
+ return undefined;
1947
+ }
1948
+ return targets.map(target => {
1949
+ if (!isString(target)) {
1950
+ return target;
1951
+ }
1952
+ if (isStateId(target)) {
1953
+ return stateNode.machine.getStateNodeById(target);
1954
+ }
1955
+ const isInternalTarget = target[0] === stateNode.machine.delimiter;
1956
+ // If internal target is defined on machine,
1957
+ // do not include machine key on target
1958
+ if (isInternalTarget && !stateNode.parent) {
1959
+ return getStateNodeByPath(stateNode, target.slice(1));
1960
+ }
1961
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1962
+ if (stateNode.parent) {
1963
+ try {
1964
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1965
+ return targetStateNode;
1966
+ } catch (err) {
1967
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1968
+ }
1969
+ } else {
1970
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1971
+ }
1972
+ });
1973
+ }
1974
+ function resolveHistoryTarget(stateNode) {
1975
+ const normalizedTarget = normalizeTarget(stateNode.target);
1976
+ if (!normalizedTarget) {
1977
+ return stateNode.parent.initial.target;
1978
+ }
1979
+ return normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t);
1980
+ }
1981
+ function isHistoryNode(stateNode) {
1982
+ return stateNode.type === 'history';
1983
+ }
1984
+ function getInitialStateNodes(stateNode) {
1985
+ const set = new Set();
1986
+ function iter(descStateNode) {
1987
+ if (set.has(descStateNode)) {
1988
+ return;
1989
+ }
1990
+ set.add(descStateNode);
1991
+ if (descStateNode.type === 'compound') {
1992
+ for (const targetStateNode of descStateNode.initial.target) {
1993
+ for (const a of getProperAncestors(targetStateNode, stateNode)) {
1994
+ set.add(a);
1995
+ }
1996
+ iter(targetStateNode);
1997
+ }
1998
+ } else if (descStateNode.type === 'parallel') {
1999
+ for (const child of getChildren(descStateNode)) {
2000
+ iter(child);
2001
+ }
2002
+ }
2003
+ }
2004
+ iter(stateNode);
2005
+ return [...set];
2006
+ }
2007
+ /**
2008
+ * Returns the child state node from its relative `stateKey`, or throws.
2009
+ */
2010
+ function getStateNode(stateNode, stateKey) {
2011
+ if (isStateId(stateKey)) {
2012
+ return stateNode.machine.getStateNodeById(stateKey);
2013
+ }
2014
+ if (!stateNode.states) {
2015
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
2016
+ }
2017
+ const result = stateNode.states[stateKey];
2018
+ if (!result) {
2019
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
2020
+ }
2021
+ return result;
2022
+ }
2023
+
2024
+ /**
2025
+ * Returns the relative state node from the given `statePath`, or throws.
2026
+ *
2027
+ * @param statePath The string or string array relative path to the state node.
2028
+ */
2029
+ function getStateNodeByPath(stateNode, statePath) {
2030
+ if (typeof statePath === 'string' && isStateId(statePath)) {
2031
+ try {
2032
+ return stateNode.machine.getStateNodeById(statePath);
2033
+ } catch (e) {
2034
+ // try individual paths
2035
+ // throw e;
2036
+ }
2037
+ }
2038
+ const arrayStatePath = toStatePath(statePath, stateNode.machine.delimiter).slice();
2039
+ let currentStateNode = stateNode;
2040
+ while (arrayStatePath.length) {
2041
+ const key = arrayStatePath.shift();
2042
+ if (!key.length) {
2043
+ break;
2044
+ }
2045
+ currentStateNode = getStateNode(currentStateNode, key);
2046
+ }
2047
+ return currentStateNode;
2048
+ }
2049
+
2050
+ /**
2051
+ * Returns the state nodes represented by the current state value.
2052
+ *
2053
+ * @param state The state value or State instance
2054
+ */
2055
+ function getStateNodes(stateNode, state) {
2056
+ const stateValue = state instanceof State ? state.value : toStateValue(state, stateNode.machine.delimiter);
2057
+ if (isString(stateValue)) {
2058
+ return [stateNode, stateNode.states[stateValue]];
2059
+ }
2060
+ const childStateKeys = Object.keys(stateValue);
2061
+ const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
2062
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
2063
+ const subStateNode = getStateNode(stateNode, subStateKey);
2064
+ if (!subStateNode) {
2065
+ return allSubStateNodes;
2066
+ }
2067
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
2068
+ return allSubStateNodes.concat(subStateNodes);
2069
+ }, []));
2070
+ }
2071
+ function transitionAtomicNode(stateNode, stateValue, state, event) {
2072
+ const childStateNode = getStateNode(stateNode, stateValue);
2073
+ const next = childStateNode.next(state, event);
2074
+ if (!next || !next.length) {
2075
+ return stateNode.next(state, event);
2076
+ }
2077
+ return next;
2078
+ }
2079
+ function transitionCompoundNode(stateNode, stateValue, state, event) {
2080
+ const subStateKeys = Object.keys(stateValue);
2081
+ const childStateNode = getStateNode(stateNode, subStateKeys[0]);
2082
+ const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], state, event);
2083
+ if (!next || !next.length) {
2084
+ return stateNode.next(state, event);
2085
+ }
2086
+ return next;
2087
+ }
2088
+ function transitionParallelNode(stateNode, stateValue, state, event) {
2089
+ const allInnerTransitions = [];
2090
+ for (const subStateKey of Object.keys(stateValue)) {
2091
+ const subStateValue = stateValue[subStateKey];
2092
+ if (!subStateValue) {
2093
+ continue;
2094
+ }
2095
+ const subStateNode = getStateNode(stateNode, subStateKey);
2096
+ const innerTransitions = transitionNode(subStateNode, subStateValue, state, event);
2097
+ if (innerTransitions) {
2098
+ allInnerTransitions.push(...innerTransitions);
2099
+ }
2100
+ }
2101
+ if (!allInnerTransitions.length) {
2102
+ return stateNode.next(state, event);
2103
+ }
2104
+ return allInnerTransitions;
2105
+ }
2106
+ function transitionNode(stateNode, stateValue, state, event) {
2107
+ // leaf node
2108
+ if (isString(stateValue)) {
2109
+ return transitionAtomicNode(stateNode, stateValue, state, event);
2110
+ }
2111
+
2112
+ // compound node
2113
+ if (Object.keys(stateValue).length === 1) {
2114
+ return transitionCompoundNode(stateNode, stateValue, state, event);
2115
+ }
2116
+
2117
+ // parallel node
2118
+ return transitionParallelNode(stateNode, stateValue, state, event);
2119
+ }
2120
+ function getHistoryNodes(stateNode) {
2121
+ return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
2122
+ }
2123
+ function isDescendant(childStateNode, parentStateNode) {
2124
+ let marker = childStateNode;
2125
+ while (marker.parent && marker.parent !== parentStateNode) {
2126
+ marker = marker.parent;
2127
+ }
2128
+ return marker.parent === parentStateNode;
2129
+ }
2130
+ function getPathFromRootToNode(stateNode) {
2131
+ const path = [];
2132
+ let marker = stateNode.parent;
2133
+ while (marker) {
2134
+ path.unshift(marker);
2135
+ marker = marker.parent;
2136
+ }
2137
+ return path;
2138
+ }
2139
+ function hasIntersection(s1, s2) {
2140
+ const set1 = new Set(s1);
2141
+ const set2 = new Set(s2);
2142
+ for (const item of set1) {
2143
+ if (set2.has(item)) {
2144
+ return true;
2145
+ }
2146
+ }
2147
+ for (const item of set2) {
2148
+ if (set1.has(item)) {
2149
+ return true;
2150
+ }
2151
+ }
2152
+ return false;
2153
+ }
2154
+ function removeConflictingTransitions(enabledTransitions, configuration, historyValue) {
2155
+ const filteredTransitions = new Set();
2156
+ for (const t1 of enabledTransitions) {
2157
+ let t1Preempted = false;
2158
+ const transitionsToRemove = new Set();
2159
+ for (const t2 of filteredTransitions) {
2160
+ if (hasIntersection(computeExitSet([t1], configuration, historyValue), computeExitSet([t2], configuration, historyValue))) {
2161
+ if (isDescendant(t1.source, t2.source)) {
2162
+ transitionsToRemove.add(t2);
2163
+ } else {
2164
+ t1Preempted = true;
2165
+ break;
2166
+ }
2167
+ }
2168
+ }
2169
+ if (!t1Preempted) {
2170
+ for (const t3 of transitionsToRemove) {
2171
+ filteredTransitions.delete(t3);
2172
+ }
2173
+ filteredTransitions.add(t1);
2174
+ }
2175
+ }
2176
+ return Array.from(filteredTransitions);
2177
+ }
2178
+ function findLCCA(stateNodes) {
2179
+ const [head] = stateNodes;
2180
+ let current = getPathFromRootToNode(head);
2181
+ let candidates = [];
2182
+ for (const stateNode of stateNodes) {
2183
+ const path = getPathFromRootToNode(stateNode);
2184
+ candidates = current.filter(sn => path.includes(sn));
2185
+ current = candidates;
2186
+ candidates = [];
2187
+ }
2188
+ return current[current.length - 1];
2189
+ }
2190
+ function getEffectiveTargetStates(transition, historyValue) {
2191
+ if (!transition.target) {
2192
+ return [];
2193
+ }
2194
+ const targets = new Set();
2195
+ for (const targetNode of transition.target) {
2196
+ if (isHistoryNode(targetNode)) {
2197
+ if (historyValue[targetNode.id]) {
2198
+ for (const node of historyValue[targetNode.id]) {
2199
+ targets.add(node);
2200
+ }
2201
+ } else {
2202
+ for (const node of getEffectiveTargetStates({
2203
+ target: resolveHistoryTarget(targetNode)
2204
+ }, historyValue)) {
2205
+ targets.add(node);
2206
+ }
2207
+ }
2208
+ } else {
2209
+ targets.add(targetNode);
2210
+ }
2211
+ }
2212
+ return [...targets];
2213
+ }
2214
+ function getTransitionDomain(transition, historyValue) {
2215
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
2216
+ if (!targetStates) {
2217
+ return null;
2218
+ }
2219
+ if (!transition.reenter && transition.source.type !== 'parallel' && targetStates.every(targetStateNode => isDescendant(targetStateNode, transition.source))) {
2220
+ return transition.source;
2221
+ }
2222
+ const lcca = findLCCA(targetStates.concat(transition.source));
2223
+ return lcca;
2224
+ }
2225
+ function computeExitSet(transitions, configuration, historyValue) {
2226
+ const statesToExit = new Set();
2227
+ for (const t of transitions) {
2228
+ if (t.target?.length) {
2229
+ const domain = getTransitionDomain(t, historyValue);
2230
+ for (const stateNode of configuration) {
2231
+ if (isDescendant(stateNode, domain)) {
2232
+ statesToExit.add(stateNode);
2233
+ }
2234
+ }
2235
+ }
2236
+ }
2237
+ return [...statesToExit];
2238
+ }
2239
+
2240
+ /**
2241
+ * https://www.w3.org/TR/scxml/#microstepProcedure
2242
+ *
2243
+ * @private
2244
+ * @param transitions
2245
+ * @param currentState
2246
+ * @param mutConfiguration
2247
+ */
2248
+
2249
+ function microstep(transitions, currentState, actorCtx, event) {
2250
+ const {
2251
+ machine
2252
+ } = currentState;
2253
+ // Transition will "apply" if:
2254
+ // - the state node is the initial state (there is no current state)
2255
+ // - OR there are transitions
2256
+ const willTransition = currentState._initial || transitions.length > 0;
2257
+ const mutConfiguration = new Set(currentState.configuration);
2258
+ if (!currentState._initial && !willTransition) {
2259
+ const inertState = cloneState(currentState, {
2260
+ event,
2261
+ actions: [],
2262
+ transitions: []
2263
+ });
2264
+ inertState.changed = false;
2265
+ return inertState;
2266
+ }
2267
+ const microstate = microstepProcedure(currentState._initial ? [{
2268
+ target: [...currentState.configuration].filter(isAtomicStateNode),
2269
+ source: machine.root,
2270
+ reenter: true,
2271
+ actions: [],
2272
+ eventType: null,
2273
+ toJSON: null // TODO: fix
2274
+ }] : transitions, currentState, mutConfiguration, event, actorCtx);
2275
+ const {
2276
+ context,
2277
+ actions: nonRaisedActions
2278
+ } = microstate;
2279
+ const children = setChildren(currentState, nonRaisedActions);
2280
+ const nextState = cloneState(microstate, {
2281
+ value: {},
2282
+ // TODO: make optional
2283
+ transitions,
2284
+ children
2285
+ });
2286
+ nextState.changed = currentState._initial ? undefined : !stateValuesEqual(nextState.value, currentState.value) || nextState.actions.length > 0 || context !== currentState.context;
2287
+ return nextState;
2288
+ }
2289
+ function setChildren(currentState, nonRaisedActions) {
2290
+ const children = {
2291
+ ...currentState.children
2292
+ };
2293
+ for (const action of nonRaisedActions) {
2294
+ if (action.type === invoke$1 && action.params.ref) {
2295
+ const ref = action.params.ref;
2296
+ if (ref) {
2297
+ children[ref.id] = ref;
2298
+ }
2299
+ } else if (action.type === stop$1) {
2300
+ const ref = action.params.actor;
2301
+ if (ref) {
2302
+ delete children[ref.id];
2303
+ }
2304
+ }
2305
+ }
2306
+ return children;
2307
+ }
2308
+ function microstepProcedure(transitions, currentState, mutConfiguration, event, actorCtx) {
2309
+ const actions = [];
2310
+ const historyValue = {
2311
+ ...currentState.historyValue
2312
+ };
2313
+ const filteredTransitions = removeConflictingTransitions(transitions, mutConfiguration, historyValue);
2314
+ const internalQueue = [...currentState._internalQueue];
2315
+
2316
+ // Exit states
2317
+ if (!currentState._initial) {
2318
+ exitStates(filteredTransitions, mutConfiguration, historyValue, actions);
2319
+ }
2320
+
2321
+ // Execute transition content
2322
+ actions.push(...filteredTransitions.flatMap(t => t.actions));
2323
+
2324
+ // Enter states
2325
+ enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue);
2326
+ const nextConfiguration = [...mutConfiguration];
2327
+ const done = isInFinalState(nextConfiguration);
2328
+ if (done) {
2329
+ const finalActions = nextConfiguration.sort((a, b) => b.order - a.order).flatMap(state => state.exit);
2330
+ actions.push(...finalActions);
2331
+ }
2332
+ try {
2333
+ const {
2334
+ nextState
2335
+ } = resolveActionsAndContext(actions, event, currentState, actorCtx);
2336
+ const output = done ? getOutput(nextConfiguration, nextState.context, event) : undefined;
2337
+ internalQueue.push(...nextState._internalQueue);
2338
+ return cloneState(currentState, {
2339
+ actions: nextState.actions,
2340
+ configuration: nextConfiguration,
2341
+ historyValue,
2342
+ _internalQueue: internalQueue,
2343
+ context: nextState.context,
2344
+ event,
2345
+ done,
2346
+ output,
2347
+ children: nextState.children
2348
+ });
2349
+ } catch (e) {
2350
+ // TODO: Refactor this once proper error handling is implemented.
2351
+ // See https://github.com/statelyai/rfcs/pull/4
2352
+ throw e;
2353
+ }
2354
+ }
2355
+ function enterStates(filteredTransitions, mutConfiguration, actions, internalQueue, currentState, historyValue) {
2356
+ const statesToEnter = new Set();
2357
+ const statesForDefaultEntry = new Set();
2358
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2359
+
2360
+ // In the initial state, the root state node is "entered".
2361
+ if (currentState._initial) {
2362
+ statesForDefaultEntry.add(currentState.machine.root);
2363
+ }
2364
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2365
+ mutConfiguration.add(stateNodeToEnter);
2366
+ for (const invokeDef of stateNodeToEnter.invoke) {
2367
+ actions.push(invoke(invokeDef));
2368
+ }
2369
+
2370
+ // Add entry actions
2371
+ actions.push(...stateNodeToEnter.entry);
2372
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
2373
+ for (const stateNode of statesForDefaultEntry) {
2374
+ const initialActions = stateNode.initial.actions;
2375
+ actions.push(...initialActions);
2376
+ }
2377
+ }
2378
+ if (stateNodeToEnter.type === 'final') {
2379
+ const parent = stateNodeToEnter.parent;
2380
+ if (!parent.parent) {
2381
+ continue;
2382
+ }
2383
+ internalQueue.push(done(parent.id, stateNodeToEnter.output ? mapContext(stateNodeToEnter.output, currentState.context, currentState.event) : undefined));
2384
+ if (parent.parent) {
2385
+ const grandparent = parent.parent;
2386
+ if (grandparent.type === 'parallel') {
2387
+ if (getChildren(grandparent).every(parentNode => isInFinalState([...mutConfiguration], parentNode))) {
2388
+ internalQueue.push(done(grandparent.id));
2389
+ }
2390
+ }
2391
+ }
2392
+ }
2393
+ }
2394
+ }
2395
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
2396
+ for (const t of transitions) {
2397
+ for (const s of t.target || []) {
2398
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2399
+ }
2400
+ const ancestor = getTransitionDomain(t, historyValue);
2401
+ const targetStates = getEffectiveTargetStates(t, historyValue);
2402
+ for (const s of targetStates) {
2403
+ addAncestorStatesToEnter(s, ancestor, statesToEnter, historyValue, statesForDefaultEntry);
2404
+ }
2405
+ }
2406
+ }
2407
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
2408
+ if (isHistoryNode(stateNode)) {
2409
+ if (historyValue[stateNode.id]) {
2410
+ const historyStateNodes = historyValue[stateNode.id];
2411
+ for (const s of historyStateNodes) {
2412
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2413
+ }
2414
+ for (const s of historyStateNodes) {
2415
+ addAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2416
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
2417
+ statesForDefaultEntry.add(stateForDefaultEntry);
2418
+ }
2419
+ }
2420
+ } else {
2421
+ const targets = resolveHistoryTarget(stateNode);
2422
+ for (const s of targets) {
2423
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2424
+ }
2425
+ for (const s of targets) {
2426
+ addAncestorStatesToEnter(s, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2427
+ for (const stateForDefaultEntry of statesForDefaultEntry) {
2428
+ statesForDefaultEntry.add(stateForDefaultEntry);
2429
+ }
2430
+ }
2431
+ }
2432
+ } else {
2433
+ statesToEnter.add(stateNode);
2434
+ if (stateNode.type === 'compound') {
2435
+ statesForDefaultEntry.add(stateNode);
2436
+ const initialStates = stateNode.initial.target;
2437
+ for (const initialState of initialStates) {
2438
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
2439
+ }
2440
+ for (const initialState of initialStates) {
2441
+ addAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2442
+ }
2443
+ } else {
2444
+ if (stateNode.type === 'parallel') {
2445
+ for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
2446
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2447
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2448
+ }
2449
+ }
2450
+ }
2451
+ }
2452
+ }
2453
+ }
2454
+ function addAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
2455
+ const properAncestors = getProperAncestors(stateNode, toStateNode);
2456
+ for (const anc of properAncestors) {
2457
+ statesToEnter.add(anc);
2458
+ if (anc.type === 'parallel') {
2459
+ for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
2460
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2461
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2462
+ }
2463
+ }
2464
+ }
2465
+ }
2466
+ }
2467
+ function exitStates(transitions, mutConfiguration, historyValue, actions) {
2468
+ const statesToExit = computeExitSet(transitions, mutConfiguration, historyValue);
2469
+ statesToExit.sort((a, b) => b.order - a.order);
2470
+
2471
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2472
+ for (const exitStateNode of statesToExit) {
2473
+ for (const historyNode of getHistoryNodes(exitStateNode)) {
2474
+ let predicate;
2475
+ if (historyNode.history === 'deep') {
2476
+ predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2477
+ } else {
2478
+ predicate = sn => {
2479
+ return sn.parent === exitStateNode;
2480
+ };
2481
+ }
2482
+ historyValue[historyNode.id] = Array.from(mutConfiguration).filter(predicate);
2483
+ }
2484
+ }
2485
+ for (const s of statesToExit) {
2486
+ actions.push(...s.exit.flat(), ...s.invoke.map(def => stop(def.id)));
2487
+ mutConfiguration.delete(s);
2488
+ }
2489
+ }
2490
+ function resolveActionsAndContext(actions, event, currentState, actorCtx) {
2491
+ const {
2492
+ machine
2493
+ } = currentState;
2494
+ const resolvedActions = [];
2495
+ const raiseActions = [];
2496
+ let intermediateState = currentState;
2497
+ function handleAction(action) {
2498
+ resolvedActions.push(action);
2499
+ if (actorCtx?.self.status === ActorStatus.Running) {
2500
+ action.execute?.(actorCtx);
2501
+ // TODO: this is hacky; re-evaluate
2502
+ delete action.execute;
2503
+ }
2504
+ }
2505
+ function resolveAction(actionObject) {
2506
+ const executableActionObject = resolveActionObject(actionObject, machine.options.actions);
2507
+ if (isDynamicAction(executableActionObject)) {
2508
+ const [nextState, resolvedAction] = executableActionObject.resolve(event, {
2509
+ state: intermediateState,
2510
+ action: actionObject,
2511
+ actorContext: actorCtx
2512
+ });
2513
+ const matchedActions = resolvedAction.params?.actions;
2514
+ intermediateState = nextState;
2515
+ if ((resolvedAction.type === raise$1 || resolvedAction.type === send$1 && resolvedAction.params.internal) && typeof resolvedAction.params.delay !== 'number') {
2516
+ raiseActions.push(resolvedAction);
2517
+ }
2518
+
2519
+ // TODO: remove the check; just handleAction
2520
+ if (resolvedAction.type !== pure$1) {
2521
+ handleAction(resolvedAction);
2522
+ }
2523
+ toActionObjects(matchedActions).forEach(resolveAction);
2524
+ return;
2525
+ }
2526
+ handleAction(executableActionObject);
2527
+ }
2528
+ for (const actionObject of actions) {
2529
+ resolveAction(actionObject);
2530
+ }
2531
+ return {
2532
+ nextState: cloneState(intermediateState, {
2533
+ actions: resolvedActions,
2534
+ _internalQueue: raiseActions.map(a => a.params.event)
2535
+ })
2536
+ };
2537
+ }
2538
+ function macrostep(state, event, actorCtx) {
2539
+ if (event.type === WILDCARD) {
2540
+ throw new Error(`An event cannot have the wildcard type ('${WILDCARD}')`);
2541
+ }
2542
+ let nextState = state;
2543
+ const states = [];
2544
+
2545
+ // Handle stop event
2546
+ if (event.type === stopSignalType) {
2547
+ nextState = stopStep(event, nextState, actorCtx);
2548
+ states.push(nextState);
2549
+ return {
2550
+ state: nextState,
2551
+ microstates: states
2552
+ };
2553
+ }
2554
+
2555
+ // Assume the state is at rest (no raised events)
2556
+ // Determine the next state based on the next microstep
2557
+ if (event.type !== init) {
2558
+ const transitions = selectTransitions(event, nextState);
2559
+ nextState = microstep(transitions, state, actorCtx, event);
2560
+ states.push(nextState);
2561
+ }
2562
+ while (!nextState.done) {
2563
+ let enabledTransitions = selectEventlessTransitions(nextState);
2564
+ if (enabledTransitions.length === 0) {
2565
+ // TODO: this is a bit of a hack, we need to review this
2566
+ // this matches the behavior from v4 for eventless transitions
2567
+ // where for `hasAlwaysTransitions` we were always trying to resolve with a NULL event
2568
+ // and if a transition was not selected the `state.transitions` stayed empty
2569
+ // without this we get into an infinite loop in the dieHard test in `@xstate/test` for the `simplePathsTo`
2570
+ if (nextState.configuration.some(state => state.always)) {
2571
+ nextState.transitions = [];
2572
+ }
2573
+ if (!nextState._internalQueue.length) {
2574
+ break;
2575
+ } else {
2576
+ const currentActions = nextState.actions;
2577
+ const nextEvent = nextState._internalQueue[0];
2578
+ const transitions = selectTransitions(nextEvent, nextState);
2579
+ nextState = microstep(transitions, nextState, actorCtx, nextEvent);
2580
+ nextState._internalQueue.shift();
2581
+ nextState.actions.unshift(...currentActions);
2582
+ states.push(nextState);
2583
+ }
2584
+ }
2585
+ if (enabledTransitions.length) {
2586
+ const currentActions = nextState.actions;
2587
+ nextState = microstep(enabledTransitions, nextState, actorCtx, nextState.event);
2588
+ nextState.actions.unshift(...currentActions);
2589
+ states.push(nextState);
2590
+ }
2591
+ }
2592
+ if (nextState.done) {
2593
+ // Perform the stop step to ensure that child actors are stopped
2594
+ stopStep(nextState.event, nextState, actorCtx);
2595
+ }
2596
+ return {
2597
+ state: nextState,
2598
+ microstates: states
2599
+ };
2600
+ }
2601
+ function stopStep(event, nextState, actorCtx) {
2602
+ const actions = [];
2603
+ for (const stateNode of nextState.configuration.sort((a, b) => b.order - a.order)) {
2604
+ actions.push(...stateNode.exit);
2605
+ }
2606
+ for (const child of Object.values(nextState.children)) {
2607
+ actions.push(stop(child));
2608
+ }
2609
+ const {
2610
+ nextState: stoppedState
2611
+ } = resolveActionsAndContext(actions, event, nextState, actorCtx);
2612
+ return stoppedState;
2613
+ }
2614
+ function selectTransitions(event, nextState) {
2615
+ return nextState.machine.getTransitionData(nextState, event);
2616
+ }
2617
+ function selectEventlessTransitions(nextState) {
2618
+ const enabledTransitionSet = new Set();
2619
+ const atomicStates = nextState.configuration.filter(isAtomicStateNode);
2620
+ for (const stateNode of atomicStates) {
2621
+ loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, null))) {
2622
+ if (!s.always) {
2623
+ continue;
2624
+ }
2625
+ for (const transition of s.always) {
2626
+ if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, nextState.event, nextState)) {
2627
+ enabledTransitionSet.add(transition);
2628
+ break loop;
2629
+ }
2630
+ }
2631
+ }
2632
+ }
2633
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState.configuration), nextState.historyValue);
2634
+ }
2635
+
2636
+ /**
2637
+ * Resolves a partial state value with its full representation in the state node's machine.
2638
+ *
2639
+ * @param stateValue The partial state value to resolve.
2640
+ */
2641
+ function resolveStateValue(rootNode, stateValue) {
2642
+ const configuration = getConfiguration(getStateNodes(rootNode, stateValue));
2643
+ return getStateValue(rootNode, [...configuration]);
2644
+ }
2645
+ function stateValuesEqual(a, b) {
2646
+ if (a === b) {
2647
+ return true;
2648
+ }
2649
+ if (a === undefined || b === undefined) {
2650
+ return false;
2651
+ }
2652
+ if (isString(a) || isString(b)) {
2653
+ return a === b;
2654
+ }
2655
+ const aKeys = Object.keys(a);
2656
+ const bKeys = Object.keys(b);
2657
+ return aKeys.length === bKeys.length && aKeys.every(key => stateValuesEqual(a[key], b[key]));
2658
+ }
2659
+ function getInitialConfiguration(rootNode) {
2660
+ const configuration = [];
2661
+ const initialTransition = rootNode.initial;
2662
+ const statesToEnter = new Set();
2663
+ const statesForDefaultEntry = new Set([rootNode]);
2664
+ computeEntrySet([initialTransition], {}, statesForDefaultEntry, statesToEnter);
2665
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2666
+ configuration.push(stateNodeToEnter);
2667
+ }
2668
+ return configuration;
2669
+ }
2670
+
2671
+ class State {
2672
+ /**
2673
+ * Indicates whether the state is a final state.
2674
+ */
2675
+
2676
+ /**
2677
+ * The done data of the top-level finite state.
2678
+ */
2679
+ // TODO: add an explicit type for `output`
2680
+
2681
+ /**
2682
+ * Indicates whether the state has changed from the previous state. A state is considered "changed" if:
2683
+ *
2684
+ * - Its value is not equal to its previous value, or:
2685
+ * - It has any new actions (side-effects) to execute.
2686
+ *
2687
+ * An initial state (with no history) will return `undefined`.
2688
+ */
2689
+
2690
+ /**
2691
+ * The enabled state nodes representative of the state value.
2692
+ */
2693
+
2694
+ /**
2695
+ * The transition definitions that resulted in this state.
2696
+ */
2697
+
2698
+ /**
2699
+ * An object mapping actor names to spawned/invoked actors.
2700
+ */
2701
+
2702
+ /**
2703
+ * Creates a new State instance for the given `stateValue` and `context`.
2704
+ * @param stateValue
2705
+ * @param context
2706
+ */
2707
+ static from(stateValue, context = {}, machine) {
2708
+ if (stateValue instanceof State) {
2709
+ if (stateValue.context !== context) {
2710
+ return new State({
2711
+ value: stateValue.value,
2712
+ context,
2713
+ event: stateValue.event,
2714
+ actions: [],
2715
+ meta: {},
2716
+ configuration: [],
2717
+ // TODO: fix,
2718
+ transitions: [],
2719
+ children: {}
2720
+ }, machine);
2721
+ }
2722
+ return stateValue;
2723
+ }
2724
+ const event = createInitEvent({}); // TODO: fix
2725
+
2726
+ const configuration = getConfiguration(getStateNodes(machine.root, stateValue));
2727
+ return new State({
2728
+ value: stateValue,
2729
+ context,
2730
+ event,
2731
+ actions: [],
2732
+ meta: undefined,
2733
+ configuration: Array.from(configuration),
2734
+ transitions: [],
2735
+ children: {}
2736
+ }, machine);
2737
+ }
2738
+
2739
+ /**
2740
+ * Creates a new `State` instance that represents the current state of a running machine.
2741
+ *
2742
+ * @param config
2743
+ */
2744
+ constructor(config, machine) {
2745
+ this.machine = machine;
2746
+ this.tags = void 0;
2747
+ this.value = void 0;
2748
+ this.done = void 0;
2749
+ this.output = void 0;
2750
+ this.context = void 0;
2751
+ this.historyValue = {};
2752
+ this.actions = [];
2753
+ this.event = void 0;
2754
+ this._internalQueue = void 0;
2755
+ this._initial = false;
2756
+ this.changed = void 0;
2757
+ this.configuration = void 0;
2758
+ this.transitions = void 0;
2759
+ this.children = void 0;
2760
+ this.context = config.context;
2761
+ this._internalQueue = config._internalQueue ?? [];
2762
+ this.event = config.event;
2763
+ this.historyValue = config.historyValue || {};
2764
+ this.actions = config.actions ?? [];
2765
+ this.matches = this.matches.bind(this);
2766
+ this.toStrings = this.toStrings.bind(this);
2767
+ this.configuration = config.configuration ?? Array.from(getConfiguration(getStateNodes(machine.root, config.value)));
2768
+ this.transitions = config.transitions;
2769
+ this.children = config.children;
2770
+ this.value = getStateValue(machine.root, this.configuration);
2771
+ this.tags = new Set(flatten(this.configuration.map(sn => sn.tags)));
2772
+ this.done = config.done ?? false;
2773
+ this.output = config.output;
2774
+ }
2775
+
2776
+ /**
2777
+ * Returns an array of all the string leaf state node paths.
2778
+ * @param stateValue
2779
+ * @param delimiter The character(s) that separate each subpath in the string state node path.
2780
+ */
2781
+ toStrings(stateValue = this.value, delimiter = '.') {
2782
+ if (isString(stateValue)) {
2783
+ return [stateValue];
2784
+ }
2785
+ const valueKeys = Object.keys(stateValue);
2786
+ return valueKeys.concat(...valueKeys.map(key => this.toStrings(stateValue[key], delimiter).map(s => key + delimiter + s)));
2787
+ }
2788
+ toJSON() {
2789
+ const {
2790
+ configuration,
2791
+ transitions,
2792
+ tags,
2793
+ machine,
2794
+ ...jsonValues
2795
+ } = this;
2796
+ return {
2797
+ ...jsonValues,
2798
+ tags: Array.from(tags),
2799
+ meta: this.meta
2800
+ };
2801
+ }
2802
+
2803
+ /**
2804
+ * Whether the current state value is a subset of the given parent state value.
2805
+ * @param parentStateValue
2806
+ */
2807
+ matches(parentStateValue) {
2808
+ return matchesState(parentStateValue, this.value);
2809
+ }
2810
+
2811
+ /**
2812
+ * Whether the current state configuration has a state node with the specified `tag`.
2813
+ * @param tag
2814
+ */
2815
+ hasTag(tag) {
2816
+ return this.tags.has(tag);
2817
+ }
2818
+
2819
+ /**
2820
+ * Determines whether sending the `event` will cause a non-forbidden transition
2821
+ * to be selected, even if the transitions have no actions nor
2822
+ * change the state value.
2823
+ *
2824
+ * @param event The event to test
2825
+ * @returns Whether the event will cause a transition
2826
+ */
2827
+ can(event) {
2828
+ if (!this.machine) {
2829
+ console.warn(`state.can(...) used outside of a machine-created State object; this will always return false.`);
2830
+ }
2831
+ const transitionData = this.machine.getTransitionData(this, event);
2832
+ return !!transitionData?.length &&
2833
+ // Check that at least one transition is not forbidden
2834
+ transitionData.some(t => t.target !== undefined || t.actions.length);
2835
+ }
2836
+
2837
+ /**
2838
+ * The next events that will cause a transition from the current state.
2839
+ */
2840
+ get nextEvents() {
2841
+ return memo(this, 'nextEvents', () => {
2842
+ return [...new Set(flatten([...this.configuration.map(sn => sn.ownEvents)]))];
2843
+ });
2844
+ }
2845
+ get meta() {
2846
+ return this.configuration.reduce((acc, stateNode) => {
2847
+ if (stateNode.meta !== undefined) {
2848
+ acc[stateNode.id] = stateNode.meta;
2849
+ }
2850
+ return acc;
2851
+ }, {});
2852
+ }
2853
+ }
2854
+ function cloneState(state, config = {}) {
2855
+ return new State({
2856
+ ...state,
2857
+ ...config
2858
+ }, state.machine);
2859
+ }
2860
+ function getPersistedState(state) {
2861
+ const {
2862
+ configuration,
2863
+ transitions,
2864
+ tags,
2865
+ machine,
2866
+ children,
2867
+ ...jsonValues
2868
+ } = state;
2869
+ const childrenJson = {};
2870
+ for (const id in children) {
2871
+ childrenJson[id] = {
2872
+ state: children[id].getPersistedState?.(),
2873
+ src: children[id].src
2874
+ };
2875
+ }
2876
+ return {
2877
+ ...jsonValues,
2878
+ children: childrenJson
2879
+ };
2880
+ }
2881
+
2882
+ function invoke(invokeDef) {
2883
+ return createDynamicAction({
2884
+ type: invoke$1,
2885
+ params: invokeDef
2886
+ }, (event, {
2887
+ state,
2888
+ actorContext
2889
+ }) => {
2890
+ const type = invoke$1;
2891
+ const {
2892
+ id,
2893
+ src
2894
+ } = invokeDef;
2895
+ let resolvedInvokeAction;
2896
+ if (isActorRef(src)) {
2897
+ resolvedInvokeAction = {
2898
+ type,
2899
+ params: {
2900
+ ...invokeDef,
2901
+ ref: src
2902
+ }
2903
+ };
2904
+ } else {
2905
+ const referenced = resolveReferencedActor(state.machine.options.actors[src]);
2906
+ if (!referenced) {
2907
+ resolvedInvokeAction = {
2908
+ type,
2909
+ params: invokeDef
2910
+ };
2911
+ } else {
2912
+ const input = 'input' in invokeDef ? invokeDef.input : referenced.input;
2913
+ const ref = interpret(referenced.src, {
2914
+ id,
2915
+ src,
2916
+ parent: actorContext?.self,
2917
+ systemId: invokeDef.systemId,
2918
+ input: typeof input === 'function' ? input({
2919
+ context: state.context,
2920
+ event,
2921
+ self: actorContext?.self
2922
+ }) : input
2923
+ });
2924
+ resolvedInvokeAction = {
2925
+ type,
2926
+ params: {
2927
+ ...invokeDef,
2928
+ ref
2929
+ }
2930
+ };
2931
+ }
2932
+ }
2933
+ const actorRef = resolvedInvokeAction.params.ref;
2934
+ const invokedState = cloneState(state, {
2935
+ children: {
2936
+ ...state.children,
2937
+ [id]: actorRef
2938
+ }
2939
+ });
2940
+ resolvedInvokeAction.execute = actorCtx => {
2941
+ const parent = actorCtx.self;
2942
+ const {
2943
+ id,
2944
+ ref
2945
+ } = resolvedInvokeAction.params;
2946
+ if (!ref) {
2947
+ {
2948
+ console.warn(`Actor type '${resolvedInvokeAction.params.src}' not found in machine '${actorCtx.id}'.`);
2949
+ }
2950
+ return;
2951
+ }
2952
+ actorCtx.defer(() => {
2953
+ if (actorRef.status === ActorStatus.Stopped) {
2954
+ return;
2955
+ }
2956
+ try {
2957
+ actorRef.start?.();
2958
+ } catch (err) {
2959
+ parent.send(error(id, err));
2960
+ return;
2961
+ }
2962
+ });
2963
+ };
2964
+ return [invokedState, resolvedInvokeAction];
2965
+ });
2966
+ }
2967
+
2968
+ function createSpawner(self, machine, context, event, mutCapturedActions) {
2969
+ return (src, options = {}) => {
2970
+ const {
2971
+ systemId
2972
+ } = options;
2973
+ if (isString(src)) {
2974
+ const referenced = resolveReferencedActor(machine.options.actors[src]);
2975
+ if (referenced) {
2976
+ const resolvedName = options.id ?? 'anon'; // TODO: better name
2977
+ const input = 'input' in options ? options.input : referenced.input;
2978
+
2979
+ // TODO: this should also receive `src`
2980
+ const actorRef = interpret(referenced.src, {
2981
+ id: resolvedName,
2982
+ parent: self,
2983
+ input: typeof input === 'function' ? input({
2984
+ context,
2985
+ event,
2986
+ self
2987
+ }) : input
2988
+ });
2989
+ mutCapturedActions.push(invoke({
2990
+ id: actorRef.id,
2991
+ // @ts-ignore TODO: fix types
2992
+ src: actorRef,
2993
+ // TODO
2994
+ ref: actorRef,
2995
+ meta: undefined,
2996
+ input,
2997
+ systemId
2998
+ }));
2999
+ return actorRef; // TODO: fix types
3000
+ }
3001
+
3002
+ throw new Error(`Behavior '${src}' not implemented in machine '${machine.id}'`);
3003
+ } else {
3004
+ // TODO: this should also receive `src`
3005
+ // TODO: instead of anonymous, it should be a unique stable ID
3006
+ const actorRef = interpret(src, {
3007
+ id: options.id || 'anonymous',
3008
+ parent: self,
3009
+ input: options.input,
3010
+ systemId
3011
+ });
3012
+ mutCapturedActions.push(invoke({
3013
+ // @ts-ignore TODO: fix types
3014
+ src: actorRef,
3015
+ ref: actorRef,
3016
+ id: actorRef.id,
3017
+ meta: undefined,
3018
+ input: options.input
3019
+ }));
3020
+ return actorRef; // TODO: fix types
3021
+ }
3022
+ };
3023
+ }
3024
+
3025
+ /**
3026
+ * Updates the current context of the machine.
3027
+ *
3028
+ * @param assignment An object that represents the partial context to update.
3029
+ */
3030
+ function assign(assignment) {
3031
+ return createDynamicAction({
3032
+ type: assign$1,
3033
+ params: {
3034
+ assignment
3035
+ }
3036
+ }, (event, {
3037
+ state,
3038
+ action,
3039
+ actorContext
3040
+ }) => {
3041
+ const capturedActions = [];
3042
+ if (!state.context) {
3043
+ throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');
3044
+ }
3045
+ const args = {
3046
+ context: state.context,
3047
+ event,
3048
+ action,
3049
+ spawn: createSpawner(actorContext?.self, state.machine, state.context, event, capturedActions),
3050
+ self: actorContext?.self ?? {},
3051
+ system: actorContext?.system
3052
+ };
3053
+ let partialUpdate = {};
3054
+ if (isFunction(assignment)) {
3055
+ partialUpdate = assignment(args);
3056
+ } else {
3057
+ for (const key of Object.keys(assignment)) {
3058
+ const propAssignment = assignment[key];
3059
+ partialUpdate[key] = isFunction(propAssignment) ? propAssignment(args) : propAssignment;
3060
+ }
3061
+ }
3062
+ const updatedContext = Object.assign({}, state.context, partialUpdate);
3063
+ return [cloneState(state, {
3064
+ context: updatedContext
3065
+ }), {
3066
+ type: assign$1,
3067
+ params: {
3068
+ context: updatedContext,
3069
+ actions: capturedActions
3070
+ }
3071
+ }];
3072
+ });
3073
+ }
3074
+
3075
+ /**
3076
+ * Raises an event. This places the event in the internal event queue, so that
3077
+ * the event is immediately consumed by the machine in the current step.
3078
+ *
3079
+ * @param eventType The event to raise.
3080
+ */
3081
+
3082
+ function raise(eventOrExpr, options) {
3083
+ return createDynamicAction({
3084
+ type: raise$1,
3085
+ params: {
3086
+ delay: options ? options.delay : undefined,
3087
+ event: eventOrExpr,
3088
+ id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
3089
+ }
3090
+ }, (event, {
3091
+ state,
3092
+ actorContext
3093
+ }) => {
3094
+ const params = {
3095
+ delay: options ? options.delay : undefined,
3096
+ event: eventOrExpr,
3097
+ id: options && options.id !== undefined ? options.id : typeof eventOrExpr === 'function' ? eventOrExpr.name : eventOrExpr.type
3098
+ };
3099
+ const args = {
3100
+ context: state.context,
3101
+ event,
3102
+ self: actorContext?.self ?? {},
3103
+ system: actorContext?.system
3104
+ };
3105
+ const delaysMap = state.machine.options.delays;
3106
+
3107
+ // TODO: helper function for resolving Expr
3108
+ if (typeof eventOrExpr === 'string') {
3109
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
3110
+ }
3111
+ const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args) : eventOrExpr;
3112
+ let resolvedDelay;
3113
+ if (typeof params.delay === 'string') {
3114
+ const configDelay = delaysMap && delaysMap[params.delay];
3115
+ resolvedDelay = typeof configDelay === 'function' ? configDelay(args) : configDelay;
3116
+ } else {
3117
+ resolvedDelay = typeof params.delay === 'function' ? params.delay(args) : params.delay;
3118
+ }
3119
+ const resolvedAction = {
3120
+ type: raise$1,
3121
+ params: {
3122
+ ...params,
3123
+ event: resolvedEvent,
3124
+ delay: resolvedDelay
3125
+ },
3126
+ execute: actorCtx => {
3127
+ if (typeof resolvedAction.params.delay === 'number') {
3128
+ actorCtx.self.delaySend(resolvedAction);
3129
+ return;
3130
+ }
3131
+ }
3132
+ };
3133
+ return [state, resolvedAction];
3134
+ });
3135
+ }
3136
+
3137
+ function choose(guards) {
3138
+ return createDynamicAction({
3139
+ type: choose$1,
3140
+ params: {
3141
+ guards
3142
+ }
3143
+ }, (event, {
3144
+ state
3145
+ }) => {
3146
+ const matchedActions = guards.find(condition => {
3147
+ const guard = condition.guard && toGuardDefinition(condition.guard, guardType => state.machine.options.guards[guardType]);
3148
+ return !guard || evaluateGuard(guard, state.context, event, state);
3149
+ })?.actions;
3150
+ return [state, {
3151
+ type: choose$1,
3152
+ params: {
3153
+ actions: toActionObjects(matchedActions)
3154
+ }
3155
+ }];
3156
+ });
3157
+ }
3158
+
3159
+ function pure(getActions) {
3160
+ return createDynamicAction({
3161
+ type: pure$1,
3162
+ params: {
3163
+ get: getActions
3164
+ }
3165
+ }, (event, {
3166
+ state
3167
+ }) => {
3168
+ return [state, {
3169
+ type: pure$1,
3170
+ params: {
3171
+ actions: toArray(toActionObjects(getActions({
3172
+ context: state.context,
3173
+ event
3174
+ }))) ?? []
3175
+ }
3176
+ }];
3177
+ });
3178
+ }
3179
+
3180
+ const initEvent = {
3181
+ type: init
3182
+ };
3183
+ function resolveActionObject(actionObject, actionFunctionMap) {
3184
+ if (isDynamicAction(actionObject)) {
3185
+ return actionObject;
3186
+ }
3187
+ const dereferencedAction = actionFunctionMap[actionObject.type];
3188
+ if (typeof dereferencedAction === 'function') {
3189
+ return createDynamicAction({
3190
+ type: 'xstate.function',
3191
+ params: actionObject.params ?? {}
3192
+ }, (event, {
3193
+ state
3194
+ }) => {
3195
+ const a = {
3196
+ type: actionObject.type,
3197
+ params: actionObject.params,
3198
+ execute: actorCtx => {
3199
+ return dereferencedAction({
3200
+ context: state.context,
3201
+ event,
3202
+ action: a,
3203
+ system: actorCtx.system,
3204
+ self: actorCtx.self
3205
+ });
3206
+ }
3207
+ };
3208
+ return [state, a];
3209
+ });
3210
+ } else if (dereferencedAction) {
3211
+ return dereferencedAction;
3212
+ } else {
3213
+ return actionObject;
3214
+ }
3215
+ }
3216
+ function toActionObject(action) {
3217
+ if (isDynamicAction(action)) {
3218
+ return action;
3219
+ }
3220
+ if (typeof action === 'string') {
3221
+ return {
3222
+ type: action,
3223
+ params: {}
3224
+ };
3225
+ }
3226
+ if (typeof action === 'function') {
3227
+ const type = 'xstate.function';
3228
+ return createDynamicAction({
3229
+ type,
3230
+ params: {}
3231
+ }, (event, {
3232
+ state
3233
+ }) => {
3234
+ const actionObject = {
3235
+ type,
3236
+ params: {
3237
+ function: action
3238
+ },
3239
+ execute: actorCtx => {
3240
+ return action({
3241
+ context: state.context,
3242
+ event: event,
3243
+ action: actionObject,
3244
+ self: actorCtx.self,
3245
+ system: actorCtx.system
3246
+ });
3247
+ }
3248
+ };
3249
+ return [state, actionObject];
3250
+ });
3251
+ }
3252
+
3253
+ // action is already a BaseActionObject
3254
+ return action;
3255
+ }
3256
+ const toActionObjects = action => {
3257
+ if (!action) {
3258
+ return [];
3259
+ }
3260
+ const actions = isArray(action) ? action : [action];
3261
+ return actions.map(toActionObject);
3262
+ };
3263
+
3264
+ /**
3265
+ * Returns an event type that represents an implicit event that
3266
+ * is sent after the specified `delay`.
3267
+ *
3268
+ * @param delayRef The delay in milliseconds
3269
+ * @param id The state node ID where this event is handled
3270
+ */
3271
+ function after(delayRef, id) {
3272
+ const idSuffix = id ? `#${id}` : '';
3273
+ return `${ActionTypes.After}(${delayRef})${idSuffix}`;
3274
+ }
3275
+
3276
+ /**
3277
+ * Returns an event that represents that a final state node
3278
+ * has been reached in the parent state node.
3279
+ *
3280
+ * @param id The final state node's parent state node `id`
3281
+ * @param output The data to pass into the event
3282
+ */
3283
+ function done(id, output) {
3284
+ const type = `${ActionTypes.DoneState}.${id}`;
3285
+ const eventObject = {
3286
+ type,
3287
+ output
3288
+ };
3289
+ eventObject.toString = () => type;
3290
+ return eventObject;
3291
+ }
3292
+
3293
+ /**
3294
+ * Returns an event that represents that an invoked service has terminated.
3295
+ *
3296
+ * An invoked service is terminated when it has reached a top-level final state node,
3297
+ * but not when it is canceled.
3298
+ *
3299
+ * @param invokeId The invoked service ID
3300
+ * @param output The data to pass into the event
3301
+ */
3302
+ function doneInvoke(invokeId, output) {
3303
+ const type = `${ActionTypes.DoneInvoke}.${invokeId}`;
3304
+ const eventObject = {
3305
+ type,
3306
+ output
3307
+ };
3308
+ eventObject.toString = () => type;
3309
+ return eventObject;
3310
+ }
3311
+ function error(id, data) {
3312
+ const type = `${ActionTypes.ErrorPlatform}.${id}`;
3313
+ const eventObject = {
3314
+ type,
3315
+ data
3316
+ };
3317
+ eventObject.toString = () => type;
3318
+ return eventObject;
3319
+ }
3320
+ function createInitEvent(input) {
3321
+ return {
3322
+ type: init,
3323
+ input
3324
+ };
3325
+ }
3326
+
3327
+ export { toObserver as $, createInitEvent as A, resolveActionsAndContext as B, microstep as C, error as D, isStateId as E, getStateNodeByPath as F, getPersistedState as G, resolveReferencedActor as H, interpret as I, initEvent as J, matchesState as K, sendTo as L, sendParent as M, NULL_EVENT as N, forwardTo as O, Interpreter as P, ActorStatus as Q, doneInvoke as R, STATE_DELIMITER as S, assign as T, cancel as U, choose as V, log as W, pure as X, raise as Y, stop as Z, pathToStateValue as _, toArray as a, fromPromise as a0, fromObservable as a1, fromCallback as a2, fromEventObservable as a3, fromTransition as a4, stateIn as a5, not as a6, and as a7, or as a8, ActionTypes as a9, SpecialTargets as aa, startSignalType as ab, stopSignalType as ac, startSignal as ad, stopSignal as ae, isSignal as af, isActorRef as ag, toActorRef as ah, createEmptyActor as ai, toGuardDefinition as aj, actionTypes as ak, resolveActionObject as al, toActionObject as am, after as an, done as ao, send as ap, escalate as aq, toTransitionConfigArray as b, formatTransition as c, memo as d, evaluateGuard as e, formatTransitions as f, flatten as g, createInvokeId as h, isString as i, invoke$1 as j, getDelayedTransitions as k, formatInitialTransition as l, mapValues as m, getCandidates as n, toInvokeConfig as o, createSpawner as p, getConfiguration as q, getStateNodes as r, resolveStateValue as s, toActionObjects as t, isInFinalState as u, State as v, isErrorEvent as w, macrostep as x, transitionNode as y, getInitialConfiguration as z };