xstate 5.0.0-beta.9 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +10 -8
  2. package/actions/dist/xstate-actions.cjs.js +19 -5
  3. package/actions/dist/xstate-actions.cjs.mjs +3 -15
  4. package/actions/dist/xstate-actions.development.cjs.js +21 -0
  5. package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
  6. package/actions/dist/xstate-actions.development.esm.js +3 -0
  7. package/actions/dist/xstate-actions.esm.js +3 -2
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +621 -4
  11. package/actors/dist/xstate-actors.cjs.mjs +1 -8
  12. package/actors/dist/xstate-actors.development.cjs.js +624 -0
  13. package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
  14. package/actors/dist/xstate-actors.development.esm.js +615 -0
  15. package/actors/dist/xstate-actors.esm.js +615 -2
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dev/dist/xstate-dev.cjs.js +45 -4
  19. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  20. package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
  21. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  22. package/dev/dist/xstate-dev.esm.js +42 -1
  23. package/dev/dist/xstate-dev.umd.min.js +1 -1
  24. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  25. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  26. package/dist/declarations/src/State.d.ts +47 -73
  27. package/dist/declarations/src/StateMachine.d.ts +29 -57
  28. package/dist/declarations/src/StateNode.d.ts +36 -33
  29. package/dist/declarations/src/actions/assign.d.ts +11 -2
  30. package/dist/declarations/src/actions/cancel.d.ts +7 -3
  31. package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
  32. package/dist/declarations/src/actions/log.d.ts +7 -3
  33. package/dist/declarations/src/actions/raise.d.ts +7 -2
  34. package/dist/declarations/src/actions/send.d.ts +14 -36
  35. package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
  36. package/dist/declarations/src/actions/stopChild.d.ts +18 -0
  37. package/dist/declarations/src/actions.d.ts +8 -48
  38. package/dist/declarations/src/actors/callback.d.ts +91 -8
  39. package/dist/declarations/src/actors/index.d.ts +6 -28
  40. package/dist/declarations/src/actors/observable.d.ts +101 -18
  41. package/dist/declarations/src/actors/promise.d.ts +80 -10
  42. package/dist/declarations/src/actors/transition.d.ts +64 -9
  43. package/dist/declarations/src/constants.d.ts +3 -0
  44. package/dist/declarations/src/createMachine.d.ts +20 -0
  45. package/dist/declarations/src/dev/index.d.ts +6 -6
  46. package/dist/declarations/src/guards.d.ts +41 -8
  47. package/dist/declarations/src/index.d.ts +18 -23
  48. package/dist/declarations/src/interpreter.d.ts +149 -41
  49. package/dist/declarations/src/setup.d.ts +51 -0
  50. package/dist/declarations/src/spawn.d.ts +23 -2
  51. package/dist/declarations/src/stateUtils.d.ts +30 -45
  52. package/dist/declarations/src/system.d.ts +26 -2
  53. package/dist/declarations/src/typegenTypes.d.ts +34 -22
  54. package/dist/declarations/src/types.d.ts +527 -669
  55. package/dist/declarations/src/utils.d.ts +15 -52
  56. package/dist/declarations/src/waitFor.d.ts +2 -2
  57. package/dist/log-22e678c5.esm.js +364 -0
  58. package/dist/log-5e226275.cjs.js +372 -0
  59. package/dist/log-641cd926.development.cjs.js +394 -0
  60. package/dist/log-f196f85f.development.esm.js +386 -0
  61. package/dist/raise-34e25c2c.cjs.js +2368 -0
  62. package/dist/raise-62704519.development.cjs.js +2422 -0
  63. package/dist/raise-89c581c4.development.esm.js +2371 -0
  64. package/dist/raise-8bc422d1.esm.js +2317 -0
  65. package/dist/xstate.cjs.js +728 -4
  66. package/dist/xstate.cjs.mjs +9 -9
  67. package/dist/xstate.development.cjs.js +737 -0
  68. package/dist/xstate.development.cjs.mjs +39 -0
  69. package/dist/xstate.development.esm.js +699 -0
  70. package/dist/xstate.esm.js +561 -770
  71. package/dist/xstate.umd.min.js +1 -1
  72. package/dist/xstate.umd.min.js.map +1 -1
  73. package/guards/dist/xstate-guards.cjs.js +12 -5
  74. package/guards/dist/xstate-guards.cjs.mjs +1 -2
  75. package/guards/dist/xstate-guards.development.cjs.js +14 -0
  76. package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
  77. package/guards/dist/xstate-guards.development.esm.js +2 -0
  78. package/guards/dist/xstate-guards.esm.js +2 -2
  79. package/guards/dist/xstate-guards.umd.min.js +1 -1
  80. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  81. package/package.json +53 -1
  82. package/actions/dist/xstate-actions.cjs.dev.js +0 -32
  83. package/actions/dist/xstate-actions.cjs.prod.js +0 -32
  84. package/actions/dynamicAction.ts +0 -42
  85. package/actors/dist/xstate-actors.cjs.dev.js +0 -22
  86. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  87. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  88. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  89. package/dist/actions-b6357569.cjs.dev.js +0 -4437
  90. package/dist/actions-bd4a184d.cjs.prod.js +0 -4423
  91. package/dist/actions-de434a04.esm.js +0 -4348
  92. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  93. package/dist/declarations/src/Machine.d.ts +0 -4
  94. package/dist/declarations/src/Mailbox.d.ts +0 -12
  95. package/dist/declarations/src/actionTypes.d.ts +0 -16
  96. package/dist/declarations/src/actions/choose.d.ts +0 -3
  97. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  98. package/dist/declarations/src/actions/pure.d.ts +0 -6
  99. package/dist/declarations/src/actions/stop.d.ts +0 -7
  100. package/dist/declarations/src/environment.d.ts +0 -1
  101. package/dist/declarations/src/mapState.d.ts +0 -3
  102. package/dist/declarations/src/memo.d.ts +0 -2
  103. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  104. package/dist/xstate.cjs.dev.js +0 -950
  105. package/dist/xstate.cjs.prod.js +0 -947
  106. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
  107. package/guards/dist/xstate-guards.cjs.prod.js +0 -15
