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