xstate 5.0.0-beta.9 → 5.0.1

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