@@ -0,0 +1,2317 @@
1
+ import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';
2
+
3
+ class Mailbox {
4
+ constructor(_process) {
5
+ this._process = _process;
6
+ this._active = false;
7
+ this._current = null;
8
+ this._last = null;
9
+ }
10
+ start() {
11
+ this._active = true;
12
+ this.flush();
13
+ }
14
+ clear() {
15
+ // we can't set _current to null because we might be currently processing
16
+ // and enqueue following clear shouldnt start processing the enqueued item immediately
17
+ if (this._current) {
18
+ this._current.next = null;
19
+ this._last = this._current;
20
+ }
21
+ }
22
+ enqueue(event) {
23
+ const enqueued = {
24
+ value: event,
25
+ next: null
26
+ };
27
+ if (this._current) {
28
+ this._last.next = enqueued;
29
+ this._last = enqueued;
30
+ return;
31
+ }
32
+ this._current = enqueued;
33
+ this._last = enqueued;
34
+ if (this._active) {
35
+ this.flush();
36
+ }
37
+ }
38
+ flush() {
39
+ while (this._current) {
40
+ // atm the given _process is responsible for implementing proper try/catch handling
41
+ // we assume here that this won't throw in a way that can affect this mailbox
42
+ const consumed = this._current;
43
+ this._process(consumed.value);
44
+ this._current = consumed.next;
45
+ }
46
+ this._last = null;
47
+ }
48
+ }
49
+
50
+ const STATE_DELIMITER = '.';
51
+ const TARGETLESS_KEY = '';
52
+ const NULL_EVENT = '';
53
+ const STATE_IDENTIFIER = '#';
54
+ const WILDCARD = '*';
55
+ const XSTATE_INIT = 'xstate.init';
56
+ const XSTATE_ERROR = 'xstate.error';
57
+ const XSTATE_STOP = 'xstate.stop';
58
+
59
+ /**
60
+ * Returns an event that represents an implicit event that
61
+ * is sent after the specified `delay`.
62
+ *
63
+ * @param delayRef The delay in milliseconds
64
+ * @param id The state node ID where this event is handled
65
+ */
66
+ function createAfterEvent(delayRef, id) {
67
+ return {
68
+ type: `xstate.after.${delayRef}.${id}`
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Returns an event that represents that a final state node
74
+ * has been reached in the parent state node.
75
+ *
76
+ * @param id The final state node's parent state node `id`
77
+ * @param output The data to pass into the event
78
+ */
79
+ function createDoneStateEvent(id, output) {
80
+ return {
81
+ type: `xstate.done.state.${id}`,
82
+ output
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Returns an event that represents that an invoked service has terminated.
88
+ *
89
+ * An invoked service is terminated when it has reached a top-level final state node,
90
+ * but not when it is canceled.
91
+ *
92
+ * @param invokeId The invoked service ID
93
+ * @param output The data to pass into the event
94
+ */
95
+ function createDoneActorEvent(invokeId, output) {
96
+ return {
97
+ type: `xstate.done.actor.${invokeId}`,
98
+ output
99
+ };
100
+ }
101
+ function createErrorActorEvent(id, error) {
102
+ return {
103
+ type: `xstate.error.actor.${id}`,
104
+ error
105
+ };
106
+ }
107
+ function createInitEvent(input) {
108
+ return {
109
+ type: XSTATE_INIT,
110
+ input
111
+ };
112
+ }
113
+
114
+ /**
115
+ * This function makes sure that unhandled errors are thrown in a separate macrotask.
116
+ * It allows those errors to be detected by global error handlers and reported to bug tracking services
117
+ * without interrupting our own stack of execution.
118
+ *
119
+ * @param err error to be thrown
120
+ */
121
+ function reportUnhandledError(err) {
122
+ setTimeout(() => {
123
+ throw err;
124
+ });
125
+ }
126
+
127
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
128
+
129
+ let idCounter = 0;
130
+ function createSystem(rootActor) {
131
+ const children = new Map();
132
+ const keyedActors = new Map();
133
+ const reverseKeyedActors = new WeakMap();
134
+ const observers = new Set();
135
+ const system = {
136
+ _bookId: () => `x:${idCounter++}`,
137
+ _register: (sessionId, actorRef) => {
138
+ children.set(sessionId, actorRef);
139
+ return sessionId;
140
+ },
141
+ _unregister: actorRef => {
142
+ children.delete(actorRef.sessionId);
143
+ const systemId = reverseKeyedActors.get(actorRef);
144
+ if (systemId !== undefined) {
145
+ keyedActors.delete(systemId);
146
+ reverseKeyedActors.delete(actorRef);
147
+ }
148
+ },
149
+ get: systemId => {
150
+ return keyedActors.get(systemId);
151
+ },
152
+ _set: (systemId, actorRef) => {
153
+ const existing = keyedActors.get(systemId);
154
+ if (existing && existing !== actorRef) {
155
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
156
+ }
157
+ keyedActors.set(systemId, actorRef);
158
+ reverseKeyedActors.set(actorRef, systemId);
159
+ },
160
+ inspect: observer => {
161
+ observers.add(observer);
162
+ },
163
+ _sendInspectionEvent: event => {
164
+ const resolvedInspectionEvent = {
165
+ ...event,
166
+ rootId: rootActor.sessionId
167
+ };
168
+ observers.forEach(observer => observer.next?.(resolvedInspectionEvent));
169
+ },
170
+ _relay: (source, target, event) => {
171
+ system._sendInspectionEvent({
172
+ type: '@xstate.event',
173
+ sourceRef: source,
174
+ actorRef: target,
175
+ event
176
+ });
177
+ target._send(event);
178
+ }
179
+ };
180
+ return system;
181
+ }
182
+
183
+ function matchesState(parentStateId, childStateId) {
184
+ const parentStateValue = toStateValue(parentStateId);
185
+ const childStateValue = toStateValue(childStateId);
186
+ if (typeof childStateValue === 'string') {
187
+ if (typeof parentStateValue === 'string') {
188
+ return childStateValue === parentStateValue;
189
+ }
190
+
191
+ // Parent more specific than child
192
+ return false;
193
+ }
194
+ if (typeof parentStateValue === 'string') {
195
+ return parentStateValue in childStateValue;
196
+ }
197
+ return Object.keys(parentStateValue).every(key => {
198
+ if (!(key in childStateValue)) {
199
+ return false;
200
+ }
201
+ return matchesState(parentStateValue[key], childStateValue[key]);
202
+ });
203
+ }
204
+ function toStatePath(stateId) {
205
+ if (isArray(stateId)) {
206
+ return stateId;
207
+ }
208
+ return stateId.split(STATE_DELIMITER);
209
+ }
210
+ function toStateValue(stateValue) {
211
+ if (isMachineSnapshot(stateValue)) {
212
+ return stateValue.value;
213
+ }
214
+ if (typeof stateValue !== 'string') {
215
+ return stateValue;
216
+ }
217
+ const statePath = toStatePath(stateValue);
218
+ return pathToStateValue(statePath);
219
+ }
220
+ function pathToStateValue(statePath) {
221
+ if (statePath.length === 1) {
222
+ return statePath[0];
223
+ }
224
+ const value = {};
225
+ let marker = value;
226
+ for (let i = 0; i < statePath.length - 1; i++) {
227
+ if (i === statePath.length - 2) {
228
+ marker[statePath[i]] = statePath[i + 1];
229
+ } else {
230
+ const previous = marker;
231
+ marker = {};
232
+ previous[statePath[i]] = marker;
233
+ }
234
+ }
235
+ return value;
236
+ }
237
+ function mapValues(collection, iteratee) {
238
+ const result = {};
239
+ const collectionKeys = Object.keys(collection);
240
+ for (let i = 0; i < collectionKeys.length; i++) {
241
+ const key = collectionKeys[i];
242
+ result[key] = iteratee(collection[key], key, collection, i);
243
+ }
244
+ return result;
245
+ }
246
+ function toArrayStrict(value) {
247
+ if (isArray(value)) {
248
+ return value;
249
+ }
250
+ return [value];
251
+ }
252
+ function toArray(value) {
253
+ if (value === undefined) {
254
+ return [];
255
+ }
256
+ return toArrayStrict(value);
257
+ }
258
+ function resolveOutput(mapper, context, event, self) {
259
+ if (typeof mapper === 'function') {
260
+ return mapper({
261
+ context,
262
+ event,
263
+ self
264
+ });
265
+ }
266
+ return mapper;
267
+ }
268
+ function isArray(value) {
269
+ return Array.isArray(value);
270
+ }
271
+ function isErrorActorEvent(event) {
272
+ return event.type.startsWith('xstate.error.actor');
273
+ }
274
+ function toTransitionConfigArray(configLike) {
275
+ return toArrayStrict(configLike).map(transitionLike => {
276
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
277
+ return {
278
+ target: transitionLike
279
+ };
280
+ }
281
+ return transitionLike;
282
+ });
283
+ }
284
+ function normalizeTarget(target) {
285
+ if (target === undefined || target === TARGETLESS_KEY) {
286
+ return undefined;
287
+ }
288
+ return toArray(target);
289
+ }
290
+ function toObserver(nextHandler, errorHandler, completionHandler) {
291
+ const isObserver = typeof nextHandler === 'object';
292
+ const self = isObserver ? nextHandler : undefined;
293
+ return {
294
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
295
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
296
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
297
+ };
298
+ }
299
+ function createInvokeId(stateNodeId, index) {
300
+ return `${index}.${stateNodeId}`;
301
+ }
302
+ function resolveReferencedActor(machine, src) {
303
+ const match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
304
+ if (!match) {
305
+ return machine.implementations.actors[src];
306
+ }
307
+ const [, indexStr, nodeId] = match;
308
+ const node = machine.getStateNodeById(nodeId);
309
+ const invokeConfig = node.config.invoke;
310
+ return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
311
+ }
312
+ function getAllOwnEventDescriptors(snapshot) {
313
+ return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];
314
+ }
315
+
316
+ const $$ACTOR_TYPE = 1;
317
+ // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
318
+ let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
319
+ ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
320
+ ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
321
+ ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
322
+ return ProcessingStatus;
323
+ }({});
324
+ const defaultOptions = {
325
+ clock: {
326
+ setTimeout: (fn, ms) => {
327
+ return setTimeout(fn, ms);
328
+ },
329
+ clearTimeout: id => {
330
+ return clearTimeout(id);
331
+ }
332
+ },
333
+ logger: console.log.bind(console),
334
+ devTools: false
335
+ };
336
+
337
+ /**
338
+ * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.
339
+ */
340
+ class Actor {
341
+ /**
342
+ * Creates a new actor instance for the given logic with the provided options, if any.
343
+ *
344
+ * @param logic The logic to create an actor from
345
+ * @param options Actor options
346
+ */
347
+ constructor(logic, options) {
348
+ this.logic = logic;
349
+ /**
350
+ * The current internal state of the actor.
351
+ */
352
+ this._snapshot = void 0;
353
+ /**
354
+ * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.
355
+ */
356
+ this.clock = void 0;
357
+ this.options = void 0;
358
+ /**
359
+ * The unique identifier for this actor relative to its parent.
360
+ */
361
+ this.id = void 0;
362
+ this.mailbox = new Mailbox(this._process.bind(this));
363
+ this.delayedEventsMap = {};
364
+ this.observers = new Set();
365
+ this.logger = void 0;
366
+ /** @internal */
367
+ this._processingStatus = ProcessingStatus.NotStarted;
368
+ // Actor Ref
369
+ this._parent = void 0;
370
+ this._syncSnapshot = void 0;
371
+ this.ref = void 0;
372
+ // TODO: add typings for system
373
+ this._actorScope = void 0;
374
+ this._systemId = void 0;
375
+ /**
376
+ * The globally unique process ID for this invocation.
377
+ */
378
+ this.sessionId = void 0;
379
+ /**
380
+ * The system to which this actor belongs.
381
+ */
382
+ this.system = void 0;
383
+ this._doneEvent = void 0;
384
+ this.src = void 0;
385
+ // array of functions to defer
386
+ this._deferred = [];
387
+ const resolvedOptions = {
388
+ ...defaultOptions,
389
+ ...options
390
+ };
391
+ const {
392
+ clock,
393
+ logger,
394
+ parent,
395
+ syncSnapshot,
396
+ id,
397
+ systemId,
398
+ inspect
399
+ } = resolvedOptions;
400
+ this.system = parent?.system ?? createSystem(this);
401
+ if (inspect && !parent) {
402
+ // Always inspect at the system-level
403
+ this.system.inspect(toObserver(inspect));
404
+ }
405
+ this.sessionId = this.system._bookId();
406
+ this.id = id ?? this.sessionId;
407
+ this.logger = logger;
408
+ this.clock = clock;
409
+ this._parent = parent;
410
+ this._syncSnapshot = syncSnapshot;
411
+ this.options = resolvedOptions;
412
+ this.src = resolvedOptions.src ?? logic;
413
+ this.ref = this;
414
+ this._actorScope = {
415
+ self: this,
416
+ id: this.id,
417
+ sessionId: this.sessionId,
418
+ logger: this.logger,
419
+ defer: fn => {
420
+ this._deferred.push(fn);
421
+ },
422
+ system: this.system,
423
+ stopChild: child => {
424
+ if (child._parent !== this) {
425
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
426
+ }
427
+ child._stop();
428
+ }
429
+ };
430
+
431
+ // Ensure that the send method is bound to this Actor instance
432
+ // if destructured
433
+ this.send = this.send.bind(this);
434
+ this.system._sendInspectionEvent({
435
+ type: '@xstate.actor',
436
+ actorRef: this
437
+ });
438
+ if (systemId) {
439
+ this._systemId = systemId;
440
+ this.system._set(systemId, this);
441
+ }
442
+ this._initState(options?.snapshot ?? options?.state);
443
+ if (systemId && this._snapshot.status !== 'active') {
444
+ this.system._unregister(this);
445
+ }
446
+ }
447
+ _initState(persistedState) {
448
+ try {
449
+ this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);
450
+ } catch (err) {
451
+ // if we get here then it means that we assign a value to this._snapshot that is not of the correct type
452
+ // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible
453
+ // so right now this is a lie of sorts
454
+ this._snapshot = {
455
+ status: 'error',
456
+ output: undefined,
457
+ error: err
458
+ };
459
+ }
460
+ }
461
+ update(snapshot, event) {
462
+ // Update state
463
+ this._snapshot = snapshot;
464
+
465
+ // Execute deferred effects
466
+ let deferredFn;
467
+ while (deferredFn = this._deferred.shift()) {
468
+ try {
469
+ deferredFn();
470
+ } catch (err) {
471
+ // this error can only be caught when executing *initial* actions
472
+ // it's the only time when we call actions provided by the user through those deferreds
473
+ // when the actor is already running we always execute them synchronously while transitioning
474
+ // no "builtin deferred" should actually throw an error since they are either safe
475
+ // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox
476
+ this._deferred.length = 0;
477
+ this._snapshot = {
478
+ ...snapshot,
479
+ status: 'error',
480
+ error: err
481
+ };
482
+ }
483
+ }
484
+ switch (this._snapshot.status) {
485
+ case 'active':
486
+ for (const observer of this.observers) {
487
+ try {
488
+ observer.next?.(snapshot);
489
+ } catch (err) {
490
+ reportUnhandledError(err);
491
+ }
492
+ }
493
+ break;
494
+ case 'done':
495
+ // next observers are meant to be notified about done snapshots
496
+ // this can be seen as something that is different from how observable work
497
+ // but with observables `complete` callback is called without any arguments
498
+ // it's more ergonomic for XState to treat a done snapshot as a "next" value
499
+ // and the completion event as something that is separate,
500
+ // something that merely follows emitting that done snapshot
501
+ for (const observer of this.observers) {
502
+ try {
503
+ observer.next?.(snapshot);
504
+ } catch (err) {
505
+ reportUnhandledError(err);
506
+ }
507
+ }
508
+ this._stopProcedure();
509
+ this._complete();
510
+ this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
511
+ if (this._parent) {
512
+ this.system._relay(this, this._parent, this._doneEvent);
513
+ }
514
+ break;
515
+ case 'error':
516
+ this._error(this._snapshot.error);
517
+ break;
518
+ }
519
+ this.system._sendInspectionEvent({
520
+ type: '@xstate.snapshot',
521
+ actorRef: this,
522
+ event,
523
+ snapshot
524
+ });
525
+ }
526
+
527
+ /**
528
+ * Subscribe an observer to an actor’s snapshot values.
529
+ *
530
+ * @remarks
531
+ * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:
532
+ * - A plain function that receives the latest snapshot, or
533
+ * - An observer object whose `.next(snapshot)` method receives the latest snapshot
534
+ *
535
+ * @example
536
+ * ```ts
537
+ * // Observer as a plain function
538
+ * const subscription = actor.subscribe((snapshot) => {
539
+ * console.log(snapshot);
540
+ * });
541
+ * ```
542
+ *
543
+ * @example
544
+ * ```ts
545
+ * // Observer as an object
546
+ * const subscription = actor.subscribe({
547
+ * next(snapshot) {
548
+ * console.log(snapshot);
549
+ * },
550
+ * error(err) {
551
+ * // ...
552
+ * },
553
+ * complete() {
554
+ * // ...
555
+ * },
556
+ * });
557
+ * ```
558
+ *
559
+ * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:
560
+ *
561
+ * @example
562
+ * ```ts
563
+ * const subscription = actor.subscribe((snapshot) => {
564
+ * // ...
565
+ * });
566
+ *
567
+ * // Unsubscribe the observer
568
+ * subscription.unsubscribe();
569
+ * ```
570
+ *
571
+ * When the actor is stopped, all of its observers will automatically be unsubscribed.
572
+ *
573
+ * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot
574
+ */
575
+
576
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
577
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
578
+ if (this._processingStatus !== ProcessingStatus.Stopped) {
579
+ this.observers.add(observer);
580
+ } else {
581
+ try {
582
+ observer.complete?.();
583
+ } catch (err) {
584
+ reportUnhandledError(err);
585
+ }
586
+ }
587
+ return {
588
+ unsubscribe: () => {
589
+ this.observers.delete(observer);
590
+ }
591
+ };
592
+ }
593
+
594
+ /**
595
+ * Starts the Actor from the initial state
596
+ */
597
+ start() {
598
+ if (this._processingStatus === ProcessingStatus.Running) {
599
+ // Do not restart the service if it is already started
600
+ return this;
601
+ }
602
+ if (this._syncSnapshot) {
603
+ this.subscribe({
604
+ next: snapshot => {
605
+ if (snapshot.status === 'active') {
606
+ this.system._relay(this, this._parent, {
607
+ type: `xstate.snapshot.${this.id}`,
608
+ snapshot
609
+ });
610
+ }
611
+ },
612
+ error: () => {}
613
+ });
614
+ }
615
+ this.system._register(this.sessionId, this);
616
+ if (this._systemId) {
617
+ this.system._set(this._systemId, this);
618
+ }
619
+ this._processingStatus = ProcessingStatus.Running;
620
+
621
+ // TODO: this isn't correct when rehydrating
622
+ const initEvent = createInitEvent(this.options.input);
623
+ this.system._sendInspectionEvent({
624
+ type: '@xstate.event',
625
+ sourceRef: this._parent,
626
+ actorRef: this,
627
+ event: initEvent
628
+ });
629
+ const status = this._snapshot.status;
630
+ switch (status) {
631
+ case 'done':
632
+ // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
633
+ // we still need to complete observers, flush deferreds etc
634
+ this.update(this._snapshot, initEvent);
635
+ // TODO: rethink cleanup of observers, mailbox, etc
636
+ return this;
637
+ case 'error':
638
+ this._error(this._snapshot.error);
639
+ return this;
640
+ }
641
+ if (this.logic.start) {
642
+ try {
643
+ this.logic.start(this._snapshot, this._actorScope);
644
+ } catch (err) {
645
+ this._snapshot = {
646
+ ...this._snapshot,
647
+ status: 'error',
648
+ error: err
649
+ };
650
+ this._error(err);
651
+ return this;
652
+ }
653
+ }
654
+
655
+ // TODO: this notifies all subscribers but usually this is redundant
656
+ // there is no real change happening here
657
+ // we need to rethink if this needs to be refactored
658
+ this.update(this._snapshot, initEvent);
659
+ if (this.options.devTools) {
660
+ this.attachDevTools();
661
+ }
662
+ this.mailbox.start();
663
+ return this;
664
+ }
665
+ _process(event) {
666
+ let nextState;
667
+ let caughtError;
668
+ try {
669
+ nextState = this.logic.transition(this._snapshot, event, this._actorScope);
670
+ } catch (err) {
671
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
672
+ caughtError = {
673
+ err
674
+ };
675
+ }
676
+ if (caughtError) {
677
+ const {
678
+ err
679
+ } = caughtError;
680
+ this._snapshot = {
681
+ ...this._snapshot,
682
+ status: 'error',
683
+ error: err
684
+ };
685
+ this._error(err);
686
+ return;
687
+ }
688
+ this.update(nextState, event);
689
+ if (event.type === XSTATE_STOP) {
690
+ this._stopProcedure();
691
+ this._complete();
692
+ }
693
+ }
694
+ _stop() {
695
+ if (this._processingStatus === ProcessingStatus.Stopped) {
696
+ return this;
697
+ }
698
+ this.mailbox.clear();
699
+ if (this._processingStatus === ProcessingStatus.NotStarted) {
700
+ this._processingStatus = ProcessingStatus.Stopped;
701
+ return this;
702
+ }
703
+ this.mailbox.enqueue({
704
+ type: XSTATE_STOP
705
+ });
706
+ return this;
707
+ }
708
+
709
+ /**
710
+ * Stops the Actor and unsubscribe all listeners.
711
+ */
712
+ stop() {
713
+ if (this._parent) {
714
+ throw new Error('A non-root actor cannot be stopped directly.');
715
+ }
716
+ return this._stop();
717
+ }
718
+ _complete() {
719
+ for (const observer of this.observers) {
720
+ try {
721
+ observer.complete?.();
722
+ } catch (err) {
723
+ reportUnhandledError(err);
724
+ }
725
+ }
726
+ this.observers.clear();
727
+ }
728
+ _reportError(err) {
729
+ if (!this.observers.size) {
730
+ if (!this._parent) {
731
+ reportUnhandledError(err);
732
+ }
733
+ return;
734
+ }
735
+ let reportError = false;
736
+ for (const observer of this.observers) {
737
+ const errorListener = observer.error;
738
+ reportError ||= !errorListener;
739
+ try {
740
+ errorListener?.(err);
741
+ } catch (err2) {
742
+ reportUnhandledError(err2);
743
+ }
744
+ }
745
+ this.observers.clear();
746
+ if (reportError) {
747
+ reportUnhandledError(err);
748
+ }
749
+ }
750
+ _error(err) {
751
+ this._stopProcedure();
752
+ this._reportError(err);
753
+ if (this._parent) {
754
+ this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
755
+ }
756
+ }
757
+ // TODO: atm children don't belong entirely to the actor so
758
+ // in a way - it's not even super aware of them
759
+ // so we can't stop them from here but we really should!
760
+ // right now, they are being stopped within the machine's transition
761
+ // but that could throw and leave us with "orphaned" active actors
762
+ _stopProcedure() {
763
+ if (this._processingStatus !== ProcessingStatus.Running) {
764
+ // Actor already stopped; do nothing
765
+ return this;
766
+ }
767
+
768
+ // Cancel all delayed events
769
+ for (const key of Object.keys(this.delayedEventsMap)) {
770
+ this.clock.clearTimeout(this.delayedEventsMap[key]);
771
+ }
772
+
773
+ // TODO: mailbox.reset
774
+ this.mailbox.clear();
775
+ // TODO: after `stop` we must prepare ourselves for receiving events again
776
+ // events sent *after* stop signal must be queued
777
+ // it seems like this should be the common behavior for all of our consumers
778
+ // so perhaps this should be unified somehow for all of them
779
+ this.mailbox = new Mailbox(this._process.bind(this));
780
+ this._processingStatus = ProcessingStatus.Stopped;
781
+ this.system._unregister(this);
782
+ return this;
783
+ }
784
+
785
+ /**
786
+ * @internal
787
+ */
788
+ _send(event) {
789
+ if (this._processingStatus === ProcessingStatus.Stopped) {
790
+ return;
791
+ }
792
+ this.mailbox.enqueue(event);
793
+ }
794
+
795
+ /**
796
+ * Sends an event to the running Actor to trigger a transition.
797
+ *
798
+ * @param event The event to send
799
+ */
800
+ send(event) {
801
+ this.system._relay(undefined, this, event);
802
+ }
803
+
804
+ /**
805
+ * TODO: figure out a way to do this within the machine
806
+ * @internal
807
+ */
808
+ delaySend(params) {
809
+ const {
810
+ event,
811
+ id,
812
+ delay
813
+ } = params;
814
+ const timerId = this.clock.setTimeout(() => {
815
+ this.system._relay(this, params.to ?? this, event);
816
+ }, delay);
817
+
818
+ // TODO: consider the rehydration story here
819
+ if (id) {
820
+ this.delayedEventsMap[id] = timerId;
821
+ }
822
+ }
823
+
824
+ /**
825
+ * TODO: figure out a way to do this within the machine
826
+ * @internal
827
+ */
828
+ cancel(sendId) {
829
+ this.clock.clearTimeout(this.delayedEventsMap[sendId]);
830
+ delete this.delayedEventsMap[sendId];
831
+ }
832
+ attachDevTools() {
833
+ const {
834
+ devTools
835
+ } = this.options;
836
+ if (devTools) {
837
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;
838
+ resolvedDevToolsAdapter(this);
839
+ }
840
+ }
841
+ toJSON() {
842
+ return {
843
+ xstate$$type: $$ACTOR_TYPE,
844
+ id: this.id
845
+ };
846
+ }
847
+
848
+ /**
849
+ * Obtain the internal state of the actor, which can be persisted.
850
+ *
851
+ * @remarks
852
+ * The internal state can be persisted from any actor, not only machines.
853
+ *
854
+ * Note that the persisted state is not the same as the snapshot from {@link Actor.getSnapshot}. Persisted state represents the internal state of the actor, while snapshots represent the actor's last emitted value.
855
+ *
856
+ * Can be restored with {@link ActorOptions.state}
857
+ *
858
+ * @see https://stately.ai/docs/persistence
859
+ */
860
+
861
+ getPersistedSnapshot(options) {
862
+ return this.logic.getPersistedSnapshot(this._snapshot, options);
863
+ }
864
+ [symbolObservable]() {
865
+ return this;
866
+ }
867
+
868
+ /**
869
+ * Read an actor’s snapshot synchronously.
870
+ *
871
+ * @remarks
872
+ * The snapshot represent an actor's last emitted value.
873
+ *
874
+ * When an actor receives an event, its internal state may change.
875
+ * An actor may emit a snapshot when a state transition occurs.
876
+ *
877
+ * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.
878
+ *
879
+ * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
880
+ * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
881
+ */
882
+ getSnapshot() {
883
+ return this._snapshot;
884
+ }
885
+ }
886
+
887
+ /**
888
+ * Creates a new actor instance for the given actor logic with the provided options, if any.
889
+ *
890
+ * @remarks
891
+ * When you create an actor from actor logic via `createActor(logic)`, you implicitly create an actor system where the created actor is the root actor.
892
+ * Any actors spawned from this root actor and its descendants are part of that actor system.
893
+ *
894
+ * @example
895
+ * ```ts
896
+ * import { createActor } from 'xstate';
897
+ * import { someActorLogic } from './someActorLogic.ts';
898
+ *
899
+ * // Creating the actor, which implicitly creates an actor system with itself as the root actor
900
+ * const actor = createActor(someActorLogic);
901
+ *
902
+ * actor.subscribe((snapshot) => {
903
+ * console.log(snapshot);
904
+ * });
905
+ *
906
+ * // Actors must be started by calling `actor.start()`, which will also start the actor system.
907
+ * actor.start();
908
+ *
909
+ * // Actors can receive events
910
+ * actor.send({ type: 'someEvent' });
911
+ *
912
+ * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
913
+ * actor.stop();
914
+ * ```
915
+ *
916
+ * @param logic - The actor logic to create an actor from. For a state machine actor logic creator, see {@link createMachine}. Other actor logic creators include {@link fromCallback}, {@link fromEventObservable}, {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.
917
+ * @param options - Actor options
918
+ */
919
+
920
+ function createActor(logic, options) {
921
+ const interpreter = new Actor(logic, options);
922
+ return interpreter;
923
+ }
924
+
925
+ /**
926
+ * Creates a new Interpreter instance for the given machine with the provided options, if any.
927
+ *
928
+ * @deprecated Use `createActor` instead
929
+ */
930
+ const interpret = createActor;
931
+
932
+ /**
933
+ * @deprecated Use `Actor` instead.
934
+ */
935
+
936
+ function resolveCancel(_, snapshot, actionArgs, actionParams, {
937
+ sendId
938
+ }) {
939
+ const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;
940
+ return [snapshot, resolvedSendId];
941
+ }
942
+ function executeCancel(actorScope, resolvedSendId) {
943
+ actorScope.self.cancel(resolvedSendId);
944
+ }
945
+ /**
946
+ * Cancels an in-flight `send(...)` action. A canceled sent action will not
947
+ * be executed, nor will its event be sent, unless it has already been sent
948
+ * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).
949
+ *
950
+ * @param sendId The `id` of the `send(...)` action to cancel.
951
+ */
952
+ function cancel(sendId) {
953
+ function cancel(args, params) {
954
+ }
955
+ cancel.type = 'xstate.cancel';
956
+ cancel.sendId = sendId;
957
+ cancel.resolve = resolveCancel;
958
+ cancel.execute = executeCancel;
959
+ return cancel;
960
+ }
961
+
962
+ function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {
963
+ id,
964
+ systemId,
965
+ src,
966
+ input,
967
+ syncSnapshot
968
+ }) {
969
+ const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;
970
+ const resolvedId = typeof id === 'function' ? id(actionArgs) : id;
971
+ let actorRef;
972
+ if (logic) {
973
+ actorRef = createActor(logic, {
974
+ id: resolvedId,
975
+ src,
976
+ parent: actorScope?.self,
977
+ syncSnapshot,
978
+ systemId,
979
+ input: typeof input === 'function' ? input({
980
+ context: snapshot.context,
981
+ event: actionArgs.event,
982
+ self: actorScope?.self
983
+ }) : input
984
+ });
985
+ }
986
+ return [cloneMachineSnapshot(snapshot, {
987
+ children: {
988
+ ...snapshot.children,
989
+ [resolvedId]: actorRef
990
+ }
991
+ }), {
992
+ id,
993
+ actorRef
994
+ }];
995
+ }
996
+ function executeSpawn(actorScope, {
997
+ id,
998
+ actorRef
999
+ }) {
1000
+ if (!actorRef) {
1001
+ return;
1002
+ }
1003
+ actorScope.defer(() => {
1004
+ if (actorRef._processingStatus === ProcessingStatus.Stopped) {
1005
+ return;
1006
+ }
1007
+ actorRef.start();
1008
+ });
1009
+ }
1010
+ function spawnChild(...[src, {
1011
+ id,
1012
+ systemId,
1013
+ input,
1014
+ syncSnapshot = false
1015
+ } = {}]) {
1016
+ function spawnChild(args, params) {
1017
+ }
1018
+ spawnChild.type = 'snapshot.spawnChild';
1019
+ spawnChild.id = id;
1020
+ spawnChild.systemId = systemId;
1021
+ spawnChild.src = src;
1022
+ spawnChild.input = input;
1023
+ spawnChild.syncSnapshot = syncSnapshot;
1024
+ spawnChild.resolve = resolveSpawn;
1025
+ spawnChild.execute = executeSpawn;
1026
+ return spawnChild;
1027
+ }
1028
+
1029
+ function resolveStop(_, snapshot, args, actionParams, {
1030
+ actorRef
1031
+ }) {
1032
+ const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;
1033
+ const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;
1034
+ let children = snapshot.children;
1035
+ if (resolvedActorRef) {
1036
+ children = {
1037
+ ...children
1038
+ };
1039
+ delete children[resolvedActorRef.id];
1040
+ }
1041
+ return [cloneMachineSnapshot(snapshot, {
1042
+ children
1043
+ }), resolvedActorRef];
1044
+ }
1045
+ function executeStop(actorScope, actorRef) {
1046
+ if (!actorRef) {
1047
+ return;
1048
+ }
1049
+
1050
+ // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately
1051
+ // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)
1052
+ // this could throw on `systemId` collision, for example, when dealing with reentering transitions
1053
+ actorScope.system._unregister(actorRef);
1054
+
1055
+ // this allows us to prevent an actor from being started if it gets stopped within the same macrostep
1056
+ // this can happen, for example, when the invoking state is being exited immediately by an always transition
1057
+ if (actorRef._processingStatus !== ProcessingStatus.Running) {
1058
+ actorScope.stopChild(actorRef);
1059
+ return;
1060
+ }
1061
+ // stopping a child enqueues a stop event in the child actor's mailbox
1062
+ // we need for all of the already enqueued events to be processed before we stop the child
1063
+ // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)
1064
+ // and we don't want to ignore those events
1065
+ actorScope.defer(() => {
1066
+ actorScope.stopChild(actorRef);
1067
+ });
1068
+ }
1069
+ /**
1070
+ * Stops a child actor.
1071
+ *
1072
+ * @param actorRef The actor to stop.
1073
+ */
1074
+ function stopChild(actorRef) {
1075
+ function stop(args, params) {
1076
+ }
1077
+ stop.type = 'xstate.stopChild';
1078
+ stop.actorRef = actorRef;
1079
+ stop.resolve = resolveStop;
1080
+ stop.execute = executeStop;
1081
+ return stop;
1082
+ }
1083
+
1084
+ /**
1085
+ * Stops a child actor.
1086
+ *
1087
+ * @deprecated Use `stopChild(...)` instead
1088
+ */
1089
+ const stop = stopChild;
1090
+
1091
+ function checkStateIn(snapshot, _, {
1092
+ stateValue
1093
+ }) {
1094
+ if (typeof stateValue === 'string' && isStateId(stateValue)) {
1095
+ const target = snapshot.machine.getStateNodeById(stateValue);
1096
+ return snapshot._nodes.some(sn => sn === target);
1097
+ }
1098
+ return snapshot.matches(stateValue);
1099
+ }
1100
+ function stateIn(stateValue) {
1101
+ function stateIn(args, params) {
1102
+ return false;
1103
+ }
1104
+ stateIn.check = checkStateIn;
1105
+ stateIn.stateValue = stateValue;
1106
+ return stateIn;
1107
+ }
1108
+ function checkNot(snapshot, {
1109
+ context,
1110
+ event
1111
+ }, {
1112
+ guards
1113
+ }) {
1114
+ return !evaluateGuard(guards[0], context, event, snapshot);
1115
+ }
1116
+ function not(guard) {
1117
+ function not(args, params) {
1118
+ return false;
1119
+ }
1120
+ not.check = checkNot;
1121
+ not.guards = [guard];
1122
+ return not;
1123
+ }
1124
+ function checkAnd(snapshot, {
1125
+ context,
1126
+ event
1127
+ }, {
1128
+ guards
1129
+ }) {
1130
+ return guards.every(guard => evaluateGuard(guard, context, event, snapshot));
1131
+ }
1132
+ function and(guards) {
1133
+ function and(args, params) {
1134
+ return false;
1135
+ }
1136
+ and.check = checkAnd;
1137
+ and.guards = guards;
1138
+ return and;
1139
+ }
1140
+ function checkOr(snapshot, {
1141
+ context,
1142
+ event
1143
+ }, {
1144
+ guards
1145
+ }) {
1146
+ return guards.some(guard => evaluateGuard(guard, context, event, snapshot));
1147
+ }
1148
+ function or(guards) {
1149
+ function or(args, params) {
1150
+ return false;
1151
+ }
1152
+ or.check = checkOr;
1153
+ or.guards = guards;
1154
+ return or;
1155
+ }
1156
+
1157
+ // TODO: throw on cycles (depth check should be enough)
1158
+ function evaluateGuard(guard, context, event, snapshot) {
1159
+ const {
1160
+ machine
1161
+ } = snapshot;
1162
+ const isInline = typeof guard === 'function';
1163
+ const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];
1164
+ if (!isInline && !resolved) {
1165
+ throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);
1166
+ }
1167
+ if (typeof resolved !== 'function') {
1168
+ return evaluateGuard(resolved, context, event, snapshot);
1169
+ }
1170
+ const guardArgs = {
1171
+ context,
1172
+ event
1173
+ };
1174
+ const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({
1175
+ context,
1176
+ event
1177
+ }) : guard.params : undefined;
1178
+ if (!('check' in resolved)) {
1179
+ // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
1180
+ // inline guards expect `TExpressionGuard` to be set to `undefined`
1181
+ // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
1182
+ return resolved(guardArgs, guardParams);
1183
+ }
1184
+ const builtinGuard = resolved;
1185
+ return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params
1186
+ );
1187
+ }
1188
+
1189
+ const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1190
+ function getChildren(stateNode) {
1191
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1192
+ }
1193
+ function getProperAncestors(stateNode, toStateNode) {
1194
+ const ancestors = [];
1195
+ if (toStateNode === stateNode) {
1196
+ return ancestors;
1197
+ }
1198
+
1199
+ // add all ancestors
1200
+ let m = stateNode.parent;
1201
+ while (m && m !== toStateNode) {
1202
+ ancestors.push(m);
1203
+ m = m.parent;
1204
+ }
1205
+ return ancestors;
1206
+ }
1207
+ function getAllStateNodes(stateNodes) {
1208
+ const nodeSet = new Set(stateNodes);
1209
+ const adjList = getAdjList(nodeSet);
1210
+
1211
+ // add descendants
1212
+ for (const s of nodeSet) {
1213
+ // if previously active, add existing child nodes
1214
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1215
+ getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));
1216
+ } else {
1217
+ if (s.type === 'parallel') {
1218
+ for (const child of getChildren(s)) {
1219
+ if (child.type === 'history') {
1220
+ continue;
1221
+ }
1222
+ if (!nodeSet.has(child)) {
1223
+ const initialStates = getInitialStateNodesWithTheirAncestors(child);
1224
+ for (const initialStateNode of initialStates) {
1225
+ nodeSet.add(initialStateNode);
1226
+ }
1227
+ }
1228
+ }
1229
+ }
1230
+ }
1231
+ }
1232
+
1233
+ // add all ancestors
1234
+ for (const s of nodeSet) {
1235
+ let m = s.parent;
1236
+ while (m) {
1237
+ nodeSet.add(m);
1238
+ m = m.parent;
1239
+ }
1240
+ }
1241
+ return nodeSet;
1242
+ }
1243
+ function getValueFromAdj(baseNode, adjList) {
1244
+ const childStateNodes = adjList.get(baseNode);
1245
+ if (!childStateNodes) {
1246
+ return {}; // todo: fix?
1247
+ }
1248
+
1249
+ if (baseNode.type === 'compound') {
1250
+ const childStateNode = childStateNodes[0];
1251
+ if (childStateNode) {
1252
+ if (isAtomicStateNode(childStateNode)) {
1253
+ return childStateNode.key;
1254
+ }
1255
+ } else {
1256
+ return {};
1257
+ }
1258
+ }
1259
+ const stateValue = {};
1260
+ for (const childStateNode of childStateNodes) {
1261
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1262
+ }
1263
+ return stateValue;
1264
+ }
1265
+ function getAdjList(stateNodes) {
1266
+ const adjList = new Map();
1267
+ for (const s of stateNodes) {
1268
+ if (!adjList.has(s)) {
1269
+ adjList.set(s, []);
1270
+ }
1271
+ if (s.parent) {
1272
+ if (!adjList.has(s.parent)) {
1273
+ adjList.set(s.parent, []);
1274
+ }
1275
+ adjList.get(s.parent).push(s);
1276
+ }
1277
+ }
1278
+ return adjList;
1279
+ }
1280
+ function getStateValue(rootNode, stateNodes) {
1281
+ const config = getAllStateNodes(stateNodes);
1282
+ return getValueFromAdj(rootNode, getAdjList(config));
1283
+ }
1284
+ function isInFinalState(stateNodeSet, stateNode) {
1285
+ if (stateNode.type === 'compound') {
1286
+ return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));
1287
+ }
1288
+ if (stateNode.type === 'parallel') {
1289
+ return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));
1290
+ }
1291
+ return stateNode.type === 'final';
1292
+ }
1293
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
1294
+ function getCandidates(stateNode, receivedEventType) {
1295
+ const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(descriptor => {
1296
+ // check if transition is a wildcard transition,
1297
+ // which matches any non-transient events
1298
+ if (descriptor === WILDCARD) {
1299
+ return true;
1300
+ }
1301
+ if (!descriptor.endsWith('.*')) {
1302
+ return false;
1303
+ }
1304
+ const partialEventTokens = descriptor.split('.');
1305
+ const eventTokens = receivedEventType.split('.');
1306
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1307
+ const partialEventToken = partialEventTokens[tokenIndex];
1308
+ const eventToken = eventTokens[tokenIndex];
1309
+ if (partialEventToken === '*') {
1310
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
1311
+ return isLastToken;
1312
+ }
1313
+ if (partialEventToken !== eventToken) {
1314
+ return false;
1315
+ }
1316
+ }
1317
+ return true;
1318
+ }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
1319
+ return candidates;
1320
+ }
1321
+
1322
+ /**
1323
+ * All delayed transitions from the config.
1324
+ */
1325
+ function getDelayedTransitions(stateNode) {
1326
+ const afterConfig = stateNode.config.after;
1327
+ if (!afterConfig) {
1328
+ return [];
1329
+ }
1330
+ const mutateEntryExit = (delay, i) => {
1331
+ const afterEvent = createAfterEvent(delay, stateNode.id);
1332
+ const eventType = afterEvent.type;
1333
+ stateNode.entry.push(raise(afterEvent, {
1334
+ id: eventType,
1335
+ delay
1336
+ }));
1337
+ stateNode.exit.push(cancel(eventType));
1338
+ return eventType;
1339
+ };
1340
+ const delayedTransitions = Object.keys(afterConfig).flatMap((delay, i) => {
1341
+ const configTransition = afterConfig[delay];
1342
+ const resolvedTransition = typeof configTransition === 'string' ? {
1343
+ target: configTransition
1344
+ } : configTransition;
1345
+ const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
1346
+ const eventType = mutateEntryExit(resolvedDelay);
1347
+ return toArray(resolvedTransition).map(transition => ({
1348
+ ...transition,
1349
+ event: eventType,
1350
+ delay: resolvedDelay
1351
+ }));
1352
+ });
1353
+ return delayedTransitions.map(delayedTransition => {
1354
+ const {
1355
+ delay
1356
+ } = delayedTransition;
1357
+ return {
1358
+ ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
1359
+ delay
1360
+ };
1361
+ });
1362
+ }
1363
+ function formatTransition(stateNode, descriptor, transitionConfig) {
1364
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1365
+ const reenter = transitionConfig.reenter ?? false;
1366
+ const target = resolveTarget(stateNode, normalizedTarget);
1367
+ const transition = {
1368
+ ...transitionConfig,
1369
+ actions: toArray(transitionConfig.actions),
1370
+ guard: transitionConfig.guard,
1371
+ target,
1372
+ source: stateNode,
1373
+ reenter,
1374
+ eventType: descriptor,
1375
+ toJSON: () => ({
1376
+ ...transition,
1377
+ source: `#${stateNode.id}`,
1378
+ target: target ? target.map(t => `#${t.id}`) : undefined
1379
+ })
1380
+ };
1381
+ return transition;
1382
+ }
1383
+ function formatTransitions(stateNode) {
1384
+ const transitions = new Map();
1385
+ if (stateNode.config.on) {
1386
+ for (const descriptor of Object.keys(stateNode.config.on)) {
1387
+ if (descriptor === NULL_EVENT) {
1388
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1389
+ }
1390
+ const transitionsConfig = stateNode.config.on[descriptor];
1391
+ transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
1392
+ }
1393
+ }
1394
+ if (stateNode.config.onDone) {
1395
+ const descriptor = `xstate.done.state.${stateNode.id}`;
1396
+ transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1397
+ }
1398
+ for (const invokeDef of stateNode.invoke) {
1399
+ if (invokeDef.onDone) {
1400
+ const descriptor = `xstate.done.actor.${invokeDef.id}`;
1401
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1402
+ }
1403
+ if (invokeDef.onError) {
1404
+ const descriptor = `xstate.error.actor.${invokeDef.id}`;
1405
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
1406
+ }
1407
+ if (invokeDef.onSnapshot) {
1408
+ const descriptor = `xstate.snapshot.${invokeDef.id}`;
1409
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
1410
+ }
1411
+ }
1412
+ for (const delayedTransition of stateNode.after) {
1413
+ let existing = transitions.get(delayedTransition.eventType);
1414
+ if (!existing) {
1415
+ existing = [];
1416
+ transitions.set(delayedTransition.eventType, existing);
1417
+ }
1418
+ existing.push(delayedTransition);
1419
+ }
1420
+ return transitions;
1421
+ }
1422
+ function formatInitialTransition(stateNode, _target) {
1423
+ const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;
1424
+ if (!resolvedTarget && _target) {
1425
+ throw new Error(`Initial state node "${_target}" not found on parent state node #${stateNode.id}`);
1426
+ }
1427
+ const transition = {
1428
+ source: stateNode,
1429
+ actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),
1430
+ eventType: null,
1431
+ reenter: false,
1432
+ target: resolvedTarget ? [resolvedTarget] : [],
1433
+ toJSON: () => ({
1434
+ ...transition,
1435
+ source: `#${stateNode.id}`,
1436
+ target: resolvedTarget ? [`#${resolvedTarget.id}`] : []
1437
+ })
1438
+ };
1439
+ return transition;
1440
+ }
1441
+ function resolveTarget(stateNode, targets) {
1442
+ if (targets === undefined) {
1443
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1444
+ return undefined;
1445
+ }
1446
+ return targets.map(target => {
1447
+ if (typeof target !== 'string') {
1448
+ return target;
1449
+ }
1450
+ if (isStateId(target)) {
1451
+ return stateNode.machine.getStateNodeById(target);
1452
+ }
1453
+ const isInternalTarget = target[0] === STATE_DELIMITER;
1454
+ // If internal target is defined on machine,
1455
+ // do not include machine key on target
1456
+ if (isInternalTarget && !stateNode.parent) {
1457
+ return getStateNodeByPath(stateNode, target.slice(1));
1458
+ }
1459
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1460
+ if (stateNode.parent) {
1461
+ try {
1462
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1463
+ return targetStateNode;
1464
+ } catch (err) {
1465
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1466
+ }
1467
+ } else {
1468
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1469
+ }
1470
+ });
1471
+ }
1472
+ function resolveHistoryDefaultTransition(stateNode) {
1473
+ const normalizedTarget = normalizeTarget(stateNode.config.target);
1474
+ if (!normalizedTarget) {
1475
+ return stateNode.parent.initial;
1476
+ }
1477
+ return {
1478
+ target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)
1479
+ };
1480
+ }
1481
+ function isHistoryNode(stateNode) {
1482
+ return stateNode.type === 'history';
1483
+ }
1484
+ function getInitialStateNodesWithTheirAncestors(stateNode) {
1485
+ const states = getInitialStateNodes(stateNode);
1486
+ for (const initialState of states) {
1487
+ for (const ancestor of getProperAncestors(initialState, stateNode)) {
1488
+ states.add(ancestor);
1489
+ }
1490
+ }
1491
+ return states;
1492
+ }
1493
+ function getInitialStateNodes(stateNode) {
1494
+ const set = new Set();
1495
+ function iter(descStateNode) {
1496
+ if (set.has(descStateNode)) {
1497
+ return;
1498
+ }
1499
+ set.add(descStateNode);
1500
+ if (descStateNode.type === 'compound') {
1501
+ iter(descStateNode.initial.target[0]);
1502
+ } else if (descStateNode.type === 'parallel') {
1503
+ for (const child of getChildren(descStateNode)) {
1504
+ iter(child);
1505
+ }
1506
+ }
1507
+ }
1508
+ iter(stateNode);
1509
+ return set;
1510
+ }
1511
+ /**
1512
+ * Returns the child state node from its relative `stateKey`, or throws.
1513
+ */
1514
+ function getStateNode(stateNode, stateKey) {
1515
+ if (isStateId(stateKey)) {
1516
+ return stateNode.machine.getStateNodeById(stateKey);
1517
+ }
1518
+ if (!stateNode.states) {
1519
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1520
+ }
1521
+ const result = stateNode.states[stateKey];
1522
+ if (!result) {
1523
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1524
+ }
1525
+ return result;
1526
+ }
1527
+
1528
+ /**
1529
+ * Returns the relative state node from the given `statePath`, or throws.
1530
+ *
1531
+ * @param statePath The string or string array relative path to the state node.
1532
+ */
1533
+ function getStateNodeByPath(stateNode, statePath) {
1534
+ if (typeof statePath === 'string' && isStateId(statePath)) {
1535
+ try {
1536
+ return stateNode.machine.getStateNodeById(statePath);
1537
+ } catch (e) {
1538
+ // try individual paths
1539
+ // throw e;
1540
+ }
1541
+ }
1542
+ const arrayStatePath = toStatePath(statePath).slice();
1543
+ let currentStateNode = stateNode;
1544
+ while (arrayStatePath.length) {
1545
+ const key = arrayStatePath.shift();
1546
+ if (!key.length) {
1547
+ break;
1548
+ }
1549
+ currentStateNode = getStateNode(currentStateNode, key);
1550
+ }
1551
+ return currentStateNode;
1552
+ }
1553
+
1554
+ /**
1555
+ * Returns the state nodes represented by the current state value.
1556
+ *
1557
+ * @param stateValue The state value or State instance
1558
+ */
1559
+ function getStateNodes(stateNode, stateValue) {
1560
+ if (typeof stateValue === 'string') {
1561
+ return [stateNode, stateNode.states[stateValue]];
1562
+ }
1563
+ const childStateKeys = Object.keys(stateValue);
1564
+ const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
1565
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
1566
+ const subStateNode = getStateNode(stateNode, subStateKey);
1567
+ if (!subStateNode) {
1568
+ return allSubStateNodes;
1569
+ }
1570
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
1571
+ return allSubStateNodes.concat(subStateNodes);
1572
+ }, []));
1573
+ }
1574
+ function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
1575
+ const childStateNode = getStateNode(stateNode, stateValue);
1576
+ const next = childStateNode.next(snapshot, event);
1577
+ if (!next || !next.length) {
1578
+ return stateNode.next(snapshot, event);
1579
+ }
1580
+ return next;
1581
+ }
1582
+ function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
1583
+ const subStateKeys = Object.keys(stateValue);
1584
+ const childStateNode = getStateNode(stateNode, subStateKeys[0]);
1585
+ const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);
1586
+ if (!next || !next.length) {
1587
+ return stateNode.next(snapshot, event);
1588
+ }
1589
+ return next;
1590
+ }
1591
+ function transitionParallelNode(stateNode, stateValue, snapshot, event) {
1592
+ const allInnerTransitions = [];
1593
+ for (const subStateKey of Object.keys(stateValue)) {
1594
+ const subStateValue = stateValue[subStateKey];
1595
+ if (!subStateValue) {
1596
+ continue;
1597
+ }
1598
+ const subStateNode = getStateNode(stateNode, subStateKey);
1599
+ const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);
1600
+ if (innerTransitions) {
1601
+ allInnerTransitions.push(...innerTransitions);
1602
+ }
1603
+ }
1604
+ if (!allInnerTransitions.length) {
1605
+ return stateNode.next(snapshot, event);
1606
+ }
1607
+ return allInnerTransitions;
1608
+ }
1609
+ function transitionNode(stateNode, stateValue, snapshot, event) {
1610
+ // leaf node
1611
+ if (typeof stateValue === 'string') {
1612
+ return transitionAtomicNode(stateNode, stateValue, snapshot, event);
1613
+ }
1614
+
1615
+ // compound node
1616
+ if (Object.keys(stateValue).length === 1) {
1617
+ return transitionCompoundNode(stateNode, stateValue, snapshot, event);
1618
+ }
1619
+
1620
+ // parallel node
1621
+ return transitionParallelNode(stateNode, stateValue, snapshot, event);
1622
+ }
1623
+ function getHistoryNodes(stateNode) {
1624
+ return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
1625
+ }
1626
+ function isDescendant(childStateNode, parentStateNode) {
1627
+ let marker = childStateNode;
1628
+ while (marker.parent && marker.parent !== parentStateNode) {
1629
+ marker = marker.parent;
1630
+ }
1631
+ return marker.parent === parentStateNode;
1632
+ }
1633
+ function hasIntersection(s1, s2) {
1634
+ const set1 = new Set(s1);
1635
+ const set2 = new Set(s2);
1636
+ for (const item of set1) {
1637
+ if (set2.has(item)) {
1638
+ return true;
1639
+ }
1640
+ }
1641
+ for (const item of set2) {
1642
+ if (set1.has(item)) {
1643
+ return true;
1644
+ }
1645
+ }
1646
+ return false;
1647
+ }
1648
+ function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
1649
+ const filteredTransitions = new Set();
1650
+ for (const t1 of enabledTransitions) {
1651
+ let t1Preempted = false;
1652
+ const transitionsToRemove = new Set();
1653
+ for (const t2 of filteredTransitions) {
1654
+ if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {
1655
+ if (isDescendant(t1.source, t2.source)) {
1656
+ transitionsToRemove.add(t2);
1657
+ } else {
1658
+ t1Preempted = true;
1659
+ break;
1660
+ }
1661
+ }
1662
+ }
1663
+ if (!t1Preempted) {
1664
+ for (const t3 of transitionsToRemove) {
1665
+ filteredTransitions.delete(t3);
1666
+ }
1667
+ filteredTransitions.add(t1);
1668
+ }
1669
+ }
1670
+ return Array.from(filteredTransitions);
1671
+ }
1672
+ function findLeastCommonAncestor(stateNodes) {
1673
+ const [head, ...tail] = stateNodes;
1674
+ for (const ancestor of getProperAncestors(head, undefined)) {
1675
+ if (tail.every(sn => isDescendant(sn, ancestor))) {
1676
+ return ancestor;
1677
+ }
1678
+ }
1679
+ }
1680
+ function getEffectiveTargetStates(transition, historyValue) {
1681
+ if (!transition.target) {
1682
+ return [];
1683
+ }
1684
+ const targets = new Set();
1685
+ for (const targetNode of transition.target) {
1686
+ if (isHistoryNode(targetNode)) {
1687
+ if (historyValue[targetNode.id]) {
1688
+ for (const node of historyValue[targetNode.id]) {
1689
+ targets.add(node);
1690
+ }
1691
+ } else {
1692
+ for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {
1693
+ targets.add(node);
1694
+ }
1695
+ }
1696
+ } else {
1697
+ targets.add(targetNode);
1698
+ }
1699
+ }
1700
+ return [...targets];
1701
+ }
1702
+ function getTransitionDomain(transition, historyValue) {
1703
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
1704
+ if (!targetStates) {
1705
+ return;
1706
+ }
1707
+ if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {
1708
+ return transition.source;
1709
+ }
1710
+ const lca = findLeastCommonAncestor(targetStates.concat(transition.source));
1711
+ if (lca) {
1712
+ return lca;
1713
+ }
1714
+
1715
+ // at this point we know that it's a root transition since LCA couldn't be found
1716
+ if (transition.reenter) {
1717
+ return;
1718
+ }
1719
+ return transition.source.machine.root;
1720
+ }
1721
+ function computeExitSet(transitions, stateNodeSet, historyValue) {
1722
+ const statesToExit = new Set();
1723
+ for (const t of transitions) {
1724
+ if (t.target?.length) {
1725
+ const domain = getTransitionDomain(t, historyValue);
1726
+ if (t.reenter && t.source === domain) {
1727
+ statesToExit.add(domain);
1728
+ }
1729
+ for (const stateNode of stateNodeSet) {
1730
+ if (isDescendant(stateNode, domain)) {
1731
+ statesToExit.add(stateNode);
1732
+ }
1733
+ }
1734
+ }
1735
+ }
1736
+ return [...statesToExit];
1737
+ }
1738
+ function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
1739
+ if (prevStateNodes.length !== nextStateNodeSet.size) {
1740
+ return false;
1741
+ }
1742
+ for (const node of prevStateNodes) {
1743
+ if (!nextStateNodeSet.has(node)) {
1744
+ return false;
1745
+ }
1746
+ }
1747
+ return true;
1748
+ }
1749
+
1750
+ /**
1751
+ * https://www.w3.org/TR/scxml/#microstepProcedure
1752
+ */
1753
+ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
1754
+ if (!transitions.length) {
1755
+ return currentSnapshot;
1756
+ }
1757
+ const mutStateNodeSet = new Set(currentSnapshot._nodes);
1758
+ let historyValue = currentSnapshot.historyValue;
1759
+ const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
1760
+ let nextState = currentSnapshot;
1761
+
1762
+ // Exit states
1763
+ if (!isInitial) {
1764
+ [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue);
1765
+ }
1766
+
1767
+ // Execute transition content
1768
+ nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue);
1769
+
1770
+ // Enter states
1771
+ nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
1772
+ const nextStateNodes = [...mutStateNodeSet];
1773
+ if (nextState.status === 'done') {
1774
+ nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue);
1775
+ }
1776
+ try {
1777
+ if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {
1778
+ return nextState;
1779
+ }
1780
+ return cloneMachineSnapshot(nextState, {
1781
+ _nodes: nextStateNodes,
1782
+ historyValue
1783
+ });
1784
+ } catch (e) {
1785
+ // TODO: Refactor this once proper error handling is implemented.
1786
+ // See https://github.com/statelyai/rfcs/pull/4
1787
+ throw e;
1788
+ }
1789
+ }
1790
+ function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
1791
+ if (!rootNode.output) {
1792
+ return;
1793
+ }
1794
+ const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);
1795
+ return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
1796
+ }
1797
+ function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
1798
+ let nextSnapshot = currentSnapshot;
1799
+ const statesToEnter = new Set();
1800
+ // those are states that were directly targeted or indirectly targeted by the explicit target
1801
+ // in other words, those are states for which initial actions should be executed
1802
+ // when we target `#deep_child` initial actions of its ancestors shouldn't be executed
1803
+ const statesForDefaultEntry = new Set();
1804
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
1805
+
1806
+ // In the initial state, the root state node is "entered".
1807
+ if (isInitial) {
1808
+ statesForDefaultEntry.add(currentSnapshot.machine.root);
1809
+ }
1810
+ const completedNodes = new Set();
1811
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
1812
+ mutStateNodeSet.add(stateNodeToEnter);
1813
+ const actions = [];
1814
+
1815
+ // Add entry actions
1816
+ actions.push(...stateNodeToEnter.entry);
1817
+ for (const invokeDef of stateNodeToEnter.invoke) {
1818
+ actions.push(spawnChild(invokeDef.src, {
1819
+ ...invokeDef,
1820
+ syncSnapshot: !!invokeDef.onSnapshot
1821
+ }));
1822
+ }
1823
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
1824
+ const initialActions = stateNodeToEnter.initial.actions;
1825
+ actions.push(...initialActions);
1826
+ }
1827
+ nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));
1828
+ if (stateNodeToEnter.type === 'final') {
1829
+ const parent = stateNodeToEnter.parent;
1830
+ let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;
1831
+ let rootCompletionNode = ancestorMarker || stateNodeToEnter;
1832
+ if (parent?.type === 'compound') {
1833
+ internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));
1834
+ }
1835
+ while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
1836
+ completedNodes.add(ancestorMarker);
1837
+ internalQueue.push(createDoneStateEvent(ancestorMarker.id));
1838
+ rootCompletionNode = ancestorMarker;
1839
+ ancestorMarker = ancestorMarker.parent;
1840
+ }
1841
+ if (ancestorMarker) {
1842
+ continue;
1843
+ }
1844
+ nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
1845
+ status: 'done',
1846
+ output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
1847
+ });
1848
+ }
1849
+ }
1850
+ return nextSnapshot;
1851
+ }
1852
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
1853
+ for (const t of transitions) {
1854
+ const domain = getTransitionDomain(t, historyValue);
1855
+ for (const s of t.target || []) {
1856
+ if (!isHistoryNode(s) && (
1857
+ // if the target is different than the source then it will *definitely* be entered
1858
+ t.source !== s ||
1859
+ // we know that the domain can't lie within the source
1860
+ // if it's different than the source then it's outside of it and it means that the target has to be entered as well
1861
+ t.source !== domain ||
1862
+ // reentering transitions always enter the target, even if it's the source itself
1863
+ t.reenter)) {
1864
+ statesToEnter.add(s);
1865
+ statesForDefaultEntry.add(s);
1866
+ }
1867
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
1868
+ }
1869
+ const targetStates = getEffectiveTargetStates(t, historyValue);
1870
+ for (const s of targetStates) {
1871
+ const ancestors = getProperAncestors(s, domain);
1872
+ if (domain?.type === 'parallel') {
1873
+ ancestors.push(domain);
1874
+ }
1875
+ addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);
1876
+ }
1877
+ }
1878
+ }
1879
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
1880
+ if (isHistoryNode(stateNode)) {
1881
+ if (historyValue[stateNode.id]) {
1882
+ const historyStateNodes = historyValue[stateNode.id];
1883
+ for (const s of historyStateNodes) {
1884
+ statesToEnter.add(s);
1885
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
1886
+ }
1887
+ for (const s of historyStateNodes) {
1888
+ addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
1889
+ }
1890
+ } else {
1891
+ const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
1892
+ for (const s of historyDefaultTransition.target) {
1893
+ statesToEnter.add(s);
1894
+ if (historyDefaultTransition === stateNode.parent?.initial) {
1895
+ statesForDefaultEntry.add(stateNode.parent);
1896
+ }
1897
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
1898
+ }
1899
+ for (const s of historyDefaultTransition.target) {
1900
+ addProperAncestorStatesToEnter(s, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
1901
+ }
1902
+ }
1903
+ } else {
1904
+ if (stateNode.type === 'compound') {
1905
+ const [initialState] = stateNode.initial.target;
1906
+ if (!isHistoryNode(initialState)) {
1907
+ statesToEnter.add(initialState);
1908
+ statesForDefaultEntry.add(initialState);
1909
+ }
1910
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
1911
+ addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
1912
+ } else {
1913
+ if (stateNode.type === 'parallel') {
1914
+ for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
1915
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
1916
+ if (!isHistoryNode(child)) {
1917
+ statesToEnter.add(child);
1918
+ statesForDefaultEntry.add(child);
1919
+ }
1920
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
1921
+ }
1922
+ }
1923
+ }
1924
+ }
1925
+ }
1926
+ }
1927
+ function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
1928
+ for (const anc of ancestors) {
1929
+ if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
1930
+ statesToEnter.add(anc);
1931
+ }
1932
+ if (anc.type === 'parallel') {
1933
+ for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
1934
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
1935
+ statesToEnter.add(child);
1936
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
1937
+ }
1938
+ }
1939
+ }
1940
+ }
1941
+ }
1942
+ function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
1943
+ addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
1944
+ }
1945
+ function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue) {
1946
+ let nextSnapshot = currentSnapshot;
1947
+ const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
1948
+ statesToExit.sort((a, b) => b.order - a.order);
1949
+ let changedHistory;
1950
+
1951
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
1952
+ for (const exitStateNode of statesToExit) {
1953
+ for (const historyNode of getHistoryNodes(exitStateNode)) {
1954
+ let predicate;
1955
+ if (historyNode.history === 'deep') {
1956
+ predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
1957
+ } else {
1958
+ predicate = sn => {
1959
+ return sn.parent === exitStateNode;
1960
+ };
1961
+ }
1962
+ changedHistory ??= {
1963
+ ...historyValue
1964
+ };
1965
+ changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
1966
+ }
1967
+ }
1968
+ for (const s of statesToExit) {
1969
+ nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue);
1970
+ mutStateNodeSet.delete(s);
1971
+ }
1972
+ return [nextSnapshot, changedHistory || historyValue];
1973
+ }
1974
+ function resolveActionsAndContextWorker(currentSnapshot, event, actorScope, actions, extra, retries) {
1975
+ const {
1976
+ machine
1977
+ } = currentSnapshot;
1978
+ let intermediateSnapshot = currentSnapshot;
1979
+ for (const action of actions) {
1980
+ const isInline = typeof action === 'function';
1981
+ const resolvedAction = isInline ? action :
1982
+ // the existing type of `.actions` assumes non-nullable `TExpressionAction`
1983
+ // it's fine to cast this here to get a common type and lack of errors in the rest of the code
1984
+ // our logic below makes sure that we call those 2 "variants" correctly
1985
+ machine.implementations.actions[typeof action === 'string' ? action : action.type];
1986
+ if (!resolvedAction) {
1987
+ continue;
1988
+ }
1989
+ const actionArgs = {
1990
+ context: intermediateSnapshot.context,
1991
+ event,
1992
+ self: actorScope?.self,
1993
+ system: actorScope?.system
1994
+ };
1995
+ const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({
1996
+ context: intermediateSnapshot.context,
1997
+ event
1998
+ }) : action.params : undefined;
1999
+ if (!('resolve' in resolvedAction)) {
2000
+ if (actorScope?.self._processingStatus === ProcessingStatus.Running) {
2001
+ resolvedAction(actionArgs, actionParams);
2002
+ } else {
2003
+ actorScope?.defer(() => {
2004
+ resolvedAction(actionArgs, actionParams);
2005
+ });
2006
+ }
2007
+ continue;
2008
+ }
2009
+ const builtinAction = resolvedAction;
2010
+ const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,
2011
+ // this holds all params
2012
+ extra);
2013
+ intermediateSnapshot = nextState;
2014
+ if ('retryResolve' in builtinAction) {
2015
+ retries?.push([builtinAction, params]);
2016
+ }
2017
+ if ('execute' in builtinAction) {
2018
+ if (actorScope?.self._processingStatus === ProcessingStatus.Running) {
2019
+ builtinAction.execute(actorScope, params);
2020
+ } else {
2021
+ actorScope?.defer(builtinAction.execute.bind(null, actorScope, params));
2022
+ }
2023
+ }
2024
+ if (actions) {
2025
+ intermediateSnapshot = resolveActionsAndContextWorker(intermediateSnapshot, event, actorScope, actions, extra, retries);
2026
+ }
2027
+ }
2028
+ return intermediateSnapshot;
2029
+ }
2030
+ function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
2031
+ const retries = deferredActorIds ? [] : undefined;
2032
+ const nextState = resolveActionsAndContextWorker(currentSnapshot, event, actorScope, actions, {
2033
+ internalQueue,
2034
+ deferredActorIds
2035
+ }, retries);
2036
+ retries?.forEach(([builtinAction, params]) => {
2037
+ builtinAction.retryResolve(actorScope, nextState, params);
2038
+ });
2039
+ return nextState;
2040
+ }
2041
+ function macrostep(snapshot, event, actorScope, internalQueue = []) {
2042
+ let nextSnapshot = snapshot;
2043
+ const states = [];
2044
+
2045
+ // Handle stop event
2046
+ if (event.type === XSTATE_STOP) {
2047
+ nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {
2048
+ status: 'stopped'
2049
+ });
2050
+ states.push(nextSnapshot);
2051
+ return {
2052
+ snapshot: nextSnapshot,
2053
+ microstates: states
2054
+ };
2055
+ }
2056
+ let nextEvent = event;
2057
+
2058
+ // Assume the state is at rest (no raised events)
2059
+ // Determine the next state based on the next microstep
2060
+ if (nextEvent.type !== XSTATE_INIT) {
2061
+ const currentEvent = nextEvent;
2062
+ const isErr = isErrorActorEvent(currentEvent);
2063
+ const transitions = selectTransitions(currentEvent, nextSnapshot);
2064
+ if (isErr && !transitions.length) {
2065
+ // TODO: we should likely only allow transitions selected by very explicit descriptors
2066
+ // `*` shouldn't be matched, likely `xstate.error.*` shouldnt be either
2067
+ // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
2068
+ nextSnapshot = cloneMachineSnapshot(snapshot, {
2069
+ status: 'error',
2070
+ error: currentEvent.error
2071
+ });
2072
+ states.push(nextSnapshot);
2073
+ return {
2074
+ snapshot: nextSnapshot,
2075
+ microstates: states
2076
+ };
2077
+ }
2078
+ nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false, internalQueue);
2079
+ states.push(nextSnapshot);
2080
+ }
2081
+ let shouldSelectEventlessTransitions = true;
2082
+ while (nextSnapshot.status === 'active') {
2083
+ let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];
2084
+
2085
+ // eventless transitions should always be selected after selecting *regular* transitions
2086
+ // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case
2087
+ const previousState = enabledTransitions.length ? nextSnapshot : undefined;
2088
+ if (!enabledTransitions.length) {
2089
+ if (!internalQueue.length) {
2090
+ break;
2091
+ }
2092
+ nextEvent = internalQueue.shift();
2093
+ enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
2094
+ }
2095
+ nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
2096
+ shouldSelectEventlessTransitions = nextSnapshot !== previousState;
2097
+ states.push(nextSnapshot);
2098
+ }
2099
+ if (nextSnapshot.status !== 'active') {
2100
+ stopChildren(nextSnapshot, nextEvent, actorScope);
2101
+ }
2102
+ return {
2103
+ snapshot: nextSnapshot,
2104
+ microstates: states
2105
+ };
2106
+ }
2107
+ function stopChildren(nextState, event, actorScope) {
2108
+ return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), []);
2109
+ }
2110
+ function selectTransitions(event, nextState) {
2111
+ return nextState.machine.getTransitionData(nextState, event);
2112
+ }
2113
+ function selectEventlessTransitions(nextState, event) {
2114
+ const enabledTransitionSet = new Set();
2115
+ const atomicStates = nextState._nodes.filter(isAtomicStateNode);
2116
+ for (const stateNode of atomicStates) {
2117
+ loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {
2118
+ if (!s.always) {
2119
+ continue;
2120
+ }
2121
+ for (const transition of s.always) {
2122
+ if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
2123
+ enabledTransitionSet.add(transition);
2124
+ break loop;
2125
+ }
2126
+ }
2127
+ }
2128
+ }
2129
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
2130
+ }
2131
+
2132
+ /**
2133
+ * Resolves a partial state value with its full representation in the state node's machine.
2134
+ *
2135
+ * @param stateValue The partial state value to resolve.
2136
+ */
2137
+ function resolveStateValue(rootNode, stateValue) {
2138
+ const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
2139
+ return getStateValue(rootNode, [...allStateNodes]);
2140
+ }
2141
+
2142
+ function isMachineSnapshot(value) {
2143
+ return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;
2144
+ }
2145
+ const machineSnapshotMatches = function matches(testValue) {
2146
+ return matchesState(testValue, this.value);
2147
+ };
2148
+ const machineSnapshotHasTag = function hasTag(tag) {
2149
+ return this.tags.has(tag);
2150
+ };
2151
+ const machineSnapshotCan = function can(event) {
2152
+ const transitionData = this.machine.getTransitionData(this, event);
2153
+ return !!transitionData?.length &&
2154
+ // Check that at least one transition is not forbidden
2155
+ transitionData.some(t => t.target !== undefined || t.actions.length);
2156
+ };
2157
+ const machineSnapshotToJSON = function toJSON() {
2158
+ const {
2159
+ _nodes: nodes,
2160
+ tags,
2161
+ machine,
2162
+ getMeta,
2163
+ toJSON,
2164
+ can,
2165
+ hasTag,
2166
+ matches,
2167
+ ...jsonValues
2168
+ } = this;
2169
+ return {
2170
+ ...jsonValues,
2171
+ tags: Array.from(tags)
2172
+ };
2173
+ };
2174
+ const machineSnapshotGetMeta = function getMeta() {
2175
+ return this._nodes.reduce((acc, stateNode) => {
2176
+ if (stateNode.meta !== undefined) {
2177
+ acc[stateNode.id] = stateNode.meta;
2178
+ }
2179
+ return acc;
2180
+ }, {});
2181
+ };
2182
+ function createMachineSnapshot(config, machine) {
2183
+ return {
2184
+ status: config.status,
2185
+ output: config.output,
2186
+ error: config.error,
2187
+ machine,
2188
+ context: config.context,
2189
+ _nodes: config._nodes,
2190
+ value: getStateValue(machine.root, config._nodes),
2191
+ tags: new Set(config._nodes.flatMap(sn => sn.tags)),
2192
+ children: config.children,
2193
+ historyValue: config.historyValue || {},
2194
+ matches: machineSnapshotMatches,
2195
+ hasTag: machineSnapshotHasTag,
2196
+ can: machineSnapshotCan,
2197
+ getMeta: machineSnapshotGetMeta,
2198
+ toJSON: machineSnapshotToJSON
2199
+ };
2200
+ }
2201
+ function cloneMachineSnapshot(snapshot, config = {}) {
2202
+ return createMachineSnapshot({
2203
+ ...snapshot,
2204
+ ...config
2205
+ }, snapshot.machine);
2206
+ }
2207
+ function getPersistedSnapshot(snapshot, options) {
2208
+ const {
2209
+ _nodes: nodes,
2210
+ tags,
2211
+ machine,
2212
+ children,
2213
+ context,
2214
+ can,
2215
+ hasTag,
2216
+ matches,
2217
+ getMeta,
2218
+ toJSON,
2219
+ ...jsonValues
2220
+ } = snapshot;
2221
+ const childrenJson = {};
2222
+ for (const id in children) {
2223
+ const child = children[id];
2224
+ childrenJson[id] = {
2225
+ snapshot: child.getPersistedSnapshot(options),
2226
+ src: child.src,
2227
+ systemId: child._systemId,
2228
+ syncSnapshot: child._syncSnapshot
2229
+ };
2230
+ }
2231
+ const persisted = {
2232
+ ...jsonValues,
2233
+ context: persistContext(context),
2234
+ children: childrenJson
2235
+ };
2236
+ return persisted;
2237
+ }
2238
+ function persistContext(contextPart) {
2239
+ let copy;
2240
+ for (const key in contextPart) {
2241
+ const value = contextPart[key];
2242
+ if (value && typeof value === 'object') {
2243
+ if ('sessionId' in value && 'send' in value && 'ref' in value) {
2244
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2245
+ ...contextPart
2246
+ };
2247
+ copy[key] = {
2248
+ xstate$$type: $$ACTOR_TYPE,
2249
+ id: value.id
2250
+ };
2251
+ } else {
2252
+ const result = persistContext(value);
2253
+ if (result !== value) {
2254
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2255
+ ...contextPart
2256
+ };
2257
+ copy[key] = result;
2258
+ }
2259
+ }
2260
+ }
2261
+ }
2262
+ return copy ?? contextPart;
2263
+ }
2264
+
2265
+ function resolveRaise(_, snapshot, args, actionParams, {
2266
+ event: eventOrExpr,
2267
+ id,
2268
+ delay
2269
+ }, {
2270
+ internalQueue
2271
+ }) {
2272
+ const delaysMap = snapshot.machine.implementations.delays;
2273
+ if (typeof eventOrExpr === 'string') {
2274
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
2275
+ }
2276
+ const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;
2277
+ let resolvedDelay;
2278
+ if (typeof delay === 'string') {
2279
+ const configDelay = delaysMap && delaysMap[delay];
2280
+ resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;
2281
+ } else {
2282
+ resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;
2283
+ }
2284
+ if (typeof resolvedDelay !== 'number') {
2285
+ internalQueue.push(resolvedEvent);
2286
+ }
2287
+ return [snapshot, {
2288
+ event: resolvedEvent,
2289
+ id,
2290
+ delay: resolvedDelay
2291
+ }];
2292
+ }
2293
+ function executeRaise(actorScope, params) {
2294
+ if (typeof params.delay === 'number') {
2295
+ actorScope.self.delaySend(params);
2296
+ return;
2297
+ }
2298
+ }
2299
+ /**
2300
+ * Raises an event. This places the event in the internal event queue, so that
2301
+ * the event is immediately consumed by the machine in the current step.
2302
+ *
2303
+ * @param eventType The event to raise.
2304
+ */
2305
+ function raise(eventOrExpr, options) {
2306
+ function raise(args, params) {
2307
+ }
2308
+ raise.type = 'xstate.raise';
2309
+ raise.event = eventOrExpr;
2310
+ raise.id = options?.id;
2311
+ raise.delay = options?.delay;
2312
+ raise.resolve = resolveRaise;
2313
+ raise.execute = executeRaise;
2314
+ return raise;
2315
+ }
2316
+
2317
+ export { $$ACTOR_TYPE as $, Actor as A, interpret as B, isMachineSnapshot as C, matchesState as D, pathToStateValue as E, toObserver as F, getAllOwnEventDescriptors as G, and as H, not as I, or as J, stateIn as K, cancel as L, raise as M, NULL_EVENT as N, spawnChild as O, stop as P, stopChild as Q, ProcessingStatus as R, STATE_DELIMITER as S, cloneMachineSnapshot as T, XSTATE_ERROR as U, createErrorActorEvent as V, XSTATE_STOP as X, toTransitionConfigArray as a, formatTransition as b, createInvokeId as c, formatInitialTransition as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, getCandidates as h, getAllStateNodes as i, getStateNodes as j, createMachineSnapshot as k, isInFinalState as l, mapValues as m, macrostep as n, transitionNode as o, resolveActionsAndContext as p, createInitEvent as q, resolveStateValue as r, microstep as s, toArray as t, getInitialStateNodes as u, isStateId as v, getStateNodeByPath as w, getPersistedSnapshot as x, resolveReferencedActor as y, createActor as z };