xstate 5.32.2 → 6.0.0-alpha.10

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 (121) hide show
  1. package/README.md +25 -24
  2. package/dist/StateMachine-0aa98f54.development.esm.js +746 -0
  3. package/dist/StateMachine-aef700df.cjs.js +732 -0
  4. package/dist/StateMachine-d4931336.esm.js +729 -0
  5. package/dist/StateMachine-da872dde.development.cjs.js +749 -0
  6. package/dist/declarations/src/State.d.ts +11 -13
  7. package/dist/declarations/src/StateMachine.d.ts +40 -26
  8. package/dist/declarations/src/StateNode.d.ts +18 -54
  9. package/dist/declarations/src/actions.d.ts +14 -9
  10. package/dist/declarations/src/actors/callback.d.ts +42 -16
  11. package/dist/declarations/src/actors/index.d.ts +9 -6
  12. package/dist/declarations/src/actors/listener.d.ts +18 -0
  13. package/dist/declarations/src/actors/logic.d.ts +105 -0
  14. package/dist/declarations/src/actors/observable.d.ts +72 -27
  15. package/dist/declarations/src/actors/promise.d.ts +133 -48
  16. package/dist/declarations/src/actors/subscription.d.ts +22 -0
  17. package/dist/declarations/src/createActor.d.ts +33 -34
  18. package/dist/declarations/src/createMachine.d.ts +38 -7
  19. package/dist/declarations/src/createMachineFromConfig.d.ts +177 -0
  20. package/dist/declarations/src/graph/graph.d.ts +6 -4
  21. package/dist/declarations/src/graph/shortestPaths.d.ts +2 -2
  22. package/dist/declarations/src/graph/simplePaths.d.ts +2 -2
  23. package/dist/declarations/src/index.d.ts +13 -9
  24. package/dist/declarations/src/inspection.d.ts +84 -30
  25. package/dist/declarations/src/mapState.d.ts +4 -2
  26. package/dist/declarations/src/schema.types.d.ts +90 -0
  27. package/dist/declarations/src/serialize.d.ts +50 -0
  28. package/dist/declarations/src/setup.d.ts +396 -136
  29. package/dist/declarations/src/spawn.d.ts +7 -32
  30. package/dist/declarations/src/stateUtils.d.ts +22 -19
  31. package/dist/declarations/src/system.d.ts +8 -7
  32. package/dist/declarations/src/transition.d.ts +8 -5
  33. package/dist/declarations/src/transitionActions.d.ts +4 -0
  34. package/dist/declarations/src/types.d.ts +494 -429
  35. package/dist/declarations/src/types.v6.d.ts +423 -0
  36. package/dist/declarations/src/utils.d.ts +5 -3
  37. package/dist/index-219cb621.development.cjs.js +4476 -0
  38. package/dist/index-2f2fbd9b.development.esm.js +4421 -0
  39. package/dist/index-559ceab3.cjs.js +4437 -0
  40. package/dist/index-8828376f.esm.js +4382 -0
  41. package/dist/xstate-actors.cjs.js +12 -838
  42. package/dist/xstate-actors.cjs.mjs +10 -5
  43. package/dist/xstate-actors.development.cjs.js +12 -838
  44. package/dist/xstate-actors.development.cjs.mjs +10 -5
  45. package/dist/xstate-actors.development.esm.js +1 -836
  46. package/dist/xstate-actors.esm.js +1 -836
  47. package/dist/xstate-actors.umd.min.js +1 -1
  48. package/dist/xstate-actors.umd.min.js.map +1 -1
  49. package/dist/xstate-graph.cjs.js +18 -29
  50. package/dist/xstate-graph.development.cjs.js +18 -29
  51. package/dist/xstate-graph.development.esm.js +15 -26
  52. package/dist/xstate-graph.esm.js +15 -26
  53. package/dist/xstate-graph.umd.min.js +1 -1
  54. package/dist/xstate-graph.umd.min.js.map +1 -1
  55. package/dist/xstate.cjs.js +1477 -122
  56. package/dist/xstate.cjs.mjs +19 -22
  57. package/dist/xstate.development.cjs.js +1477 -122
  58. package/dist/xstate.development.cjs.mjs +19 -22
  59. package/dist/xstate.development.esm.js +1442 -86
  60. package/dist/xstate.esm.js +1442 -86
  61. package/dist/xstate.umd.min.js +1 -1
  62. package/dist/xstate.umd.min.js.map +1 -1
  63. package/package.json +3 -47
  64. package/dist/StateMachine-23c204bb.development.esm.js +0 -566
  65. package/dist/StateMachine-67a0f463.development.cjs.js +0 -569
  66. package/dist/StateMachine-94d215e3.cjs.js +0 -563
  67. package/dist/StateMachine-d1d80308.esm.js +0 -560
  68. package/dist/assign-43b1b558.development.esm.js +0 -133
  69. package/dist/assign-54b312bc.esm.js +0 -127
  70. package/dist/assign-b5bc78f7.cjs.js +0 -129
  71. package/dist/assign-f8f66278.development.cjs.js +0 -135
  72. package/dist/declarations/src/actions/assign.d.ts +0 -45
  73. package/dist/declarations/src/actions/cancel.d.ts +0 -39
  74. package/dist/declarations/src/actions/emit.d.ts +0 -44
  75. package/dist/declarations/src/actions/enqueueActions.d.ts +0 -57
  76. package/dist/declarations/src/actions/log.d.ts +0 -16
  77. package/dist/declarations/src/actions/raise.d.ts +0 -21
  78. package/dist/declarations/src/actions/send.d.ts +0 -42
  79. package/dist/declarations/src/actions/spawnChild.d.ts +0 -34
  80. package/dist/declarations/src/actions/stopChild.d.ts +0 -19
  81. package/dist/declarations/src/actors/transition.d.ts +0 -143
  82. package/dist/declarations/src/dev/index.d.ts +0 -14
  83. package/dist/declarations/src/guards.d.ts +0 -128
  84. package/dist/log-9b02c355.esm.js +0 -401
  85. package/dist/log-c94995c7.cjs.js +0 -409
  86. package/dist/log-d9f3f459.development.cjs.js +0 -437
  87. package/dist/log-db444cad.development.esm.js +0 -429
  88. package/dist/raise-235108c6.esm.js +0 -2762
  89. package/dist/raise-45f11c00.development.esm.js +0 -2824
  90. package/dist/raise-c445379d.cjs.js +0 -2817
  91. package/dist/raise-eca73993.development.cjs.js +0 -2879
  92. package/dist/xstate-actions.cjs.d.mts +0 -2
  93. package/dist/xstate-actions.cjs.d.ts +0 -2
  94. package/dist/xstate-actions.cjs.js +0 -23
  95. package/dist/xstate-actions.cjs.mjs +0 -14
  96. package/dist/xstate-actions.development.cjs.js +0 -23
  97. package/dist/xstate-actions.development.cjs.mjs +0 -14
  98. package/dist/xstate-actions.development.esm.js +0 -4
  99. package/dist/xstate-actions.esm.js +0 -4
  100. package/dist/xstate-actions.umd.min.js +0 -2
  101. package/dist/xstate-actions.umd.min.js.map +0 -1
  102. package/dist/xstate-dev.cjs.d.mts +0 -2
  103. package/dist/xstate-dev.cjs.d.ts +0 -2
  104. package/dist/xstate-dev.cjs.js +0 -48
  105. package/dist/xstate-dev.cjs.mjs +0 -5
  106. package/dist/xstate-dev.development.cjs.js +0 -51
  107. package/dist/xstate-dev.development.cjs.mjs +0 -5
  108. package/dist/xstate-dev.development.esm.js +0 -45
  109. package/dist/xstate-dev.esm.js +0 -42
  110. package/dist/xstate-dev.umd.min.js +0 -2
  111. package/dist/xstate-dev.umd.min.js.map +0 -1
  112. package/dist/xstate-guards.cjs.d.mts +0 -2
  113. package/dist/xstate-guards.cjs.d.ts +0 -2
  114. package/dist/xstate-guards.cjs.js +0 -14
  115. package/dist/xstate-guards.cjs.mjs +0 -7
  116. package/dist/xstate-guards.development.cjs.js +0 -14
  117. package/dist/xstate-guards.development.cjs.mjs +0 -7
  118. package/dist/xstate-guards.development.esm.js +0 -2
  119. package/dist/xstate-guards.esm.js +0 -2
  120. package/dist/xstate-guards.umd.min.js +0 -2
  121. package/dist/xstate-guards.umd.min.js.map +0 -1
@@ -0,0 +1,4421 @@
1
+ class Mailbox {
2
+ constructor(_process) {
3
+ this._process = _process;
4
+ this._active = false;
5
+ this._current = null;
6
+ this._last = null;
7
+ }
8
+ start() {
9
+ this._active = true;
10
+ this.flush();
11
+ }
12
+ clear() {
13
+ // we can't set _current to null because we might be currently processing
14
+ // and enqueue following clear shouldn't start processing the enqueued item immediately
15
+ if (this._current) {
16
+ this._current.next = null;
17
+ this._last = this._current;
18
+ }
19
+ }
20
+ enqueue(event) {
21
+ const enqueued = {
22
+ value: event,
23
+ next: null
24
+ };
25
+ if (this._current) {
26
+ this._last.next = enqueued;
27
+ this._last = enqueued;
28
+ return;
29
+ }
30
+ this._current = enqueued;
31
+ this._last = enqueued;
32
+ if (this._active) {
33
+ this.flush();
34
+ }
35
+ }
36
+ flush() {
37
+ while (this._current) {
38
+ // atm the given _process is responsible for implementing proper try/catch handling
39
+ // we assume here that this won't throw in a way that can affect this mailbox
40
+ const consumed = this._current;
41
+ this._process(consumed.value);
42
+ this._current = consumed.next;
43
+ }
44
+ this._last = null;
45
+ }
46
+ }
47
+
48
+ const STATE_DELIMITER = '.';
49
+ const TARGETLESS_KEY = '';
50
+ const NULL_EVENT = '';
51
+ const STATE_IDENTIFIER = '#';
52
+ const WILDCARD = '*';
53
+ const XSTATE_INIT = '@xstate.init';
54
+ const XSTATE_STOP = '@xstate.stop';
55
+
56
+ /**
57
+ * Returns an event that represents an implicit event that is sent after the
58
+ * specified `delay`.
59
+ *
60
+ * @param delayRef The delay in milliseconds
61
+ * @param id The state node ID where this event is handled
62
+ */
63
+ function createAfterEvent(delayRef, id) {
64
+ return {
65
+ type: `xstate.after.${delayRef}.${id}`
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Returns an event that represents an implicit state-level timeout. Fired when
71
+ * a state's `timeout` duration elapses without the state being exited.
72
+ *
73
+ * @param id The state node ID where this timeout is configured
74
+ */
75
+ function createTimeoutEvent(id) {
76
+ return {
77
+ type: `xstate.timeout.${id}`
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Returns an event that represents an implicit invoke-level timeout. Fired when
83
+ * an invoked actor has not completed within its `timeout` duration.
84
+ *
85
+ * @param invokeId The invoked actor's ID
86
+ */
87
+ function createInvokeTimeoutEvent(invokeId) {
88
+ return {
89
+ type: `xstate.timeout.actor.${invokeId}`
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Returns an event that represents that a final state node has been reached in
95
+ * the parent state node.
96
+ *
97
+ * @param id The final state node's parent state node `id`
98
+ * @param output The data to pass into the event
99
+ */
100
+ function createDoneStateEvent(id, output) {
101
+ return {
102
+ type: `xstate.done.state.${id}`,
103
+ output
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Returns an event that represents that an invoked service has terminated.
109
+ *
110
+ * An invoked service is terminated when it has reached a top-level final state
111
+ * node, but not when it is canceled.
112
+ *
113
+ * @param invokeId The invoked service ID
114
+ * @param output The data to pass into the event
115
+ */
116
+ function createDoneActorEvent(invokeId, output) {
117
+ return {
118
+ type: `xstate.done.actor.${invokeId}`,
119
+ output,
120
+ actorId: invokeId
121
+ };
122
+ }
123
+ function createErrorActorEvent(id, error) {
124
+ return {
125
+ type: `xstate.error.actor.${id}`,
126
+ error,
127
+ actorId: id
128
+ };
129
+ }
130
+ function createInitEvent(input) {
131
+ return {
132
+ type: XSTATE_INIT,
133
+ input
134
+ };
135
+ }
136
+
137
+ /**
138
+ * This function makes sure that unhandled errors are thrown in a separate
139
+ * macrotask. It allows those errors to be detected by global error handlers and
140
+ * reported to bug tracking services without interrupting our own stack of
141
+ * execution.
142
+ *
143
+ * @param err Error to be thrown
144
+ */
145
+ function reportUnhandledError(err) {
146
+ setTimeout(() => {
147
+ throw err;
148
+ });
149
+ }
150
+
151
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
152
+
153
+ const builtInActions = {
154
+ ['@xstate.start']: actor => {
155
+ actor.start();
156
+ },
157
+ ['@xstate.raise']: (actorScope, event, options) => {
158
+ actorScope.system.scheduler.schedule(actorScope.self, actorScope.self, event, options?.delay ?? 0, options?.id);
159
+ },
160
+ ['@xstate.sendTo']: (actorScope, actor, event, options) => {
161
+ if (typeof event === 'string') {
162
+ throw new Error(// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
163
+ `Only event objects may be used with sendTo; use sendTo({ type: "${event}" }) instead` );
164
+ }
165
+ if (options?.delay !== undefined) {
166
+ actorScope.system.scheduler.schedule(actorScope.self, actor, event, options?.delay ?? 0, options?.id);
167
+ } else {
168
+ actorScope.defer(() => {
169
+ actorScope.system._relay(actorScope.self, actor, event);
170
+ });
171
+ }
172
+ },
173
+ ['@xstate.cancel']: (actorScope, sendId) => {
174
+ actorScope.system.scheduler.cancel(actorScope.self, sendId);
175
+ },
176
+ ['@xstate.stop']: (actorScope, actor) => {
177
+ actorScope.stopChild(actor);
178
+ }
179
+ };
180
+
181
+ const subscriptions = /* #__PURE__ */new WeakMap();
182
+
183
+ /**
184
+ * Internal factory for actor logic that attaches to another actor on start
185
+ * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.
186
+ */
187
+ function createAttachedLogic(attach) {
188
+ const initialTransition = (input, _) => [{
189
+ status: 'active',
190
+ output: undefined,
191
+ error: undefined,
192
+ input
193
+ }, []];
194
+ return {
195
+ start: (state, {
196
+ self,
197
+ system
198
+ }) => {
199
+ // Don't attach if the target doesn't exist or is stopped.
200
+ const target = state.input.actor;
201
+ if (!target || target.getSnapshot().status === 'stopped') {
202
+ return;
203
+ }
204
+ const subscription = attach(state.input, {
205
+ self,
206
+ system
207
+ });
208
+ if (!subscription) {
209
+ return;
210
+ }
211
+
212
+ // Attached actors are not registered as children (their `input` holds
213
+ // non-serializable function mappers), so a parent stop does not cascade
214
+ // to them. Subscribe to the parent and tear down when it stops/errors,
215
+ // so the subscription never relays to a stopped parent or leaks the
216
+ // source subscription.
217
+ let parentSubscription;
218
+ let torndown = false;
219
+ const teardown = () => {
220
+ if (torndown) {
221
+ return;
222
+ }
223
+ torndown = true;
224
+ subscription.unsubscribe();
225
+ parentSubscription?.unsubscribe();
226
+ };
227
+ const parent = self._parent;
228
+ if (parent) {
229
+ parentSubscription = parent.subscribe({
230
+ complete: teardown,
231
+ error: teardown
232
+ });
233
+ }
234
+ subscriptions.set(self, {
235
+ unsubscribe: teardown
236
+ });
237
+ },
238
+ transition: (state, event, {
239
+ self
240
+ }) => {
241
+ if (event.type === XSTATE_STOP) {
242
+ subscriptions.get(self)?.unsubscribe();
243
+ subscriptions.delete(self);
244
+ return [{
245
+ ...state,
246
+ status: 'stopped',
247
+ error: undefined
248
+ }, []];
249
+ }
250
+ return [state, []];
251
+ },
252
+ initialTransition,
253
+ getInitialSnapshot: (actorScope, input) => initialTransition(input)[0],
254
+ getPersistedSnapshot: snapshot => snapshot,
255
+ restoreSnapshot: snapshot => snapshot
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Relays a mapped event to the attached actor's parent, unless the attached
261
+ * actor has been stopped (the mapper is not called in that case).
262
+ */
263
+ function relayMappedToParent(self, system, getEvent) {
264
+ if (self.getSnapshot().status === 'stopped' || !self._parent) {
265
+ return;
266
+ }
267
+ system._relay(self, self._parent, getEvent());
268
+ }
269
+
270
+ /**
271
+ * Creates actor logic for listening to emitted events from another actor. Used
272
+ * internally by `enq.listen()`.
273
+ */
274
+ function createListenerLogic() {
275
+ return createAttachedLogic(({
276
+ actor,
277
+ eventType,
278
+ mapper
279
+ }, {
280
+ self,
281
+ system
282
+ }) => {
283
+ // Determine the subscription type:
284
+ // - For exact matches or '*', subscribe directly
285
+ // - For partial wildcards ('data.*'), subscribe to '*' and filter
286
+ const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');
287
+ return actor.on(isPartialWildcard ? '*' : eventType, emittedEvent => {
288
+ if (isPartialWildcard && !matchesEventDescriptor(emittedEvent.type, eventType)) {
289
+ return;
290
+ }
291
+ relayMappedToParent(self, system, () => mapper(emittedEvent));
292
+ });
293
+ });
294
+ }
295
+
296
+ // Singleton logic instance
297
+ const listenerLogic = /* #__PURE__ */createListenerLogic();
298
+
299
+ /**
300
+ * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)
301
+ * from another actor. Used internally by `enq.subscribeTo()`.
302
+ */
303
+ function createSubscriptionLogic() {
304
+ return createAttachedLogic(({
305
+ actor,
306
+ mappers
307
+ }, {
308
+ self,
309
+ system
310
+ }) => {
311
+ const {
312
+ done,
313
+ error,
314
+ snapshot: onSnapshot
315
+ } = mappers;
316
+ return actor.subscribe({
317
+ next: snapshot => {
318
+ if (snapshot.status === 'done' && done) {
319
+ relayMappedToParent(self, system, () => done(snapshot.output));
320
+ } else if (snapshot.status === 'error' && error) {
321
+ relayMappedToParent(self, system, () => error(snapshot.error));
322
+ } else if (snapshot.status === 'active' && onSnapshot) {
323
+ relayMappedToParent(self, system, () => onSnapshot(snapshot));
324
+ }
325
+ },
326
+ error: err => {
327
+ if (error) {
328
+ relayMappedToParent(self, system, () => error(err));
329
+ }
330
+ },
331
+ complete: () => {
332
+ // Actor completed without output (stopped); no action needed
333
+ }
334
+ });
335
+ });
336
+ }
337
+
338
+ // Singleton logic instance
339
+ const subscriptionLogic = /* #__PURE__ */createSubscriptionLogic();
340
+
341
+ function mergeContextPatch$1(context, patch) {
342
+ return {
343
+ ...context,
344
+ ...patch
345
+ };
346
+ }
347
+ function pushBuiltInAction(actions, action, ...args) {
348
+ actions.push({
349
+ action,
350
+ args
351
+ });
352
+ }
353
+ function registerSpawnedChild(actor, id) {
354
+ return Object.assign(function registerChild(args) {
355
+ return {
356
+ children: {
357
+ ...args.children,
358
+ [id]: actor
359
+ }
360
+ };
361
+ }, {
362
+ _special: true
363
+ });
364
+ }
365
+ function unregisterChild(actor) {
366
+ return Object.assign(function removeChild(args) {
367
+ const children = {
368
+ ...args.children
369
+ };
370
+ for (const key of Object.keys(children)) {
371
+ if (children[key] === actor) {
372
+ delete children[key];
373
+ }
374
+ }
375
+ return {
376
+ children
377
+ };
378
+ }, {
379
+ _special: true
380
+ });
381
+ }
382
+ function pushStartedChild(actions, actor, id) {
383
+ pushBuiltInAction(actions, builtInActions['@xstate.start'], actor);
384
+ actions.push(registerSpawnedChild(actor, id ?? actor.id));
385
+ }
386
+ function createTransitionEnqueue(actorScope, actions, internalEvents, actorSubscriptions = false) {
387
+ const props = {
388
+ cancel: id => {
389
+ pushBuiltInAction(actions, builtInActions['@xstate.cancel'], actorScope, id);
390
+ },
391
+ emit: emittedEvent => {
392
+ actions.push(emittedEvent);
393
+ },
394
+ log: (...args) => {
395
+ pushBuiltInAction(actions, actorScope.logger, ...args);
396
+ },
397
+ raise: (raisedEvent, options) => {
398
+ if (typeof raisedEvent === 'string') {
399
+ throw new Error(`Only event objects may be used with raise; use raise({ type: "${raisedEvent}" }) instead` );
400
+ }
401
+ if (options?.delay !== undefined) {
402
+ pushBuiltInAction(actions, builtInActions['@xstate.raise'], actorScope, raisedEvent, options);
403
+ } else {
404
+ internalEvents.push(raisedEvent);
405
+ }
406
+ },
407
+ spawn: (logic, options) => {
408
+ const actor = createActor(logic, {
409
+ ...options,
410
+ parent: actorScope.self
411
+ });
412
+ pushStartedChild(actions, actor, options?.id);
413
+ return actor;
414
+ },
415
+ sendTo: (actor, event, options) => {
416
+ if (actor) {
417
+ pushBuiltInAction(actions, builtInActions['@xstate.sendTo'], actorScope, actor, event, options);
418
+ }
419
+ },
420
+ stop: actor => {
421
+ if (actor) {
422
+ pushBuiltInAction(actions, builtInActions['@xstate.stop'], actorScope, actor);
423
+ actions.push(unregisterChild(actor));
424
+ }
425
+ }
426
+ };
427
+ if (actorSubscriptions) {
428
+ Object.assign(props, {
429
+ listen: (actor, eventType, mapper) => {
430
+ const input = {
431
+ actor,
432
+ eventType,
433
+ mapper
434
+ };
435
+ const listenerActor = createActor(listenerLogic, {
436
+ input,
437
+ parent: actorScope.self
438
+ });
439
+ pushBuiltInAction(actions, builtInActions['@xstate.start'], listenerActor);
440
+ return listenerActor;
441
+ },
442
+ subscribeTo: (actor, mappers) => {
443
+ const normalizedMappers = typeof mappers === 'function' ? {
444
+ snapshot: mappers
445
+ } : mappers;
446
+ const input = {
447
+ actor,
448
+ mappers: normalizedMappers
449
+ };
450
+ const subscriptionActor = createActor(subscriptionLogic, {
451
+ input,
452
+ parent: actorScope.self
453
+ });
454
+ pushBuiltInAction(actions, builtInActions['@xstate.start'], subscriptionActor);
455
+ return subscriptionActor;
456
+ }
457
+ });
458
+ }
459
+ return createEnqueueObject$1(props, (action, ...args) => {
460
+ pushBuiltInAction(actions, action, ...args);
461
+ });
462
+ }
463
+ function getBuiltInActionFields(action, args) {
464
+ switch (action) {
465
+ case builtInActions['@xstate.start']:
466
+ {
467
+ const [actor] = args;
468
+ return {
469
+ actor,
470
+ id: actor.id,
471
+ logic: actor.logic,
472
+ src: actor.src,
473
+ input: actor.options?.input
474
+ };
475
+ }
476
+ case builtInActions['@xstate.raise']:
477
+ {
478
+ const [, event, options] = args;
479
+ return {
480
+ event,
481
+ id: options?.id,
482
+ delay: options?.delay
483
+ };
484
+ }
485
+ case builtInActions['@xstate.sendTo']:
486
+ {
487
+ const [, target, event, options] = args;
488
+ return {
489
+ target,
490
+ event,
491
+ id: options?.id,
492
+ delay: options?.delay
493
+ };
494
+ }
495
+ case builtInActions['@xstate.cancel']:
496
+ {
497
+ const [, id] = args;
498
+ return {
499
+ id
500
+ };
501
+ }
502
+ case builtInActions['@xstate.stop']:
503
+ {
504
+ const [, actor] = args;
505
+ return {
506
+ actor
507
+ };
508
+ }
509
+ default:
510
+ return undefined;
511
+ }
512
+ }
513
+ function isBuiltInExecutableAction(action) {
514
+ return Object.prototype.hasOwnProperty.call(builtInActions, action.type);
515
+ }
516
+ function resolveActionsWithContext(currentSnapshot, event, actorScope, actions) {
517
+ let intermediateSnapshot = currentSnapshot;
518
+ const executableActions = [];
519
+ for (const action of actions) {
520
+ const isInline = typeof action === 'function';
521
+ const resolvedAction = isInline ? action : typeof action === 'object' && 'action' in action && typeof action.action === 'function' ? action.action.bind(null, ...action.args) : false;
522
+ const actionArgs = {
523
+ context: intermediateSnapshot.context,
524
+ event,
525
+ output: getEventOutput(event),
526
+ self: actorScope.self,
527
+ system: actorScope.system,
528
+ children: intermediateSnapshot.children,
529
+ parent: actorScope.self._parent,
530
+ actions: currentSnapshot.machine.implementations.actions,
531
+ actorSources: currentSnapshot.machine.implementations.actorSources
532
+ };
533
+ let actionParams = undefined;
534
+ if (typeof action === 'object' && action !== null) {
535
+ const {
536
+ type: _,
537
+ ...emittedEventParams
538
+ } = action;
539
+ actionParams = emittedEventParams;
540
+ }
541
+ if (resolvedAction && '_special' in resolvedAction) {
542
+ executableActions.push({
543
+ type: typeof action === 'object' ? 'action' in action && typeof action.action === 'function' ? action.action.name ?? '(anonymous)' : action.type ?? '(anonymous)' : action.name || '(anonymous)',
544
+ params: actionParams,
545
+ args: [],
546
+ exec: undefined
547
+ });
548
+ const specialAction = resolvedAction;
549
+ const res = specialAction(actionArgs, emptyEnqueueObject);
550
+ if (res && ('context' in res || 'children' in res)) {
551
+ intermediateSnapshot = cloneMachineSnapshot(intermediateSnapshot, {
552
+ ...(res.context !== undefined ? {
553
+ context: mergeContextPatch$1(intermediateSnapshot.context, res.context)
554
+ } : {}),
555
+ ...('children' in res ? {
556
+ children: res.children
557
+ } : {})
558
+ });
559
+ }
560
+ continue;
561
+ }
562
+ if (!resolvedAction || !('resolve' in resolvedAction)) {
563
+ const builtInFields = typeof action === 'object' && action !== null && 'action' in action && typeof action.action === 'function' ? getBuiltInActionFields(action.action, action.args) : undefined;
564
+ executableActions.push({
565
+ type: typeof action === 'object' ? 'action' in action && typeof action.action === 'function' ? action.action.name ?? '(anonymous)' : action.type : action.name || '(anonymous)',
566
+ params: actionParams,
567
+ args: typeof action === 'object' && 'action' in action ? action.args : [],
568
+ exec: resolvedAction || (typeof action === 'object' && action !== null ? () => actorScope.defer(() => actorScope.emit(action)) : undefined),
569
+ ...builtInFields
570
+ });
571
+ continue;
572
+ }
573
+ }
574
+ return [intermediateSnapshot, executableActions];
575
+ }
576
+ function createEnqueueObject$1(props, action) {
577
+ const enqueueFn = (fn, ...args) => {
578
+ action(fn, ...args);
579
+ };
580
+ Object.assign(enqueueFn, {
581
+ cancel: () => {},
582
+ emit: () => {},
583
+ log: () => {},
584
+ raise: () => {},
585
+ spawn: () => ({}),
586
+ sendTo: () => {},
587
+ stop: () => {},
588
+ listen: () => ({}),
589
+ subscribeTo: () => ({}),
590
+ ...props
591
+ });
592
+ return enqueueFn;
593
+ }
594
+ const emptyEnqueueObject = createEnqueueObject$1({}, () => {});
595
+
596
+ function parseDurationToMilliseconds(duration) {
597
+ const normalizedDuration = duration.trim();
598
+ const millisecondsMatch = normalizedDuration.match(/^(\d+)ms$/i);
599
+ if (millisecondsMatch) {
600
+ return parseInt(millisecondsMatch[1], 10);
601
+ }
602
+ const secondsMatch = normalizedDuration.match(/^(\d*)(\.?)(\d*)s$/i);
603
+ if (secondsMatch) {
604
+ const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;
605
+ const hasDecimal = !!secondsMatch[2];
606
+ const fracPart = secondsMatch[3] ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10) : 0;
607
+ return wholePart * 1000 + (hasDecimal ? fracPart : 0);
608
+ }
609
+ const iso8601DurationMatch = normalizedDuration.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);
610
+ if (!iso8601DurationMatch?.groups) {
611
+ return undefined;
612
+ }
613
+ const {
614
+ weeks,
615
+ days,
616
+ hours,
617
+ minutes,
618
+ seconds
619
+ } = iso8601DurationMatch.groups;
620
+ if (!weeks && !days && !hours && !minutes && !seconds) {
621
+ return undefined;
622
+ }
623
+ const toNumber = value => value ? Number(value.replace(',', '.')) : 0;
624
+ return toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 + toNumber(days) * 24 * 60 * 60 * 1000 + toNumber(hours) * 60 * 60 * 1000 + toNumber(minutes) * 60 * 1000 + toNumber(seconds) * 1000;
625
+ }
626
+ function parseDelayToMilliseconds(delay) {
627
+ if (delay === undefined) {
628
+ return undefined;
629
+ }
630
+ if (typeof delay === 'number') {
631
+ return delay;
632
+ }
633
+ return parseDurationToMilliseconds(delay);
634
+ }
635
+
636
+ function getConfiguredDelayValue(delay, delaySource) {
637
+ if (typeof delay !== 'string') {
638
+ return delay;
639
+ }
640
+ const referencedDelay = delaySource[delay];
641
+ if (referencedDelay !== undefined) {
642
+ return referencedDelay;
643
+ }
644
+ return parseDurationToMilliseconds(delay) ?? delay;
645
+ }
646
+ function resolveDelay(delay, delaySource, args) {
647
+ if (typeof delay === 'function') {
648
+ return delay(args);
649
+ }
650
+ const configuredDelay = getConfiguredDelayValue(delay, delaySource);
651
+ if (typeof configuredDelay === 'function') {
652
+ return configuredDelay(args);
653
+ }
654
+ return configuredDelay;
655
+ }
656
+ function isAtomicStateNode(stateNode) {
657
+ return stateNode.type === 'atomic' || stateNode.type === 'final' || stateNode.type === 'choice';
658
+ }
659
+ function getChildren(stateNode) {
660
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
661
+ }
662
+ function getProperAncestors(stateNode, toStateNode) {
663
+ const ancestors = [];
664
+ if (toStateNode === stateNode) {
665
+ return ancestors;
666
+ }
667
+
668
+ // add all ancestors
669
+ let m = stateNode.parent;
670
+ while (m && m !== toStateNode) {
671
+ ancestors.push(m);
672
+ m = m.parent;
673
+ }
674
+ return ancestors;
675
+ }
676
+ function getAllStateNodes(stateNodes) {
677
+ const nodeSet = new Set(stateNodes);
678
+ const activeParentSet = new Set();
679
+ for (const stateNode of nodeSet) {
680
+ if (stateNode.parent) {
681
+ activeParentSet.add(stateNode.parent);
682
+ }
683
+ }
684
+
685
+ // add descendants
686
+ for (const s of nodeSet) {
687
+ // if previously active, add existing child nodes
688
+ if (s.type === 'compound' && !activeParentSet.has(s)) {
689
+ for (const sn of getInitialStateNodes(s)) {
690
+ nodeSet.add(sn);
691
+ }
692
+ continue;
693
+ }
694
+ if (s.type === 'parallel') {
695
+ for (const child of getChildren(s)) {
696
+ if (!nodeSet.has(child)) {
697
+ const initialStates = getInitialStateNodes(child);
698
+ for (const initialStateNode of initialStates) {
699
+ nodeSet.add(initialStateNode);
700
+ }
701
+ }
702
+ }
703
+ }
704
+ }
705
+
706
+ // add all ancestors
707
+ // Stop walking up as soon as we hit a node already in the set: its own
708
+ // ancestor chain is guaranteed to be added when it is visited by this loop
709
+ // (Set iteration visits elements added during iteration), so shared ancestor
710
+ // chains are never re-walked once per descendant.
711
+ for (const s of nodeSet) {
712
+ let m = s.parent;
713
+ while (m && !nodeSet.has(m)) {
714
+ nodeSet.add(m);
715
+ m = m.parent;
716
+ }
717
+ }
718
+ return nodeSet;
719
+ }
720
+ function getStateValue(rootNode, stateNodes) {
721
+ const config = getAllStateNodes(stateNodes);
722
+ const adjList = new Map();
723
+ for (const s of config) {
724
+ if (!adjList.has(s)) {
725
+ adjList.set(s, []);
726
+ }
727
+ if (!s.parent) {
728
+ continue;
729
+ }
730
+ if (!adjList.has(s.parent)) {
731
+ adjList.set(s.parent, []);
732
+ }
733
+ adjList.get(s.parent).push(s);
734
+ }
735
+ const getValueFromAdj = baseNode => {
736
+ const childStateNodes = adjList.get(baseNode);
737
+ if (!childStateNodes) {
738
+ return {}; // todo: fix?
739
+ }
740
+ if (baseNode.type === 'compound') {
741
+ const childStateNode = childStateNodes[0];
742
+ if (!childStateNode) {
743
+ return {};
744
+ }
745
+ if (isAtomicStateNode(childStateNode)) {
746
+ return childStateNode.key;
747
+ }
748
+ }
749
+ const stateValue = {};
750
+ for (const childStateNode of childStateNodes) {
751
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode);
752
+ }
753
+ return stateValue;
754
+ };
755
+ return getValueFromAdj(rootNode);
756
+ }
757
+ function isInFinalState(stateNodeSet, stateNode) {
758
+ if (stateNode.type === 'compound') {
759
+ return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));
760
+ }
761
+ if (stateNode.type === 'parallel') {
762
+ return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));
763
+ }
764
+ return stateNode.type === 'final';
765
+ }
766
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
767
+ function getCandidates(stateNode, receivedEventType) {
768
+ const exactMatch = stateNode.transitions.get(receivedEventType);
769
+ const wildcardCandidates = [...stateNode.transitions.keys()].filter(eventDescriptor => eventDescriptor !== receivedEventType && matchesEventDescriptor(receivedEventType, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
770
+ return exactMatch ? [...exactMatch, ...wildcardCandidates] : wildcardCandidates;
771
+ }
772
+ function scheduleDelayedEvent(stateNode, event, resolveScheduledDelay) {
773
+ const eventType = event.type;
774
+ const oldEntry = stateNode.entry;
775
+ stateNode.entry = (x, enq) => {
776
+ enq.raise(event, {
777
+ id: eventType,
778
+ delay: resolveScheduledDelay(x)
779
+ });
780
+ return typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;
781
+ };
782
+ const oldExit = stateNode.exit;
783
+ stateNode.exit = (_, enq) => {
784
+ enq.cancel(eventType);
785
+ return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;
786
+ };
787
+ return eventType;
788
+ }
789
+
790
+ /** All delayed transitions from the config. */
791
+ function getDelayedTransitions(stateNode) {
792
+ const afterConfig = stateNode.config.after;
793
+ const timeoutConfig = stateNode.config.timeout;
794
+ const onTimeoutConfig = stateNode.config.onTimeout;
795
+ const invokeDefs = stateNode.invoke.filter(invokeDef => invokeDef.timeout !== undefined);
796
+ if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {
797
+ return [];
798
+ }
799
+ if (timeoutConfig !== undefined && !onTimeoutConfig) {
800
+ throw new Error(`State "${stateNode.id}" has \`timeout\` but no \`onTimeout\` transition.`);
801
+ }
802
+ {
803
+ for (const invokeDef of invokeDefs) {
804
+ if (!invokeDef.onTimeout) {
805
+ throw new Error(`Invoke on state "${stateNode.id}" has \`timeout\` but no \`onTimeout\` transition.`);
806
+ }
807
+ }
808
+ }
809
+
810
+ // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and
811
+ // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on
812
+ // entry (and cancelled on exit) plus a transition that catches it. They
813
+ // differ only in the event raised, the transition(s) caught, and whether the
814
+ // delay resolves against the machine's `delays` map (invoke timeouts do not).
815
+ //
816
+ // `xstate.timeout.<id>` is a dedicated event so a state-level `timeout` cannot
817
+ // collide with an explicit `after` entry on the same state. Invoke timeouts
818
+ // are scheduled on the enclosing state; completion transitions cancel the
819
+ // timer separately, so it clears even when the parent state stays active.
820
+ const sources = [];
821
+ if (afterConfig) {
822
+ for (const key of Object.keys(afterConfig)) {
823
+ const delay = Number.isNaN(+key) ? key : +key;
824
+ sources.push({
825
+ event: createAfterEvent(delay, stateNode.id),
826
+ delay,
827
+ transitions: afterConfig[key],
828
+ fromDelaysMap: true
829
+ });
830
+ }
831
+ }
832
+ if (timeoutConfig !== undefined && onTimeoutConfig) {
833
+ sources.push({
834
+ event: createTimeoutEvent(stateNode.id),
835
+ delay: timeoutConfig,
836
+ transitions: onTimeoutConfig,
837
+ fromDelaysMap: true
838
+ });
839
+ }
840
+ for (const invokeDef of invokeDefs) {
841
+ sources.push({
842
+ event: createInvokeTimeoutEvent(invokeDef.id),
843
+ delay: invokeDef.timeout,
844
+ transitions: invokeDef.onTimeout,
845
+ fromDelaysMap: false
846
+ });
847
+ }
848
+
849
+ // `delay` here is the raw config value, retained only as metadata on the
850
+ // transition definition — the live delay is resolved at runtime in the
851
+ // scheduled entry action, so no eager resolution is needed.
852
+ const delayedTransitions = [];
853
+ for (const {
854
+ event,
855
+ delay,
856
+ transitions,
857
+ fromDelaysMap
858
+ } of sources) {
859
+ const eventType = scheduleDelayedEvent(stateNode, event, x => resolveDelay(delay, fromDelaysMap ? x.delays : {}, {
860
+ context: x.context,
861
+ event: x.event,
862
+ stateNode
863
+ }));
864
+ for (const transition of toTransitionConfigArray(transitions)) {
865
+ delayedTransitions.push({
866
+ ...transition,
867
+ event: eventType,
868
+ delay
869
+ });
870
+ }
871
+ }
872
+ return delayedTransitions.map(delayedTransition => ({
873
+ ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
874
+ delay: delayedTransition.delay
875
+ }));
876
+ }
877
+ function formatTransition(stateNode, descriptor, transitionConfig) {
878
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
879
+ const reenter = transitionConfig.reenter ?? false;
880
+ const target = resolveTarget(stateNode, normalizedTarget);
881
+ const transition = {
882
+ ...transitionConfig,
883
+ target,
884
+ source: stateNode,
885
+ reenter,
886
+ eventType: descriptor,
887
+ toJSON: () => ({
888
+ ...transition,
889
+ source: `#${stateNode.id}`,
890
+ target: target ? target.map(t => `#${t.id}`) : undefined
891
+ })
892
+ };
893
+ return transition;
894
+ }
895
+
896
+ /**
897
+ * Collects route transitions from all descendants with explicit IDs. Called
898
+ * once on the root node to avoid O(N²) repeated traversals.
899
+ */
900
+ function formatRouteTransitions(rootStateNode) {
901
+ const routeTransitions = [];
902
+ const collectRoutes = states => {
903
+ Object.values(states).forEach(sn => {
904
+ if (sn.config.route && sn.config.id) {
905
+ const routeId = sn.config.id;
906
+ const routeConfig = sn.config.route;
907
+ const routeMatches = ({
908
+ event
909
+ }) => event.to === `#${routeId}`;
910
+ if (typeof routeConfig === 'function') {
911
+ // Transition-style route: the function is the guard and resolver.
912
+ // Returning undefined/false blocks the route; returning true or a
913
+ // config object allows it.
914
+ routeTransitions.push(formatTransition(rootStateNode, 'xstate.route', {
915
+ guard: routeMatches,
916
+ to: args => {
917
+ const result = routeConfig(args);
918
+ if (!result) {
919
+ return undefined;
920
+ }
921
+ return {
922
+ ...(result === true ? {} : result),
923
+ target: `#${routeId}`
924
+ };
925
+ }
926
+ }));
927
+ if (sn.states) {
928
+ collectRoutes(sn.states);
929
+ }
930
+ return;
931
+ }
932
+ if ('$unserializable' in routeConfig) {
933
+ throw new Error(`State "${sn.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);
934
+ }
935
+ const {
936
+ guard: _guard,
937
+ ...routeOptions
938
+ } = routeConfig;
939
+ const transition = {
940
+ ...routeOptions,
941
+ guard: routeMatches,
942
+ target: `#${routeId}`
943
+ };
944
+ routeTransitions.push(formatTransition(rootStateNode, 'xstate.route', transition));
945
+ }
946
+ if (sn.states) {
947
+ collectRoutes(sn.states);
948
+ }
949
+ });
950
+ };
951
+ collectRoutes(rootStateNode.states);
952
+ if (routeTransitions.length > 0) {
953
+ rootStateNode.transitions.set('xstate.route', routeTransitions);
954
+ }
955
+ }
956
+ function resolveTarget(stateNode, targets) {
957
+ if (targets === undefined) {
958
+ // an undefined target signals that the state node should not transition from that state when receiving that event
959
+ return undefined;
960
+ }
961
+ return targets.map(target => {
962
+ if (typeof target !== 'string') {
963
+ return target;
964
+ }
965
+ if (isStateId(target)) {
966
+ return stateNode.machine.getStateNodeById(target);
967
+ }
968
+ const isInternalTarget = target[0] === STATE_DELIMITER;
969
+ // If internal target is defined on machine,
970
+ // do not include machine key on target
971
+ if (isInternalTarget && !stateNode.parent) {
972
+ return getStateNodeByPath(stateNode, target.slice(1));
973
+ }
974
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
975
+ if (stateNode.parent) {
976
+ try {
977
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
978
+ return targetStateNode;
979
+ } catch (err) {
980
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
981
+ }
982
+ } else {
983
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?` );
984
+ }
985
+ });
986
+ }
987
+ function resolveHistoryDefaultTransition(stateNode) {
988
+ const normalizedTarget = normalizeTarget(stateNode.config.target);
989
+ if (!normalizedTarget) {
990
+ return stateNode.parent.initial;
991
+ }
992
+ return {
993
+ target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t),
994
+ source: stateNode,
995
+ reenter: false,
996
+ eventType: ''
997
+ };
998
+ }
999
+ function isHistoryNode(stateNode) {
1000
+ return stateNode.type === 'history';
1001
+ }
1002
+ function getInitialStateNodes(stateNode) {
1003
+ const set = new Set();
1004
+ function iter(descStateNode) {
1005
+ if (set.has(descStateNode)) {
1006
+ return;
1007
+ }
1008
+ set.add(descStateNode);
1009
+ if (descStateNode.type === 'compound') {
1010
+ iter(descStateNode.initial.target[0]);
1011
+ } else if (descStateNode.type === 'parallel') {
1012
+ for (const child of getChildren(descStateNode)) {
1013
+ iter(child);
1014
+ }
1015
+ }
1016
+ }
1017
+ iter(stateNode);
1018
+ for (const initialState of set) {
1019
+ for (const ancestor of getProperAncestors(initialState, stateNode)) {
1020
+ set.add(ancestor);
1021
+ }
1022
+ }
1023
+ return set;
1024
+ }
1025
+
1026
+ /** Returns the child state node from its relative `stateKey`, or throws. */
1027
+ function getStateNode(stateNode, stateKey) {
1028
+ if (isStateId(stateKey)) {
1029
+ return stateNode.machine.getStateNodeById(stateKey);
1030
+ }
1031
+ if (!stateNode.states) {
1032
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1033
+ }
1034
+ const result = stateNode.states[stateKey];
1035
+ if (!result) {
1036
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1037
+ }
1038
+ return result;
1039
+ }
1040
+
1041
+ /**
1042
+ * Returns the relative state node from the given `statePath`, or throws.
1043
+ *
1044
+ * @param statePath The string or string array relative path to the state node.
1045
+ */
1046
+ function getStateNodeByPath(stateNode, statePath) {
1047
+ if (typeof statePath === 'string' && isStateId(statePath)) {
1048
+ try {
1049
+ return stateNode.machine.getStateNodeById(statePath);
1050
+ } catch {
1051
+ // try individual paths
1052
+ // throw e;
1053
+ }
1054
+ }
1055
+ const arrayStatePath = toStatePath(statePath).slice();
1056
+ let currentStateNode = stateNode;
1057
+ while (arrayStatePath.length) {
1058
+ const key = arrayStatePath.shift();
1059
+ if (!key.length) {
1060
+ break;
1061
+ }
1062
+ currentStateNode = getStateNode(currentStateNode, key);
1063
+ }
1064
+ return currentStateNode;
1065
+ }
1066
+
1067
+ /**
1068
+ * Returns the state nodes represented by the current state value.
1069
+ *
1070
+ * @param stateValue The state value or State instance
1071
+ */
1072
+ function getStateNodes(stateNode, stateValue) {
1073
+ if (typeof stateValue === 'string') {
1074
+ const childStateNode = stateNode.states[stateValue];
1075
+ if (!childStateNode) {
1076
+ throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);
1077
+ }
1078
+ return [stateNode, childStateNode];
1079
+ }
1080
+ const childStateKeys = Object.keys(stateValue);
1081
+ const childStateNodes = new Array(childStateKeys.length);
1082
+ const allStateNodes = [stateNode.machine.root, stateNode];
1083
+ for (let i = 0; i < childStateKeys.length; i++) {
1084
+ const subStateNode = getStateNode(stateNode, childStateKeys[i]);
1085
+ childStateNodes[i] = subStateNode;
1086
+ allStateNodes.push(subStateNode);
1087
+ }
1088
+ for (let i = 0; i < childStateKeys.length; i++) {
1089
+ allStateNodes.push(...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]));
1090
+ }
1091
+ return allStateNodes;
1092
+ }
1093
+ function transitionNode(stateNode, stateValue, snapshot, event, self) {
1094
+ // leaf node
1095
+ if (typeof stateValue === 'string') {
1096
+ const childStateNode = getStateNode(stateNode, stateValue);
1097
+ const next = childStateNode.next(snapshot, event, self);
1098
+ if (!next || !next.length) {
1099
+ return stateNode.next(snapshot, event, self);
1100
+ }
1101
+ return next;
1102
+ }
1103
+ const subStateKeys = Object.keys(stateValue);
1104
+ const subStateKey = subStateKeys[0];
1105
+ if (subStateKeys.length === 1) {
1106
+ const childStateNode = getStateNode(stateNode, subStateKey);
1107
+ const next = transitionNode(childStateNode, stateValue[subStateKey], snapshot, event, self);
1108
+ if (!next || !next.length) {
1109
+ return stateNode.next(snapshot, event, self);
1110
+ }
1111
+ return next;
1112
+ }
1113
+ const allInnerTransitions = [];
1114
+ for (const subStateKey of subStateKeys) {
1115
+ const subStateValue = stateValue[subStateKey];
1116
+ if (!subStateValue) {
1117
+ continue;
1118
+ }
1119
+ const subStateNode = getStateNode(stateNode, subStateKey);
1120
+ const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event, self);
1121
+ if (innerTransitions) {
1122
+ allInnerTransitions.push(...innerTransitions);
1123
+ }
1124
+ }
1125
+ if (!allInnerTransitions.length) {
1126
+ return stateNode.next(snapshot, event, self);
1127
+ }
1128
+ return allInnerTransitions;
1129
+ }
1130
+ function isDescendant(childStateNode, parentStateNode) {
1131
+ let marker = childStateNode;
1132
+ while (marker.parent && marker.parent !== parentStateNode) {
1133
+ marker = marker.parent;
1134
+ }
1135
+ return marker.parent === parentStateNode;
1136
+ }
1137
+ function hasDescendantState(stateNodes, parentStateNode) {
1138
+ for (const stateNode of stateNodes) {
1139
+ if (isDescendant(stateNode, parentStateNode)) {
1140
+ return true;
1141
+ }
1142
+ }
1143
+ return false;
1144
+ }
1145
+ function hasIntersection(s1, s2) {
1146
+ const s1Size = s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;
1147
+ const s2Size = s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;
1148
+ if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {
1149
+ [s1, s2] = [s2, s1];
1150
+ }
1151
+ const set1 = s1 instanceof Set ? s1 : new Set(s1);
1152
+ for (const item of s2) {
1153
+ if (set1.has(item)) {
1154
+ return true;
1155
+ }
1156
+ }
1157
+ return false;
1158
+ }
1159
+ function removeConflictingTransitions(enabledTransitions, stateNodeSet, snapshot, event, actorScope) {
1160
+ const filteredTransitions = new Set();
1161
+ const exitSets = new Map();
1162
+ const getExitSet = transition => {
1163
+ let exitSet = exitSets.get(transition);
1164
+ if (!exitSet) {
1165
+ exitSet = computeExitSet([transition], stateNodeSet, snapshot, event, actorScope);
1166
+ exitSets.set(transition, exitSet);
1167
+ }
1168
+ return exitSet;
1169
+ };
1170
+ for (const t1 of enabledTransitions) {
1171
+ let t1Preempted = false;
1172
+ const transitionsToRemove = new Set();
1173
+ for (const t2 of filteredTransitions) {
1174
+ if (hasIntersection(getExitSet(t1), getExitSet(t2))) {
1175
+ if (isDescendant(t1.source, t2.source)) {
1176
+ transitionsToRemove.add(t2);
1177
+ } else {
1178
+ t1Preempted = true;
1179
+ break;
1180
+ }
1181
+ }
1182
+ }
1183
+ if (!t1Preempted) {
1184
+ for (const t3 of transitionsToRemove) {
1185
+ filteredTransitions.delete(t3);
1186
+ }
1187
+ filteredTransitions.add(t1);
1188
+ }
1189
+ }
1190
+ return Array.from(filteredTransitions);
1191
+ }
1192
+ function getEffectiveTargetStates(transition, snapshot, event, actorScope) {
1193
+ const historyValue = snapshot.historyValue;
1194
+ const {
1195
+ targets
1196
+ } = getTransitionResult(transition, snapshot, event, actorScope);
1197
+ if (!targets) {
1198
+ return [];
1199
+ }
1200
+ const targetSet = new Set();
1201
+ for (const targetNode of targets) {
1202
+ if (isHistoryNode(targetNode)) {
1203
+ if (historyValue[targetNode.id]) {
1204
+ for (const node of historyValue[targetNode.id]) {
1205
+ targetSet.add(node);
1206
+ }
1207
+ } else {
1208
+ for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), snapshot, event, actorScope)) {
1209
+ targetSet.add(node);
1210
+ }
1211
+ }
1212
+ } else {
1213
+ targetSet.add(targetNode);
1214
+ }
1215
+ }
1216
+ return [...targetSet];
1217
+ }
1218
+ function getTransitionDomain(transition, snapshot, event, actorScope) {
1219
+ const targetStates = getEffectiveTargetStates(transition, snapshot, event, actorScope);
1220
+ const {
1221
+ reenter
1222
+ } = getTransitionResult(transition, snapshot, event, actorScope);
1223
+ if (!reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {
1224
+ return transition.source;
1225
+ }
1226
+ const [head, ...tail] = targetStates.concat(transition.source);
1227
+ // Find the least common ancestor (LCA) of the source and effective targets.
1228
+ for (const ancestor of getProperAncestors(head, undefined)) {
1229
+ if (tail.every(sn => isDescendant(sn, ancestor))) {
1230
+ return ancestor;
1231
+ }
1232
+ }
1233
+
1234
+ // at this point we know that it's a root transition since LCA couldn't be found
1235
+ if (reenter) {
1236
+ return;
1237
+ }
1238
+ return transition.source.machine.root;
1239
+ }
1240
+ function computeExitSet(transitions, stateNodeSet, snapshot, event, actorScope) {
1241
+ const statesToExit = new Set();
1242
+ for (const transition of transitions) {
1243
+ const {
1244
+ targets
1245
+ } = getTransitionResult(transition, snapshot, event, actorScope);
1246
+ if (targets?.length) {
1247
+ const domain = getTransitionDomain(transition, snapshot, event, actorScope);
1248
+ if (transition.reenter && transition.source === domain) {
1249
+ statesToExit.add(domain);
1250
+ }
1251
+ for (const stateNode of stateNodeSet) {
1252
+ if (isDescendant(stateNode, domain)) {
1253
+ statesToExit.add(stateNode);
1254
+ }
1255
+ }
1256
+ }
1257
+ }
1258
+ return [...statesToExit];
1259
+ }
1260
+ function initialMicrostep(root, preInitialState, actorScope, initEvent, internalQueue) {
1261
+ return microstep([{
1262
+ target: [...getInitialStateNodes(root)],
1263
+ source: root,
1264
+ reenter: true,
1265
+ eventType: null,
1266
+ toJSON: null
1267
+ }], preInitialState, actorScope, initEvent, true, internalQueue);
1268
+ }
1269
+ function mergeContextPatch(context, patch) {
1270
+ return {
1271
+ ...context,
1272
+ ...patch
1273
+ };
1274
+ }
1275
+
1276
+ /** https://www.w3.org/TR/scxml/#microstepProcedure */
1277
+ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
1278
+ const executableActions = [];
1279
+ if (!transitions.length) {
1280
+ return [currentSnapshot, executableActions];
1281
+ }
1282
+ {
1283
+ const mutStateNodeSet = new Set(currentSnapshot._nodes);
1284
+ let historyValue = currentSnapshot.historyValue;
1285
+ const originalContext = currentSnapshot.context;
1286
+ const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, currentSnapshot, event, actorScope);
1287
+ const getCurrentTransitionResult = transition => getTransitionResult(transition, currentSnapshot, event, actorScope);
1288
+ const getStateActionsAndContext = (transitionFn, context, children, input) => {
1289
+ if (transitionFn.length === 2) {
1290
+ // enqueue action; retrieve
1291
+ const actions = [];
1292
+ const internalEvents = [];
1293
+ let updatedContext;
1294
+ const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, true);
1295
+ const res = transitionFn({
1296
+ context,
1297
+ event,
1298
+ parent: actorScope.self._parent,
1299
+ self: actorScope.self,
1300
+ children,
1301
+ system: actorScope.system,
1302
+ actions: currentSnapshot.machine.implementations.actions,
1303
+ actorSources: currentSnapshot.machine.implementations.actorSources,
1304
+ guards: currentSnapshot.machine.implementations.guards,
1305
+ delays: currentSnapshot.machine.implementations.delays,
1306
+ input
1307
+ }, enqueue);
1308
+ if (res?.context !== undefined) {
1309
+ updatedContext = mergeContextPatch(context, res.context);
1310
+ }
1311
+ return [actions, updatedContext, internalEvents];
1312
+ }
1313
+
1314
+ // For 1-argument actions, wrap them to include input
1315
+ // Preserve _special flag if present (for entry/exit actions)
1316
+ const wrappedAction = Object.assign((args, enqueue) => transitionFn({
1317
+ ...args,
1318
+ input
1319
+ }, enqueue), '_special' in transitionFn ? {
1320
+ _special: true
1321
+ } : {});
1322
+ return [[wrappedAction], undefined, undefined];
1323
+ };
1324
+ let nextState = currentSnapshot;
1325
+ const exitStates = () => {
1326
+ const statesToExit = computeExitSet(filteredTransitions, mutStateNodeSet, currentSnapshot, event, actorScope);
1327
+ statesToExit.sort((a, b) => b.order - a.order);
1328
+ let changedHistory;
1329
+ const currentStateNodes = [...mutStateNodeSet];
1330
+
1331
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
1332
+ for (const exitStateNode of statesToExit) {
1333
+ for (const historyNode of Object.values(exitStateNode.states)) {
1334
+ if (historyNode.type !== 'history') {
1335
+ continue;
1336
+ }
1337
+ const predicate = historyNode.history === 'deep' ? sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode) : sn => sn.parent === exitStateNode;
1338
+ changedHistory ??= {
1339
+ ...historyValue
1340
+ };
1341
+ changedHistory[historyNode.id] = currentStateNodes.filter(predicate);
1342
+ }
1343
+ }
1344
+ for (const exitStateNode of statesToExit) {
1345
+ const stateInput = currentSnapshot._stateInputs?.[exitStateNode.id];
1346
+ const [exitActions, nextContext, internalEvents] = exitStateNode.exit ? getStateActionsAndContext(exitStateNode.exit, nextState.context, currentSnapshot.children, stateInput) : [[]];
1347
+ if (internalEvents?.length) {
1348
+ internalQueue.push(...internalEvents);
1349
+ }
1350
+ if (nextContext) {
1351
+ nextState = cloneMachineSnapshot(nextState, {
1352
+ context: nextContext
1353
+ });
1354
+ }
1355
+ const [resolvedState, resolvedActions] = resolveActionsWithContext(nextState, event, actorScope, exitActions);
1356
+ nextState = resolvedState;
1357
+ executableActions.push(...resolvedActions);
1358
+ for (const def of exitStateNode.invoke) {
1359
+ const childActor = nextState.children[def.id];
1360
+ if (childActor && !childActor._isExternal) {
1361
+ actorScope.stopChild(childActor);
1362
+ }
1363
+ delete nextState.children[def.id];
1364
+ }
1365
+ mutStateNodeSet.delete(exitStateNode);
1366
+ }
1367
+ historyValue = changedHistory || historyValue;
1368
+ };
1369
+
1370
+ // Exit states
1371
+ if (!isInitial) {
1372
+ exitStates();
1373
+ }
1374
+ let context = nextState.context;
1375
+ const transitionActions = [];
1376
+ const internalEvents = [];
1377
+ for (const t of filteredTransitions) {
1378
+ if (t.actions) {
1379
+ transitionActions.push(...toArray(t.actions));
1380
+ }
1381
+ const res = getCurrentTransitionResult(t);
1382
+ if (res.context !== undefined) {
1383
+ context = mergeContextPatch(context, res.context);
1384
+ }
1385
+ if (res.actions) {
1386
+ transitionActions.push(...res.actions);
1387
+ }
1388
+ if (res.internalEvents) {
1389
+ internalEvents.push(...res.internalEvents);
1390
+ }
1391
+ }
1392
+ if (internalEvents.length) {
1393
+ internalQueue.push(...internalEvents);
1394
+ }
1395
+ const enterStates = () => {
1396
+ const getMachineOutput = rootCompletionNode => {
1397
+ const rootNode = nextState.machine.root;
1398
+ if (rootNode.output === undefined) {
1399
+ return;
1400
+ }
1401
+ let completionOutput;
1402
+ if (rootCompletionNode.output !== undefined && rootCompletionNode.parent) {
1403
+ completionOutput = resolveOutput(rootCompletionNode.output, nextState.context, event, actorScope.self);
1404
+ } else if (rootCompletionNode.type === 'parallel') {
1405
+ const parallelDoneType = `xstate.done.state.${rootCompletionNode.id}`;
1406
+ const parallelDoneEvent = internalQueue.find(e => e.type === parallelDoneType);
1407
+ completionOutput = parallelDoneEvent?.output;
1408
+ }
1409
+ return resolveOutput(rootNode.output, nextState.context, createDoneStateEvent(rootCompletionNode.id, completionOutput), actorScope.self);
1410
+ };
1411
+ const statesToEnter = new Set();
1412
+ // those are states that were directly targeted or indirectly targeted by the explicit target
1413
+ // in other words, those are states for which initial actions should be executed
1414
+ // when we target `#deep_child` initial actions of its ancestors shouldn't be executed
1415
+ const statesForDefaultEntry = new Set();
1416
+ const addAncestorStatesToEnter = (ancestors, reentrancyDomain) => {
1417
+ for (const anc of ancestors) {
1418
+ if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
1419
+ statesToEnter.add(anc);
1420
+ }
1421
+ if (anc.type === 'parallel') {
1422
+ for (const child of getChildren(anc)) {
1423
+ if (!hasDescendantState(statesToEnter, child)) {
1424
+ statesToEnter.add(child);
1425
+ addDescendantStatesToEnter(child);
1426
+ }
1427
+ }
1428
+ }
1429
+ }
1430
+ };
1431
+ const addDescendantStatesToEnter = stateNode => {
1432
+ if (isHistoryNode(stateNode)) {
1433
+ if (historyValue[stateNode.id]) {
1434
+ const historyStateNodes = historyValue[stateNode.id];
1435
+ for (const s of historyStateNodes) {
1436
+ statesToEnter.add(s);
1437
+ addDescendantStatesToEnter(s);
1438
+ }
1439
+ for (const s of historyStateNodes) {
1440
+ addAncestorStatesToEnter(getProperAncestors(s, stateNode.parent), undefined);
1441
+ }
1442
+ } else {
1443
+ const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
1444
+ const {
1445
+ targets
1446
+ } = getCurrentTransitionResult(historyDefaultTransition);
1447
+ for (const s of targets ?? []) {
1448
+ statesToEnter.add(s);
1449
+ if (historyDefaultTransition === stateNode.parent?.initial) {
1450
+ statesForDefaultEntry.add(stateNode.parent);
1451
+ }
1452
+ addDescendantStatesToEnter(s);
1453
+ }
1454
+ for (const s of targets ?? []) {
1455
+ addAncestorStatesToEnter(getProperAncestors(s, stateNode.parent), undefined);
1456
+ }
1457
+ }
1458
+ return;
1459
+ }
1460
+ if (stateNode.type === 'compound') {
1461
+ const [initialState] = getCurrentTransitionResult(stateNode.initial).targets;
1462
+ if (!isHistoryNode(initialState)) {
1463
+ statesToEnter.add(initialState);
1464
+ statesForDefaultEntry.add(initialState);
1465
+ }
1466
+ addDescendantStatesToEnter(initialState);
1467
+ addAncestorStatesToEnter(getProperAncestors(initialState, stateNode), undefined);
1468
+ return;
1469
+ }
1470
+ if (stateNode.type === 'parallel') {
1471
+ for (const child of getChildren(stateNode)) {
1472
+ if (!hasDescendantState(statesToEnter, child)) {
1473
+ statesToEnter.add(child);
1474
+ statesForDefaultEntry.add(child);
1475
+ addDescendantStatesToEnter(child);
1476
+ }
1477
+ }
1478
+ }
1479
+ };
1480
+ for (const transition of filteredTransitions) {
1481
+ const domain = getTransitionDomain(transition, currentSnapshot, event, actorScope);
1482
+ const {
1483
+ targets,
1484
+ reenter
1485
+ } = getCurrentTransitionResult(transition);
1486
+ for (const targetNode of targets ?? []) {
1487
+ if (!isHistoryNode(targetNode) && (transition.source !== targetNode || transition.source !== domain || reenter)) {
1488
+ statesToEnter.add(targetNode);
1489
+ statesForDefaultEntry.add(targetNode);
1490
+ }
1491
+ addDescendantStatesToEnter(targetNode);
1492
+ }
1493
+ const targetStates = getEffectiveTargetStates(transition, currentSnapshot, event, actorScope);
1494
+ for (const s of targetStates) {
1495
+ const ancestors = getProperAncestors(s, domain);
1496
+ if (domain?.type === 'parallel') {
1497
+ ancestors.push(domain);
1498
+ }
1499
+ addAncestorStatesToEnter(ancestors, !transition.source.parent && reenter ? undefined : domain);
1500
+ }
1501
+ }
1502
+ if (isInitial) {
1503
+ statesForDefaultEntry.add(currentSnapshot.machine.root);
1504
+ }
1505
+ const stateInputMap = {
1506
+ ...currentSnapshot._stateInputs
1507
+ };
1508
+ for (const transition of filteredTransitions) {
1509
+ const {
1510
+ targets,
1511
+ input
1512
+ } = getCurrentTransitionResult(transition);
1513
+ if (input && targets) {
1514
+ for (const targetNode of targets) {
1515
+ stateInputMap[targetNode.id] = input;
1516
+ }
1517
+ }
1518
+ }
1519
+ const completedNodes = new Set();
1520
+ const children = {
1521
+ ...currentSnapshot.children
1522
+ };
1523
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
1524
+ mutStateNodeSet.add(stateNodeToEnter);
1525
+ const actions = [];
1526
+ let invoked = false;
1527
+ for (const invokeDef of stateNodeToEnter.invoke) {
1528
+ invoked = true;
1529
+ let src = invokeDef.logic;
1530
+ if (typeof src === 'function') {
1531
+ src = src({
1532
+ actorSources: currentSnapshot.machine.implementations.actorSources,
1533
+ context: nextState.context,
1534
+ event,
1535
+ self: actorScope.self
1536
+ });
1537
+ }
1538
+ const logic = typeof src === 'string' ? resolveReferencedActor(currentSnapshot.machine, src) : src;
1539
+ if (!logic) {
1540
+ throw new Error(`Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in machine '${currentSnapshot.machine.id}'`);
1541
+ }
1542
+ const input = typeof invokeDef.input === 'function' ? invokeDef.input({
1543
+ self: actorScope.self,
1544
+ context: nextState.context,
1545
+ event,
1546
+ output: getEventOutput(event)
1547
+ }) : invokeDef.input;
1548
+ const actor = createActor(logic, {
1549
+ ...invokeDef,
1550
+ input,
1551
+ parent: actorScope.self,
1552
+ syncSnapshot: !!invokeDef.onSnapshot
1553
+ });
1554
+ actions.push({
1555
+ action: builtInActions['@xstate.start'],
1556
+ args: [actor]
1557
+ });
1558
+ if (invokeDef.id) {
1559
+ children[invokeDef.id] = actor;
1560
+ }
1561
+ }
1562
+ if (invoked) {
1563
+ nextState = cloneMachineSnapshot(nextState, {
1564
+ children
1565
+ });
1566
+ }
1567
+ let context = nextState.context;
1568
+ let contextChangedByEntry = false;
1569
+ const stateInput = stateInputMap[stateNodeToEnter.id];
1570
+ if (stateNodeToEnter.entry) {
1571
+ const [resultActions, nextContext, nextInternalEvents] = getStateActionsAndContext(stateNodeToEnter.entry, context, children, stateInput);
1572
+ actions.push(...resultActions);
1573
+ if (nextInternalEvents?.length) {
1574
+ internalQueue.push(...nextInternalEvents);
1575
+ }
1576
+ if (nextContext) {
1577
+ context = nextContext;
1578
+ contextChangedByEntry = true;
1579
+ }
1580
+ }
1581
+ if (contextChangedByEntry) {
1582
+ nextState.context = context;
1583
+ }
1584
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
1585
+ const {
1586
+ actions: initialActions,
1587
+ input: initialInput
1588
+ } = getTransitionResult(stateNodeToEnter.initial, nextState, event, actorScope);
1589
+ if (initialActions) {
1590
+ actions.push(...initialActions);
1591
+ }
1592
+ if (initialInput && stateNodeToEnter.initial?.target) {
1593
+ for (const targetNode of stateNodeToEnter.initial.target) {
1594
+ stateInputMap[targetNode.id] = initialInput;
1595
+ }
1596
+ }
1597
+ }
1598
+ const [resolvedState, resolvedActions] = resolveActionsWithContext(nextState, event, actorScope, actions);
1599
+ nextState = resolvedState;
1600
+ actions.length = 0;
1601
+ executableActions.push(...resolvedActions);
1602
+ if (stateNodeToEnter.type !== 'final') {
1603
+ continue;
1604
+ }
1605
+ const parent = stateNodeToEnter.parent;
1606
+ let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;
1607
+ let rootCompletionNode = ancestorMarker || stateNodeToEnter;
1608
+ if (parent?.type === 'compound') {
1609
+ internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextState.context, event, actorScope.self) : undefined));
1610
+ }
1611
+ while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
1612
+ completedNodes.add(ancestorMarker);
1613
+ const regionOutput = {};
1614
+ for (const region of getChildren(ancestorMarker)) {
1615
+ if (region.type === 'final') {
1616
+ regionOutput[region.key] = region.output !== undefined ? resolveOutput(region.output, nextState.context, event, actorScope.self) : undefined;
1617
+ continue;
1618
+ }
1619
+ if (region.type === 'parallel') {
1620
+ const regionDoneType = `xstate.done.state.${region.id}`;
1621
+ const regionDoneEvent = internalQueue.find(e => e.type === regionDoneType);
1622
+ regionOutput[region.key] = regionDoneEvent?.output;
1623
+ continue;
1624
+ }
1625
+ const finalChild = getChildren(region).find(s => s.type === 'final' && mutStateNodeSet.has(s));
1626
+ regionOutput[region.key] = finalChild?.output !== undefined ? resolveOutput(finalChild.output, nextState.context, event, actorScope.self) : undefined;
1627
+ }
1628
+ internalQueue.push(createDoneStateEvent(ancestorMarker.id, regionOutput));
1629
+ rootCompletionNode = ancestorMarker;
1630
+ ancestorMarker = ancestorMarker.parent;
1631
+ }
1632
+ if (ancestorMarker) {
1633
+ continue;
1634
+ }
1635
+ nextState = cloneMachineSnapshot(nextState, {
1636
+ status: 'done',
1637
+ output: getMachineOutput(rootCompletionNode)
1638
+ });
1639
+ }
1640
+ const inputChanged = JSON.stringify(stateInputMap) !== JSON.stringify(currentSnapshot._stateInputs || {});
1641
+ if (inputChanged) {
1642
+ nextState = cloneMachineSnapshot(nextState, {
1643
+ _stateInputs: stateInputMap
1644
+ });
1645
+ }
1646
+ };
1647
+
1648
+ // Execute transition content
1649
+ const [resolvedTransitionState, transitionExecutableActions] = resolveActionsWithContext(nextState, event, actorScope, transitionActions);
1650
+ nextState = resolvedTransitionState;
1651
+ executableActions.push(...transitionExecutableActions);
1652
+ if (context && context !== currentSnapshot.context) {
1653
+ nextState = cloneMachineSnapshot(nextState, {
1654
+ context
1655
+ });
1656
+ }
1657
+
1658
+ // Enter states
1659
+ enterStates();
1660
+ const nextStateNodes = [...mutStateNodeSet];
1661
+ if (nextState.status === 'done') {
1662
+ const allExitActions = [];
1663
+ const nextStateNodesToExit = nextStateNodes.sort((a, b) => b.order - a.order);
1664
+ nextStateNodesToExit.forEach(stateNode => {
1665
+ if (stateNode.exit) {
1666
+ const stateInput = nextState._stateInputs?.[stateNode.id];
1667
+ const [exitActions,, nextInternalEvents] = getStateActionsAndContext(stateNode.exit, nextState.context, nextState.children, stateInput);
1668
+ allExitActions.push(...exitActions);
1669
+ if (nextInternalEvents?.length) {
1670
+ internalQueue.push(...nextInternalEvents);
1671
+ }
1672
+ }
1673
+ });
1674
+ const [resolvedState, resolvedActions] = resolveActionsWithContext(nextState, event, actorScope, allExitActions);
1675
+ nextState = resolvedState;
1676
+ executableActions.push(...resolvedActions);
1677
+ }
1678
+ if (historyValue === currentSnapshot.historyValue && currentSnapshot._nodes.length === mutStateNodeSet.size && currentSnapshot._nodes.every(node => mutStateNodeSet.has(node))) {
1679
+ // If context was changed (e.g. by entry actions during self-transition),
1680
+ // clone to ensure reference inequality for eventless transition re-evaluation
1681
+ if (nextState.context !== originalContext) {
1682
+ return [cloneMachineSnapshot(nextState), executableActions];
1683
+ }
1684
+ return [nextState, executableActions];
1685
+ }
1686
+ return [cloneMachineSnapshot(nextState, {
1687
+ _nodes: nextStateNodes,
1688
+ historyValue
1689
+ }), executableActions];
1690
+ }
1691
+ }
1692
+
1693
+ /**
1694
+ * Gets the transition result for a given transition without executing the
1695
+ * transition.
1696
+ */
1697
+ function getTransitionResult(transition, snapshot, event, actorScope) {
1698
+ if (transition.to) {
1699
+ const actions = [];
1700
+ const internalEvents = [];
1701
+ const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents);
1702
+ const res = transition.to({
1703
+ context: snapshot.context,
1704
+ event,
1705
+ output: getEventOutput(event),
1706
+ value: snapshot.value,
1707
+ children: snapshot.children,
1708
+ system: actorScope.system,
1709
+ parent: actorScope.self._parent,
1710
+ self: actorScope.self,
1711
+ actions: snapshot.machine.implementations.actions,
1712
+ actorSources: snapshot.machine.implementations.actorSources,
1713
+ guards: snapshot.machine.implementations.guards,
1714
+ delays: snapshot.machine.implementations.delays
1715
+ }, enqueue);
1716
+ const targets = res?.target ? resolveTarget(transition.source, toArray(res.target)) : undefined;
1717
+ // Resolve input for .to transitions
1718
+ const resolvedInput = typeof transition.input === 'function' ? transition.input({
1719
+ context: snapshot.context,
1720
+ event,
1721
+ output: getEventOutput(event)
1722
+ }) : transition.input;
1723
+ return {
1724
+ targets: targets,
1725
+ context: res?.context,
1726
+ reenter: res?.reenter,
1727
+ actions,
1728
+ internalEvents,
1729
+ input: resolvedInput
1730
+ };
1731
+ }
1732
+
1733
+ // Resolve input for regular transitions
1734
+ const resolvedInput = typeof transition.input === 'function' ? transition.input({
1735
+ context: snapshot.context,
1736
+ event,
1737
+ output: getEventOutput(event)
1738
+ }) : transition.input;
1739
+ return {
1740
+ targets: transition.target,
1741
+ context: transition.context,
1742
+ reenter: transition.reenter,
1743
+ actions: undefined,
1744
+ internalEvents: undefined,
1745
+ input: resolvedInput
1746
+ };
1747
+ }
1748
+ function macrostep(snapshot, event, actorScope, internalQueue) {
1749
+ let nextSnapshot = snapshot;
1750
+ const microsteps = [];
1751
+ function addMicrostep(step, transitions) {
1752
+ // collect microsteps; surfaced on the enclosing '@xstate.transition' event
1753
+ // via its `microsteps[]` facet (there is no standalone microstep event)
1754
+ const collectedMicrosteps = actorScope.self._collectedMicrosteps || [];
1755
+ collectedMicrosteps.push(...transitions);
1756
+ actorScope.self._collectedMicrosteps = collectedMicrosteps;
1757
+ microsteps.push(step);
1758
+ }
1759
+
1760
+ // Handle stop event
1761
+ if (event.type === XSTATE_STOP) {
1762
+ nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, actorScope), {
1763
+ status: 'stopped'
1764
+ });
1765
+ addMicrostep([nextSnapshot, []], []);
1766
+ return {
1767
+ snapshot: nextSnapshot,
1768
+ microsteps
1769
+ };
1770
+ }
1771
+ let nextEvent = event;
1772
+
1773
+ // Assume the state is at rest (no raised events)
1774
+ // Determine the next state based on the next microstep
1775
+ if (nextEvent.type !== XSTATE_INIT) {
1776
+ const currentEvent = nextEvent;
1777
+ const isErr = isErrorActorEvent(currentEvent);
1778
+ const transitions = nextSnapshot.machine.getTransitionData(nextSnapshot, currentEvent, actorScope.self);
1779
+ if (isErr && !transitions.length) {
1780
+ // TODO: we should likely only allow transitions selected by very explicit descriptors
1781
+ // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either
1782
+ // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
1783
+ nextSnapshot = cloneMachineSnapshot(snapshot, {
1784
+ status: 'error',
1785
+ error: currentEvent.error
1786
+ });
1787
+ addMicrostep([nextSnapshot, []], []);
1788
+ return {
1789
+ snapshot: nextSnapshot,
1790
+ microsteps
1791
+ };
1792
+ }
1793
+ const step = microstep(transitions, snapshot, actorScope, nextEvent, false,
1794
+ // isInitial
1795
+ internalQueue);
1796
+ nextSnapshot = step[0];
1797
+ addMicrostep(step, transitions);
1798
+ }
1799
+ let shouldSelectEventlessTransitions = true;
1800
+ const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;
1801
+ let iterationCount = 0;
1802
+ let microstepCount = 0;
1803
+ while (nextSnapshot.status === 'active') {
1804
+ microstepCount++;
1805
+ if (microstepCount > 1000) {
1806
+ throw new Error('Microstep count exceeded 1000');
1807
+ }
1808
+ iterationCount++;
1809
+ if (iterationCount > maxIterations) {
1810
+ throw new Error(`Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).` );
1811
+ }
1812
+ let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope) : [];
1813
+
1814
+ // eventless transitions should always be selected after selecting *regular* transitions
1815
+ // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case
1816
+ const previousState = enabledTransitions.length ? nextSnapshot : undefined;
1817
+ if (!enabledTransitions.length) {
1818
+ if (!internalQueue.length) {
1819
+ break;
1820
+ }
1821
+ nextEvent = internalQueue.shift();
1822
+ enabledTransitions = nextSnapshot.machine.getTransitionData(nextSnapshot, nextEvent, actorScope.self);
1823
+ }
1824
+ const step = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
1825
+ nextSnapshot = step[0];
1826
+ shouldSelectEventlessTransitions = nextSnapshot !== previousState;
1827
+ addMicrostep(step, enabledTransitions);
1828
+ }
1829
+ if (nextSnapshot.status !== 'active' && nextSnapshot.children) {
1830
+ stopChildren(nextSnapshot, actorScope);
1831
+ }
1832
+ return {
1833
+ snapshot: nextSnapshot,
1834
+ microsteps
1835
+ };
1836
+ }
1837
+
1838
+ /**
1839
+ * Resolves a partial state value with its full representation in the state
1840
+ * node's machine.
1841
+ *
1842
+ * @param stateValue The partial state value to resolve.
1843
+ */
1844
+ function resolveStateValue(rootNode, stateValue) {
1845
+ const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
1846
+ return getStateValue(rootNode, allStateNodes);
1847
+ }
1848
+ function createEnqueueObject(props, action) {
1849
+ const enqueueFn = (fn, ...args) => {
1850
+ action(fn, ...args);
1851
+ };
1852
+ Object.assign(enqueueFn, {
1853
+ cancel: () => {},
1854
+ emit: () => {},
1855
+ log: () => {},
1856
+ raise: () => {},
1857
+ spawn: () => ({}),
1858
+ sendTo: () => {},
1859
+ stop: () => {},
1860
+ listen: () => ({}),
1861
+ subscribeTo: () => ({}),
1862
+ ...props
1863
+ });
1864
+ return enqueueFn;
1865
+ }
1866
+ function hasEffect(transition, context, event, snapshot, self) {
1867
+ if (transition.to) {
1868
+ return transitionToHasEffect(transition.to, context, event, snapshot, self, snapshot.machine.implementations);
1869
+ }
1870
+ return false;
1871
+ }
1872
+ function transitionToHasEffect(transitionTo, context, event, snapshot, self, implementations) {
1873
+ let hasEffect = false;
1874
+ let res;
1875
+ try {
1876
+ const triggerEffect = () => {
1877
+ hasEffect = true;
1878
+ throw new Error('Effect triggered');
1879
+ };
1880
+ res = transitionTo({
1881
+ context,
1882
+ event,
1883
+ output: getEventOutput(event),
1884
+ self,
1885
+ system: self.system,
1886
+ value: snapshot.value,
1887
+ children: snapshot.children,
1888
+ parent: {
1889
+ send: triggerEffect
1890
+ },
1891
+ actions: implementations.actions,
1892
+ actorSources: implementations.actorSources,
1893
+ guards: implementations.guards,
1894
+ delays: implementations.delays
1895
+ }, createEnqueueObject({
1896
+ emit: triggerEffect,
1897
+ cancel: triggerEffect,
1898
+ log: triggerEffect,
1899
+ raise: triggerEffect,
1900
+ spawn: triggerEffect,
1901
+ sendTo: triggerEffect,
1902
+ stop: triggerEffect
1903
+ }, triggerEffect));
1904
+ } catch (err) {
1905
+ if (hasEffect) {
1906
+ return true;
1907
+ }
1908
+ throw err;
1909
+ }
1910
+ return res !== undefined;
1911
+ }
1912
+ function stopChildren(snapshot, actorScope) {
1913
+ let children;
1914
+ if (!snapshot.children || (children = Object.values(snapshot.children).filter(Boolean)).length === 0) {
1915
+ return snapshot;
1916
+ }
1917
+ for (const child of children) {
1918
+ actorScope.stopChild(child);
1919
+ }
1920
+ return cloneMachineSnapshot(snapshot, {
1921
+ children: {}
1922
+ });
1923
+ }
1924
+ function selectEventlessTransitions(snapshot, event, actorScope) {
1925
+ const enabledTransitionSet = new Set();
1926
+ const atomicStates = snapshot._nodes.filter(isAtomicStateNode);
1927
+ for (const atomicStateNode of atomicStates) {
1928
+ loop: for (let stateNode = atomicStateNode; stateNode; stateNode = stateNode.parent) {
1929
+ if (!stateNode.always) {
1930
+ continue;
1931
+ }
1932
+ for (const transition of stateNode.always) {
1933
+ if (evaluateCandidate(transition, event, snapshot, stateNode, actorScope.self)) {
1934
+ enabledTransitionSet.add(transition);
1935
+ break loop;
1936
+ }
1937
+ }
1938
+ }
1939
+ }
1940
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(snapshot._nodes), snapshot, event, actorScope);
1941
+ }
1942
+ function evaluateCandidate(candidate, event, snapshot, stateNode, self) {
1943
+ if (candidate.guard) {
1944
+ const guardArgs = {
1945
+ context: snapshot.context,
1946
+ event,
1947
+ output: getEventOutput(event),
1948
+ self,
1949
+ parent: self._parent,
1950
+ children: snapshot.children,
1951
+ actions: stateNode.machine.implementations.actions,
1952
+ actorSources: stateNode.machine.implementations.actorSources,
1953
+ guards: stateNode.machine.implementations.guards,
1954
+ delays: stateNode.machine.implementations.delays,
1955
+ _snapshot: snapshot
1956
+ };
1957
+ if (!candidate.guard(guardArgs)) {
1958
+ return false;
1959
+ }
1960
+ }
1961
+ if (candidate.to) {
1962
+ return transitionToHasEffect(candidate.to, snapshot.context, event, snapshot, self, stateNode.machine.implementations);
1963
+ }
1964
+ return true;
1965
+ }
1966
+
1967
+ function isMachineSnapshot(value) {
1968
+ return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;
1969
+ }
1970
+ let emptyCanActor;
1971
+ let emptyCanActorScope;
1972
+ function getEmptyCanActor() {
1973
+ return emptyCanActor ??= createEmptyActor();
1974
+ }
1975
+ function getEmptyCanActorScope() {
1976
+ if (emptyCanActorScope) {
1977
+ return emptyCanActorScope;
1978
+ }
1979
+ const actor = getEmptyCanActor();
1980
+ emptyCanActorScope = {
1981
+ self: actor,
1982
+ logger: () => {},
1983
+ id: '',
1984
+ sessionId: '',
1985
+ defer: () => {},
1986
+ system: actor.system,
1987
+ stopChild: () => {},
1988
+ emit: () => {},
1989
+ actionExecutor: () => {}
1990
+ };
1991
+ return emptyCanActorScope;
1992
+ }
1993
+ const machineSnapshotMatches = function matches(testValue) {
1994
+ return matchesState(testValue, this.value);
1995
+ };
1996
+ const machineSnapshotHasTag = function hasTag(tag) {
1997
+ return this.tags.has(tag);
1998
+ };
1999
+ const machineSnapshotCan = function can(event) {
2000
+ if (!this.machine) {
2001
+ console.warn(`state.can(...) used outside of a machine-created State object; this will always return false.`);
2002
+ }
2003
+ const emptyActor = getEmptyCanActor();
2004
+ const emptyActorScope = getEmptyCanActorScope();
2005
+ const transitionData = this.machine.getTransitionData(this, event, emptyActor);
2006
+ if (!transitionData?.length) {
2007
+ return false;
2008
+ }
2009
+
2010
+ // Check that at least one transition is not forbidden
2011
+ for (const transition of transitionData) {
2012
+ if (transition.target !== undefined) {
2013
+ return true;
2014
+ }
2015
+ const res = getTransitionResult(transition, this, event, emptyActorScope);
2016
+ if (res.targets?.length || res.context || hasEffect(transition, this.context, event, this, emptyActor)) {
2017
+ return true;
2018
+ }
2019
+ }
2020
+ return false;
2021
+ };
2022
+ const machineSnapshotToJSON = function toJSON() {
2023
+ const {
2024
+ _nodes: nodes,
2025
+ _stateInputs,
2026
+ tags,
2027
+ machine,
2028
+ getMeta,
2029
+ getInputs,
2030
+ toJSON,
2031
+ can,
2032
+ hasTag,
2033
+ matches,
2034
+ ...jsonValues
2035
+ } = this;
2036
+ return {
2037
+ ...jsonValues,
2038
+ tags: Array.from(tags)
2039
+ };
2040
+ };
2041
+ const machineSnapshotGetMeta = function getMeta() {
2042
+ const meta = {};
2043
+ for (const stateNode of this._nodes) {
2044
+ if (stateNode.meta !== undefined) {
2045
+ meta[stateNode.id] = stateNode.meta;
2046
+ }
2047
+ }
2048
+ return meta;
2049
+ };
2050
+ const machineSnapshotGetInputs = function getInputs() {
2051
+ return this._stateInputs;
2052
+ };
2053
+ function collectTags(stateNodes) {
2054
+ const tags = new Set();
2055
+ for (const stateNode of stateNodes) {
2056
+ for (const tag of stateNode.tags) {
2057
+ tags.add(tag);
2058
+ }
2059
+ }
2060
+ return tags;
2061
+ }
2062
+ function createMachineSnapshot(config, machine) {
2063
+ return {
2064
+ status: config.status,
2065
+ output: config.output,
2066
+ error: config.error,
2067
+ machine,
2068
+ context: config.context,
2069
+ _nodes: config._nodes,
2070
+ value: config.value ?? getStateValue(machine.root, config._nodes),
2071
+ tags: collectTags(config._nodes),
2072
+ children: config.children,
2073
+ historyValue: config.historyValue || {},
2074
+ _stateInputs: config._stateInputs || {},
2075
+ matches: machineSnapshotMatches,
2076
+ hasTag: machineSnapshotHasTag,
2077
+ can: machineSnapshotCan,
2078
+ getMeta: machineSnapshotGetMeta,
2079
+ getInputs: machineSnapshotGetInputs,
2080
+ toJSON: machineSnapshotToJSON
2081
+ };
2082
+ }
2083
+ function cloneMachineSnapshot(snapshot, config = {}) {
2084
+ const configWithSnapshot = {
2085
+ ...snapshot,
2086
+ ...config
2087
+ };
2088
+ if ((config._nodes ?? snapshot._nodes) === snapshot._nodes) {
2089
+ return {
2090
+ status: configWithSnapshot.status,
2091
+ output: configWithSnapshot.output,
2092
+ error: configWithSnapshot.error,
2093
+ machine: snapshot.machine,
2094
+ context: configWithSnapshot.context,
2095
+ _nodes: snapshot._nodes,
2096
+ value: snapshot.value,
2097
+ tags: snapshot.tags,
2098
+ children: configWithSnapshot.children,
2099
+ historyValue: configWithSnapshot.historyValue || {},
2100
+ _stateInputs: configWithSnapshot._stateInputs || {},
2101
+ matches: machineSnapshotMatches,
2102
+ hasTag: machineSnapshotHasTag,
2103
+ can: machineSnapshotCan,
2104
+ getMeta: machineSnapshotGetMeta,
2105
+ getInputs: machineSnapshotGetInputs,
2106
+ toJSON: machineSnapshotToJSON
2107
+ };
2108
+ }
2109
+ return createMachineSnapshot({
2110
+ ...configWithSnapshot,
2111
+ value: undefined
2112
+ }, snapshot.machine);
2113
+ }
2114
+ function serializeHistoryValue(historyValue) {
2115
+ const result = {};
2116
+ for (const key in historyValue) {
2117
+ const value = historyValue[key];
2118
+ if (Array.isArray(value)) {
2119
+ result[key] = value.map(item => ({
2120
+ id: item.id
2121
+ }));
2122
+ }
2123
+ }
2124
+ return result;
2125
+ }
2126
+ function getPersistedSnapshot(snapshot, options) {
2127
+ const {
2128
+ _nodes: nodes,
2129
+ _stateInputs,
2130
+ tags,
2131
+ machine,
2132
+ children,
2133
+ context,
2134
+ can,
2135
+ hasTag,
2136
+ matches,
2137
+ getMeta,
2138
+ getInputs,
2139
+ toJSON,
2140
+ ...jsonValues
2141
+ } = snapshot;
2142
+ const childrenJson = {};
2143
+ for (const id in children) {
2144
+ const child = children[id];
2145
+ if (typeof child.src !== 'string' && (!options || !('__unsafeAllowInlineActors' in options))) {
2146
+ throw new Error('An inline child actor cannot be persisted.');
2147
+ }
2148
+ childrenJson[id] = {
2149
+ snapshot: child.getPersistedSnapshot(options),
2150
+ src: child.src,
2151
+ registryKey: child.registryKey,
2152
+ syncSnapshot: child._syncSnapshot
2153
+ };
2154
+ }
2155
+ const persisted = {
2156
+ ...jsonValues,
2157
+ context: persistContext(context),
2158
+ children: childrenJson,
2159
+ historyValue: serializeHistoryValue(jsonValues.historyValue)
2160
+ };
2161
+ if (machine.version !== undefined) {
2162
+ persisted.version = machine.version;
2163
+ }
2164
+ return persisted;
2165
+ }
2166
+ function persistContext(contextPart) {
2167
+ let copy;
2168
+ for (const key in contextPart) {
2169
+ const value = contextPart[key];
2170
+ if (value && typeof value === 'object') {
2171
+ if ('sessionId' in value && 'send' in value && 'ref' in value) {
2172
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2173
+ ...contextPart
2174
+ };
2175
+ copy[key] = {
2176
+ xstate$$type: $$ACTOR_TYPE,
2177
+ id: value.id
2178
+ };
2179
+ } else {
2180
+ const result = persistContext(value);
2181
+ if (result !== value) {
2182
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2183
+ ...contextPart
2184
+ };
2185
+ copy[key] = result;
2186
+ }
2187
+ }
2188
+ }
2189
+ }
2190
+ return copy ?? contextPart;
2191
+ }
2192
+
2193
+ function matchesState(parentStateId, childStateId) {
2194
+ const parentStateValue = toStateValue(parentStateId);
2195
+ const childStateValue = toStateValue(childStateId);
2196
+ if (typeof childStateValue === 'string') {
2197
+ if (typeof parentStateValue === 'string') {
2198
+ return childStateValue === parentStateValue;
2199
+ }
2200
+
2201
+ // Parent more specific than child
2202
+ return false;
2203
+ }
2204
+ if (typeof parentStateValue === 'string') {
2205
+ return parentStateValue in childStateValue;
2206
+ }
2207
+ return Object.keys(parentStateValue).every(key => {
2208
+ if (!(key in childStateValue)) {
2209
+ return false;
2210
+ }
2211
+ return matchesState(parentStateValue[key], childStateValue[key]);
2212
+ });
2213
+ }
2214
+ function checkStateIn(snapshot, stateValue) {
2215
+ if (typeof stateValue === 'string' && isStateId(stateValue)) {
2216
+ const target = snapshot.machine.getStateNodeById(stateValue);
2217
+ return snapshot._nodes.some(sn => sn === target);
2218
+ }
2219
+ return snapshot.matches(stateValue);
2220
+ }
2221
+ function toStatePath(stateId) {
2222
+ if (isArray(stateId)) {
2223
+ return stateId;
2224
+ }
2225
+ const result = [];
2226
+ let segment = '';
2227
+ for (let i = 0; i < stateId.length; i++) {
2228
+ const char = stateId.charCodeAt(i);
2229
+ switch (char) {
2230
+ // \
2231
+ case 92:
2232
+ // consume the next character
2233
+ segment += stateId[i + 1];
2234
+ // and skip over it
2235
+ i++;
2236
+ continue;
2237
+ // .
2238
+ case 46:
2239
+ result.push(segment);
2240
+ segment = '';
2241
+ continue;
2242
+ }
2243
+ segment += stateId[i];
2244
+ }
2245
+ result.push(segment);
2246
+ return result;
2247
+ }
2248
+ function toStateValue(stateValue) {
2249
+ if (isMachineSnapshot(stateValue)) {
2250
+ return stateValue.value;
2251
+ }
2252
+ if (typeof stateValue !== 'string') {
2253
+ return stateValue;
2254
+ }
2255
+ const statePath = toStatePath(stateValue);
2256
+ return pathToStateValue(statePath);
2257
+ }
2258
+ function pathToStateValue(statePath) {
2259
+ if (statePath.length === 1) {
2260
+ return statePath[0];
2261
+ }
2262
+ const value = {};
2263
+ let marker = value;
2264
+ for (let i = 0; i < statePath.length - 1; i++) {
2265
+ if (i === statePath.length - 2) {
2266
+ marker[statePath[i]] = statePath[i + 1];
2267
+ } else {
2268
+ const previous = marker;
2269
+ marker = {};
2270
+ previous[statePath[i]] = marker;
2271
+ }
2272
+ }
2273
+ return value;
2274
+ }
2275
+ function mapValues(collection, iteratee) {
2276
+ const result = {};
2277
+ const collectionKeys = Object.keys(collection);
2278
+ for (let i = 0; i < collectionKeys.length; i++) {
2279
+ const key = collectionKeys[i];
2280
+ result[key] = iteratee(collection[key], key, collection, i);
2281
+ }
2282
+ return result;
2283
+ }
2284
+ function toArrayStrict(value) {
2285
+ if (isArray(value)) {
2286
+ return value;
2287
+ }
2288
+ return [value];
2289
+ }
2290
+ function toArray(value) {
2291
+ if (value === undefined) {
2292
+ return [];
2293
+ }
2294
+ return toArrayStrict(value);
2295
+ }
2296
+ function resolveOutput(mapper, context, event, self) {
2297
+ if (typeof mapper === 'function') {
2298
+ const outputMapper = mapper;
2299
+ const args = {
2300
+ context,
2301
+ event,
2302
+ output: getEventOutput(event),
2303
+ self
2304
+ };
2305
+ return outputMapper(args);
2306
+ }
2307
+ if (!!mapper && typeof mapper === 'object' && Object.values(mapper).some(val => typeof val === 'function')) {
2308
+ 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(([, value]) => typeof value === 'function').map(([key, value]) => `\n - ${key}: ${value.toString().replace(/\n\s*/g, '')}`).join('')}`);
2309
+ }
2310
+ return mapper;
2311
+ }
2312
+ function getEventOutput(event) {
2313
+ if (isDoneEvent(event)) {
2314
+ const doneEvent = event;
2315
+ return doneEvent.output;
2316
+ }
2317
+ return undefined;
2318
+ }
2319
+ function isDoneEvent(event) {
2320
+ return event.type.startsWith('xstate.done.actor.') || event.type.startsWith('xstate.done.state.');
2321
+ }
2322
+ function isArray(value) {
2323
+ return Array.isArray(value);
2324
+ }
2325
+ function isErrorActorEvent(event) {
2326
+ return event.type.startsWith('xstate.error.actor');
2327
+ }
2328
+ function toTransitionConfigArray(configLike) {
2329
+ return toArrayStrict(configLike).map(transitionLike => {
2330
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
2331
+ return {
2332
+ target: transitionLike
2333
+ };
2334
+ }
2335
+ if (typeof transitionLike === 'function') {
2336
+ return {
2337
+ to: transitionLike
2338
+ };
2339
+ }
2340
+ return transitionLike;
2341
+ });
2342
+ }
2343
+ function normalizeTarget(target) {
2344
+ if (target === undefined || target === TARGETLESS_KEY) {
2345
+ return undefined;
2346
+ }
2347
+ return toArray(target);
2348
+ }
2349
+ function toObserver(nextHandler, errorHandler, completionHandler) {
2350
+ const isObserver = typeof nextHandler === 'object';
2351
+ const self = isObserver ? nextHandler : undefined;
2352
+ return {
2353
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
2354
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
2355
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
2356
+ };
2357
+ }
2358
+ function createInvokeId(stateNodeId, index) {
2359
+ return `${index}.${stateNodeId}`;
2360
+ }
2361
+ function resolveReferencedActor(machine, src) {
2362
+ const match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
2363
+ if (!match) {
2364
+ return machine.implementations.actorSources[src];
2365
+ }
2366
+ const [, indexStr, nodeId] = match;
2367
+ const node = machine.getStateNodeById(nodeId);
2368
+ const invokeConfig = node.config.invoke;
2369
+ const configSrc = (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
2370
+ // A referenced actor may itself be registered by name.
2371
+ return typeof configSrc === 'string' ? machine.implementations.actorSources[configSrc] : configSrc;
2372
+ }
2373
+ function getAllOwnEventDescriptors(snapshot) {
2374
+ return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];
2375
+ }
2376
+
2377
+ /**
2378
+ * Checks if an event type matches an event descriptor, supporting wildcards.
2379
+ * Event descriptors can be:
2380
+ *
2381
+ * - Exact matches: "event.type"
2382
+ * - Wildcard: "*"
2383
+ * - Partial matches: "event.*"
2384
+ *
2385
+ * @param eventType - The actual event type string
2386
+ * @param descriptor - The event descriptor to match against
2387
+ * @returns True if the event type matches the descriptor
2388
+ */
2389
+ function matchesEventDescriptor(eventType, descriptor) {
2390
+ if (descriptor === eventType) {
2391
+ return true;
2392
+ }
2393
+ if (descriptor === WILDCARD) {
2394
+ return true;
2395
+ }
2396
+ if (!descriptor.endsWith('.*')) {
2397
+ return false;
2398
+ }
2399
+ if (/.*\*.+/.test(descriptor)) {
2400
+ 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.`);
2401
+ }
2402
+ const partialEventTokens = descriptor.split('.');
2403
+ const eventTokens = eventType.split('.');
2404
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
2405
+ const partialEventToken = partialEventTokens[tokenIndex];
2406
+ const eventToken = eventTokens[tokenIndex];
2407
+ if (partialEventToken === '*') {
2408
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
2409
+ if (!isLastToken) {
2410
+ console.warn(`Infix wildcards in transition events are not allowed. Check the "${descriptor}" transition.`);
2411
+ }
2412
+ return isLastToken;
2413
+ }
2414
+ if (partialEventToken !== eventToken) {
2415
+ return false;
2416
+ }
2417
+ }
2418
+ return true;
2419
+ }
2420
+
2421
+ function createScheduledEventId(actor, id) {
2422
+ return `${actor.sessionId}.${id}`;
2423
+ }
2424
+ function createRuntimeSystem(rootActor, options) {
2425
+ let idCounter = 0;
2426
+ const children = new Map();
2427
+ const keyedActors = new Map();
2428
+ const reverseKeyedActors = new WeakMap();
2429
+ const inspectionObservers = new Set();
2430
+ const timerMap = {};
2431
+ const {
2432
+ clock,
2433
+ logger
2434
+ } = options;
2435
+
2436
+ // Records a send on the *sender's* transition for the `sent[]` inspection
2437
+ // facet. Captures the send when it is initiated (including delayed sends that
2438
+ // may never deliver), keyed to the source actor's in-flight transition.
2439
+ const recordSent = (source, target, event, delay, id) => {
2440
+ if (!inspectionObservers.size || !source) {
2441
+ return;
2442
+ }
2443
+ const collected = source._collectedSent ??= [];
2444
+ collected.push({
2445
+ targetRef: target,
2446
+ targetId: target.id,
2447
+ event,
2448
+ delay,
2449
+ id
2450
+ });
2451
+ };
2452
+ const scheduler = {
2453
+ schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {
2454
+ recordSent(source, target, event, delay, id);
2455
+ const scheduledEvent = {
2456
+ source,
2457
+ target,
2458
+ event,
2459
+ delay,
2460
+ id,
2461
+ startedAt: Date.now()
2462
+ };
2463
+ const scheduledEventId = createScheduledEventId(source, id);
2464
+ system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
2465
+ const timeout = clock.setTimeout(() => {
2466
+ delete timerMap[scheduledEventId];
2467
+ delete system._snapshot._scheduledEvents[scheduledEventId];
2468
+
2469
+ // The send was already recorded at schedule time on the sender's
2470
+ // transition, so deliver without re-recording.
2471
+ deliver(source, target, event);
2472
+ }, delay);
2473
+ timerMap[scheduledEventId] = timeout;
2474
+ },
2475
+ cancel: (source, id) => {
2476
+ const scheduledEventId = createScheduledEventId(source, id);
2477
+ const timeout = timerMap[scheduledEventId];
2478
+ delete timerMap[scheduledEventId];
2479
+ delete system._snapshot._scheduledEvents[scheduledEventId];
2480
+ if (timeout !== undefined) {
2481
+ clock.clearTimeout(timeout);
2482
+ }
2483
+ },
2484
+ cancelAll: actor => {
2485
+ for (const scheduledEventId in system._snapshot._scheduledEvents) {
2486
+ const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
2487
+ if (scheduledEvent.source === actor) {
2488
+ scheduler.cancel(actor, scheduledEvent.id);
2489
+ }
2490
+ }
2491
+ }
2492
+ };
2493
+ // Delivers an event to the target actor. Used by both `_relay` (which also
2494
+ // records the send) and the scheduler's timer (which already recorded it).
2495
+ const deliver = (source, target, event) => {
2496
+ const targetMachine = target.logic;
2497
+ const isInternalEvent = typeof targetMachine?.isInternalEventType === 'function' && targetMachine.isInternalEventType(event.type);
2498
+ if (isInternalEvent && source !== target) {
2499
+ throw new Error(`Internal event "${event.type}" cannot be sent to actor "${target.id}" from outside.`);
2500
+ }
2501
+
2502
+ // remember the last source for unified transition inspect event
2503
+ target._lastSourceRef = source;
2504
+ target._send(event);
2505
+ };
2506
+ const sendInspectionEvent = event => {
2507
+ if (!inspectionObservers.size) {
2508
+ return;
2509
+ }
2510
+ const resolvedInspectionEvent = {
2511
+ ...event,
2512
+ rootId: rootActor.sessionId
2513
+ };
2514
+ inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));
2515
+ };
2516
+ const system = {
2517
+ children,
2518
+ reverseKeyedActors,
2519
+ keyedActors,
2520
+ _snapshot: {
2521
+ _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}
2522
+ },
2523
+ _bookId: () => `x:${idCounter++}`,
2524
+ _register: (sessionId, actor) => {
2525
+ children.set(sessionId, actor);
2526
+ return sessionId;
2527
+ },
2528
+ _unregister: actor => {
2529
+ children.delete(actor.sessionId);
2530
+ const registryKey = reverseKeyedActors.get(actor);
2531
+ if (registryKey !== undefined) {
2532
+ keyedActors.delete(registryKey);
2533
+ reverseKeyedActors.delete(actor);
2534
+ }
2535
+ },
2536
+ get: registryKey => {
2537
+ return keyedActors.get(registryKey);
2538
+ },
2539
+ getAll: () => {
2540
+ return Object.fromEntries(keyedActors.entries());
2541
+ },
2542
+ _set: (registryKey, actor) => {
2543
+ const existing = keyedActors.get(registryKey);
2544
+ if (existing && existing !== actor) {
2545
+ throw new Error(`Actor with registry key '${registryKey}' already exists.`);
2546
+ }
2547
+ keyedActors.set(registryKey, actor);
2548
+ reverseKeyedActors.set(actor, registryKey);
2549
+ },
2550
+ inspect: observerOrFn => {
2551
+ const observer = toObserver(observerOrFn);
2552
+ inspectionObservers.add(observer);
2553
+ return {
2554
+ unsubscribe() {
2555
+ inspectionObservers.delete(observer);
2556
+ }
2557
+ };
2558
+ },
2559
+ _sendInspectionEvent: sendInspectionEvent,
2560
+ _relay: (source, target, event) => {
2561
+ recordSent(source, target, event);
2562
+ deliver(source, target, event);
2563
+ },
2564
+ scheduler,
2565
+ getSnapshot: () => {
2566
+ return {
2567
+ _scheduledEvents: {
2568
+ ...system._snapshot._scheduledEvents
2569
+ }
2570
+ };
2571
+ },
2572
+ start: () => {
2573
+ const scheduledEvents = system._snapshot._scheduledEvents;
2574
+ system._snapshot._scheduledEvents = {};
2575
+ for (const scheduledId in scheduledEvents) {
2576
+ const {
2577
+ source,
2578
+ target,
2579
+ event,
2580
+ delay,
2581
+ id
2582
+ } = scheduledEvents[scheduledId];
2583
+ scheduler.schedule(source, target, event, delay, id);
2584
+ }
2585
+ },
2586
+ _clock: clock,
2587
+ _logger: logger,
2588
+ _timerStrategy: options.timers
2589
+ };
2590
+ return system;
2591
+ }
2592
+
2593
+ const effectStates = new WeakMap();
2594
+ const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';
2595
+ const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';
2596
+ const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';
2597
+ function getEffectState(self) {
2598
+ let state = effectStates.get(self);
2599
+ if (!state) {
2600
+ state = new Map();
2601
+ effectStates.set(self, state);
2602
+ }
2603
+ return state;
2604
+ }
2605
+ function executeLogicEffects(effects, actorScope) {
2606
+ if (!effects?.length) {
2607
+ return;
2608
+ }
2609
+ for (const effect of effects) {
2610
+ switch (effect.type) {
2611
+ case 'emit':
2612
+ actorScope.emit(effect.event);
2613
+ break;
2614
+ case 'sendBack':
2615
+ {
2616
+ const parent = actorScope.self._parent;
2617
+ if (parent) {
2618
+ actorScope.system._relay(actorScope.self, parent, effect.event);
2619
+ }
2620
+ break;
2621
+ }
2622
+ case 'raise':
2623
+ actorScope.system._relay(actorScope.self, actorScope.self, effect.event);
2624
+ break;
2625
+ case 'effect':
2626
+ {
2627
+ if (!effect.key) {
2628
+ const cleanup = effect.exec();
2629
+ if (typeof cleanup === 'function') {
2630
+ getEffectState(actorScope.self).set(Symbol(), {
2631
+ cleanup
2632
+ });
2633
+ }
2634
+ break;
2635
+ }
2636
+ const state = getEffectState(actorScope.self);
2637
+ if (state.has(effect.key)) {
2638
+ break;
2639
+ }
2640
+ const cleanup = effect.exec();
2641
+ state.set(effect.key, {
2642
+ cleanup: typeof cleanup === 'function' ? cleanup : undefined
2643
+ });
2644
+ break;
2645
+ }
2646
+ case 'cleanupEffects':
2647
+ {
2648
+ const state = effectStates.get(actorScope.self);
2649
+ if (!state) {
2650
+ break;
2651
+ }
2652
+ for (const {
2653
+ cleanup
2654
+ } of state.values()) {
2655
+ cleanup?.();
2656
+ }
2657
+ effectStates.delete(actorScope.self);
2658
+ break;
2659
+ }
2660
+ }
2661
+ }
2662
+ }
2663
+ function resolveContext(context, input) {
2664
+ return typeof context === 'function' ? context({
2665
+ input
2666
+ }) : context;
2667
+ }
2668
+ function createLogic(config) {
2669
+ const transition = (snapshot, event, actorScope) => {
2670
+ if (snapshot.status !== 'active') {
2671
+ return [snapshot, []];
2672
+ }
2673
+ if (event.type === XSTATE_STOP) {
2674
+ return [{
2675
+ ...snapshot,
2676
+ status: 'stopped',
2677
+ input: undefined
2678
+ }, [{
2679
+ type: 'cleanupEffects'
2680
+ }]];
2681
+ }
2682
+ if (event.type === XSTATE_LOGIC_EFFECT_START) {
2683
+ return [{
2684
+ ...snapshot,
2685
+ effects: {
2686
+ ...snapshot.effects,
2687
+ [event.key]: {
2688
+ status: 'active'
2689
+ }
2690
+ }
2691
+ }, []];
2692
+ }
2693
+ if (event.type === XSTATE_LOGIC_EFFECT_RESOLVE) {
2694
+ return [{
2695
+ ...snapshot,
2696
+ effects: {
2697
+ ...snapshot.effects,
2698
+ [event.key]: {
2699
+ status: 'done',
2700
+ output: event.output
2701
+ }
2702
+ }
2703
+ }, []];
2704
+ }
2705
+ if (event.type === XSTATE_LOGIC_EFFECT_REJECT) {
2706
+ return [{
2707
+ ...snapshot,
2708
+ effects: {
2709
+ ...snapshot.effects,
2710
+ [event.key]: {
2711
+ status: 'error',
2712
+ error: event.error
2713
+ }
2714
+ }
2715
+ }, []];
2716
+ }
2717
+ const effects = [];
2718
+ const trackedEffects = {};
2719
+ const enqueueEffect = (key, exec) => {
2720
+ if (snapshot.effects?.[key]) {
2721
+ return;
2722
+ }
2723
+ effects.push({
2724
+ type: 'effect',
2725
+ key,
2726
+ exec
2727
+ });
2728
+ trackedEffects[key] = {
2729
+ status: 'active'
2730
+ };
2731
+ };
2732
+ const enq = {
2733
+ emit: emitted => {
2734
+ effects.push({
2735
+ type: 'emit',
2736
+ event: emitted
2737
+ });
2738
+ },
2739
+ sendBack: sentEvent => {
2740
+ effects.push({
2741
+ type: 'sendBack',
2742
+ event: sentEvent
2743
+ });
2744
+ },
2745
+ raise: raisedEvent => {
2746
+ effects.push({
2747
+ type: 'raise',
2748
+ event: raisedEvent
2749
+ });
2750
+ },
2751
+ effect: (keyOrExec, maybeExec) => {
2752
+ if (typeof keyOrExec === 'string') {
2753
+ enqueueEffect(keyOrExec, maybeExec);
2754
+ return;
2755
+ }
2756
+ effects.push({
2757
+ type: 'effect',
2758
+ exec: keyOrExec
2759
+ });
2760
+ }
2761
+ };
2762
+ const patch = config.run({
2763
+ context: snapshot.context,
2764
+ event,
2765
+ input: snapshot.input,
2766
+ system: actorScope.system,
2767
+ self: actorScope.self,
2768
+ emit: actorScope.emit
2769
+ }, enq);
2770
+ const nextSnapshot = {
2771
+ ...snapshot,
2772
+ ...(patch || {})
2773
+ };
2774
+ if ('context' in snapshot || patch?.context !== undefined) {
2775
+ nextSnapshot.context = patch?.context ?? snapshot.context;
2776
+ }
2777
+ if (patch?.effects || Object.keys(trackedEffects).length) {
2778
+ nextSnapshot.effects = {
2779
+ ...snapshot.effects,
2780
+ ...patch?.effects,
2781
+ ...trackedEffects
2782
+ };
2783
+ }
2784
+ return [nextSnapshot, effects];
2785
+ };
2786
+ const logic = {
2787
+ id: config.id,
2788
+ config,
2789
+ transition,
2790
+ start: (snapshot, actorScope) => {
2791
+ const [nextSnapshot, effects] = transition(snapshot, createInitEvent(snapshot.input), actorScope);
2792
+ Object.assign(snapshot, nextSnapshot);
2793
+ executeLogicEffects(effects, actorScope);
2794
+ },
2795
+ initialTransition: (input, _) => {
2796
+ const context = resolveContext(config.context, input);
2797
+ const snapshot = {
2798
+ status: 'active',
2799
+ output: undefined,
2800
+ error: undefined,
2801
+ input
2802
+ };
2803
+ if (context !== undefined) {
2804
+ snapshot.context = context;
2805
+ }
2806
+ return [{
2807
+ ...snapshot
2808
+ }, []];
2809
+ },
2810
+ getInitialSnapshot: (actorScope, input) => logic.initialTransition(input, actorScope)[0],
2811
+ getPersistedSnapshot: snapshot => snapshot,
2812
+ restoreSnapshot: snapshot => snapshot
2813
+ };
2814
+ return logic;
2815
+ }
2816
+
2817
+ // those are needed to make JSDoc `@link` work properly
2818
+
2819
+ let executingCustomAction = false;
2820
+ const $$ACTOR_TYPE = 1;
2821
+
2822
+ // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
2823
+ let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
2824
+ ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
2825
+ ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
2826
+ ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
2827
+ return ProcessingStatus;
2828
+ }({});
2829
+ const defaultOptions = {
2830
+ clock: {
2831
+ setTimeout: (fn, ms) => {
2832
+ return setTimeout(fn, ms);
2833
+ },
2834
+ clearTimeout: id => {
2835
+ return clearTimeout(id);
2836
+ }
2837
+ },
2838
+ logger: console.log.bind(console)
2839
+ };
2840
+ function isExecutableActionObject(effect) {
2841
+ return typeof effect === 'object' && effect !== null && 'args' in effect && 'exec' in effect;
2842
+ }
2843
+ function executeExecutableEffects(effects, actorScope) {
2844
+ if (!effects?.length) {
2845
+ return [];
2846
+ }
2847
+ const logicEffects = [];
2848
+ for (const effect of effects) {
2849
+ if (isExecutableActionObject(effect)) {
2850
+ actorScope.actionExecutor(effect);
2851
+ } else {
2852
+ logicEffects.push(effect);
2853
+ }
2854
+ }
2855
+ return logicEffects;
2856
+ }
2857
+
2858
+ /**
2859
+ * An Actor is a running process that can receive events, send events and change
2860
+ * its behavior based on the events it receives, which can cause effects outside
2861
+ * of the actor. When you run a state machine, it becomes an actor.
2862
+ *
2863
+ * An `Actor` is the concrete runtime instance with lifecycle methods and
2864
+ * system-owned internals. It also satisfies the narrower `ActorRef` contract,
2865
+ * so consumer APIs should accept `ActorRef` when they only need to send events
2866
+ * or read snapshots.
2867
+ */
2868
+ class Actor {
2869
+ /**
2870
+ * Creates a new actor instance for the given logic with the provided options,
2871
+ * if any.
2872
+ *
2873
+ * @param logic The logic to create an actor from
2874
+ * @param options Actor options
2875
+ */
2876
+ constructor(logic, options) {
2877
+ this.logic = logic;
2878
+ /** The current internal state of the actor. */
2879
+ this._snapshot = void 0;
2880
+ /**
2881
+ * The clock that is responsible for setting and clearing timeouts, such as
2882
+ * delayed events and transitions.
2883
+ */
2884
+ this.clock = void 0;
2885
+ this.options = void 0;
2886
+ /** The unique identifier for this actor relative to its parent. */
2887
+ this.id = void 0;
2888
+ this._boundProcess = this._process.bind(this);
2889
+ this.mailbox = new Mailbox(this._boundProcess);
2890
+ this.observers = new Set();
2891
+ this.eventListeners = new Map();
2892
+ this.logger = void 0;
2893
+ /** @internal */
2894
+ this._processingStatus = ProcessingStatus.NotStarted;
2895
+ this._forceDeferredActions = false;
2896
+ // Actor Ref
2897
+ this._parent = void 0;
2898
+ /** @internal */
2899
+ this._syncSnapshot = void 0;
2900
+ this.ref = void 0;
2901
+ // TODO: add typings for system
2902
+ this._actorScope = void 0;
2903
+ /** @internal */
2904
+ this._lastSourceRef = void 0;
2905
+ /** @internal */
2906
+ this._collectedMicrosteps = [];
2907
+ /** @internal Actions executed during the in-flight transition. */
2908
+ this._collectedActions = [];
2909
+ /** @internal Events relayed to other actors during the in-flight transition. */
2910
+ this._collectedSent = [];
2911
+ this._initialEffects = void 0;
2912
+ this.registryKey = void 0;
2913
+ /** The globally unique process ID for this invocation. */
2914
+ this.sessionId = void 0;
2915
+ /** The system to which this actor belongs. */
2916
+ this.system = void 0;
2917
+ this.trigger = void 0;
2918
+ this.src = void 0;
2919
+ // array of functions to defer
2920
+ this._deferred = [];
2921
+ // pending effects (timers) from a persisted snapshot, rescheduled on `start()`
2922
+ this._pendingEffects = void 0;
2923
+ const resolvedOptions = {
2924
+ ...defaultOptions,
2925
+ ...options
2926
+ };
2927
+ const {
2928
+ clock,
2929
+ logger,
2930
+ parent,
2931
+ syncSnapshot,
2932
+ id,
2933
+ registryKey,
2934
+ inspect
2935
+ } = resolvedOptions;
2936
+ this.system = parent ? parent.system : resolvedOptions._systemRef?.current ?? createRuntimeSystem(this, {
2937
+ clock,
2938
+ logger,
2939
+ timers: resolvedOptions.timers
2940
+ });
2941
+ if (!parent && resolvedOptions._systemRef && !resolvedOptions._systemRef.current) {
2942
+ resolvedOptions._systemRef.current = this.system;
2943
+ }
2944
+ if (inspect && !parent) {
2945
+ // Always inspect at the system-level
2946
+ this.system.inspect(toObserver(inspect));
2947
+ }
2948
+ this.sessionId = this.system._bookId();
2949
+ this.id = id ?? this.sessionId;
2950
+ this.logger = options?.logger ?? this.system._logger;
2951
+ this.clock = options?.clock ?? this.system._clock;
2952
+ this._parent = parent;
2953
+ this._syncSnapshot = syncSnapshot;
2954
+ this.options = resolvedOptions;
2955
+ this.src = resolvedOptions.src ?? logic;
2956
+ this.ref = this;
2957
+ this._actorScope = {
2958
+ self: this,
2959
+ id: this.id,
2960
+ sessionId: this.sessionId,
2961
+ logger: this.logger,
2962
+ defer: fn => {
2963
+ this._deferred.push(fn);
2964
+ },
2965
+ system: this.system,
2966
+ stopChild: child => {
2967
+ if (child._parent !== this) {
2968
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
2969
+ }
2970
+ child._stop();
2971
+ },
2972
+ emit: emittedEvent => {
2973
+ const listeners = this.eventListeners.get(emittedEvent.type);
2974
+ const wildcardListener = this.eventListeners.get('*');
2975
+ if (!listeners && !wildcardListener) {
2976
+ return;
2977
+ }
2978
+ if (listeners) {
2979
+ for (const handler of listeners) {
2980
+ try {
2981
+ handler(emittedEvent);
2982
+ } catch (err) {
2983
+ reportUnhandledError(err);
2984
+ }
2985
+ }
2986
+ }
2987
+ if (!wildcardListener) {
2988
+ return;
2989
+ }
2990
+ for (const handler of wildcardListener) {
2991
+ try {
2992
+ handler(emittedEvent);
2993
+ } catch (err) {
2994
+ reportUnhandledError(err);
2995
+ }
2996
+ }
2997
+ },
2998
+ actionExecutor: action => {
2999
+ const exec = () => {
3000
+ // Record every executed action for the '@xstate.transition' inspection
3001
+ // event's `actions[]` facet (replaces the v5 '@xstate.action' event).
3002
+ this._collectedActions.push({
3003
+ type: action.type,
3004
+ params: action.params
3005
+ });
3006
+ if (!action.exec) {
3007
+ return;
3008
+ }
3009
+ const saveExecutingCustomAction = executingCustomAction;
3010
+ try {
3011
+ executingCustomAction = true;
3012
+ action.exec();
3013
+ } finally {
3014
+ executingCustomAction = saveExecutingCustomAction;
3015
+ }
3016
+ };
3017
+ if (this._processingStatus === ProcessingStatus.Running && !this._forceDeferredActions) {
3018
+ exec();
3019
+ } else {
3020
+ this._deferred.push(exec);
3021
+ }
3022
+ }
3023
+ };
3024
+
3025
+ // Ensure that the send method is bound to this Actor instance
3026
+ // if destructured
3027
+ this.send = this.send.bind(this);
3028
+ this.trigger = new Proxy({}, {
3029
+ get: (_, eventType) => {
3030
+ return payload => {
3031
+ this.send({
3032
+ ...payload,
3033
+ type: eventType
3034
+ });
3035
+ };
3036
+ }
3037
+ });
3038
+
3039
+ // unified '@xstate.transition' event replaces '@xstate.actor'
3040
+
3041
+ const resolvedRegistryKey = registryKey;
3042
+ if (resolvedRegistryKey) {
3043
+ this.registryKey = resolvedRegistryKey;
3044
+ this.system._set(resolvedRegistryKey, this);
3045
+ }
3046
+
3047
+ // prepare to collect initial microsteps during initialTransition
3048
+ this._collectedMicrosteps = [];
3049
+ let persistedState = options?.snapshot ?? options?.state;
3050
+ if (persistedState && typeof persistedState === 'object' && '_pendingEffects' in persistedState) {
3051
+ // Pending effects are restored by this actor on `start()`; the logic
3052
+ // only sees the rest of the persisted snapshot.
3053
+ const {
3054
+ _pendingEffects,
3055
+ ...rest
3056
+ } = persistedState;
3057
+ this._pendingEffects = _pendingEffects;
3058
+ persistedState = rest;
3059
+ }
3060
+ try {
3061
+ if (persistedState) {
3062
+ this._snapshot = this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState;
3063
+ } else {
3064
+ const [snapshot, effects] = this.logic.initialTransition(this.options?.input, this._actorScope);
3065
+ this._snapshot = snapshot;
3066
+ this._initialEffects = effects;
3067
+ }
3068
+ } catch (err) {
3069
+ // if we get here then it means that we assign a value to this._snapshot that is not of the correct type
3070
+ // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible
3071
+ // so right now this is a lie of sorts
3072
+ this._snapshot = {
3073
+ status: 'error',
3074
+ output: undefined,
3075
+ error: err
3076
+ };
3077
+ // discard any functions deferred during the failed initial snapshot
3078
+ // computation so they can't run against an inconsistent actor
3079
+ this._deferred.length = 0;
3080
+ }
3081
+ if (resolvedRegistryKey && this._snapshot.status !== 'active') {
3082
+ this.system._unregister(this);
3083
+ }
3084
+
3085
+ // Announce actor topology: emitted once for every actor (root and every
3086
+ // spawned/invoked child) so the actor graph can be drawn before any
3087
+ // transitions occur. This is the only place actor identity is announced.
3088
+ this.system._sendInspectionEvent({
3089
+ type: '@xstate.actor',
3090
+ actorRef: this,
3091
+ parentRef: this._parent,
3092
+ id: this.id,
3093
+ src: this.src,
3094
+ snapshot: this._snapshot
3095
+ });
3096
+ }
3097
+ _setErrorSnapshot(err, snapshot = this._snapshot) {
3098
+ this._snapshot = {
3099
+ ...snapshot,
3100
+ status: 'error',
3101
+ error: err
3102
+ };
3103
+ }
3104
+ _next(snapshot) {
3105
+ for (const observer of this.observers) {
3106
+ try {
3107
+ observer.next?.(snapshot);
3108
+ } catch (err) {
3109
+ reportUnhandledError(err);
3110
+ }
3111
+ }
3112
+ }
3113
+ update(snapshot, event) {
3114
+ // Update state
3115
+ this._snapshot = snapshot;
3116
+
3117
+ // Execute deferred effects
3118
+ for (let i = 0; i < this._deferred.length; i++) {
3119
+ const deferredFn = this._deferred[i];
3120
+ try {
3121
+ deferredFn();
3122
+ } catch (err) {
3123
+ // this error can only be caught when executing *initial* actions
3124
+ // it's the only time when we call actions provided by the user through those deferreds
3125
+ // when the actor is already running we always execute them synchronously while transitioning
3126
+ // no "builtin deferred" should actually throw an error since they are either safe
3127
+ // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox
3128
+ this._deferred.length = 0;
3129
+ this._setErrorSnapshot(err, snapshot);
3130
+ break;
3131
+ }
3132
+ }
3133
+ this._deferred.length = 0;
3134
+ switch (this._snapshot.status) {
3135
+ case 'active':
3136
+ this._next(snapshot);
3137
+ break;
3138
+ case 'done':
3139
+ {
3140
+ // next observers are meant to be notified about done snapshots
3141
+ // this can be seen as something that is different from how observable work
3142
+ // but with observables `complete` callback is called without any arguments
3143
+ // it's more ergonomic for XState to treat a done snapshot as a "next" value
3144
+ // and the completion event as something that is separate,
3145
+ // something that merely follows emitting that done snapshot
3146
+ this._next(snapshot);
3147
+ this._stopProcedure();
3148
+ this._complete();
3149
+ const doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
3150
+ if (this._parent) {
3151
+ this.system._relay(this, this._parent, doneEvent);
3152
+ }
3153
+ break;
3154
+ }
3155
+ case 'error':
3156
+ this._error(this._snapshot.error);
3157
+ break;
3158
+ }
3159
+ this.system._sendInspectionEvent({
3160
+ type: '@xstate.transition',
3161
+ actorRef: this,
3162
+ event,
3163
+ sourceRef: this._lastSourceRef,
3164
+ targetRef: this,
3165
+ snapshot,
3166
+ microsteps: this._collectedMicrosteps,
3167
+ actions: this._collectedActions,
3168
+ sent: this._collectedSent,
3169
+ eventType: event.type
3170
+ });
3171
+ // reset facets after emission
3172
+ this._collectedMicrosteps = [];
3173
+ this._collectedActions = [];
3174
+ this._collectedSent = [];
3175
+ }
3176
+ _flushInitialEffects() {
3177
+ if (!this._initialEffects) {
3178
+ return true;
3179
+ }
3180
+ this._forceDeferredActions = true;
3181
+ try {
3182
+ const logicEffects = executeExecutableEffects(this._initialEffects, this._actorScope);
3183
+ executeLogicEffects(logicEffects, this._actorScope);
3184
+ this._initialEffects = undefined;
3185
+ return true;
3186
+ } catch (err) {
3187
+ this._initialEffects = undefined;
3188
+ this._deferred.length = 0;
3189
+ this._setErrorSnapshot(err);
3190
+ this._error(err);
3191
+ return false;
3192
+ } finally {
3193
+ this._forceDeferredActions = false;
3194
+ }
3195
+ }
3196
+
3197
+ /**
3198
+ * Subscribe an observer to an actor’s snapshot values.
3199
+ *
3200
+ * @remarks
3201
+ * The observer will receive the actor’s snapshot value when it is emitted.
3202
+ * The observer can be:
3203
+ *
3204
+ * - A plain function that receives the latest snapshot, or
3205
+ * - An observer object whose `.next(snapshot)` method receives the latest
3206
+ * snapshot
3207
+ *
3208
+ * @example
3209
+ *
3210
+ * ```ts
3211
+ * // Observer as a plain function
3212
+ * const subscription = actor.subscribe((snapshot) => {
3213
+ * console.log(snapshot);
3214
+ * });
3215
+ * ```
3216
+ *
3217
+ * @example
3218
+ *
3219
+ * ```ts
3220
+ * // Observer as an object
3221
+ * const subscription = actor.subscribe({
3222
+ * next(snapshot) {
3223
+ * console.log(snapshot);
3224
+ * },
3225
+ * error(err) {
3226
+ * // ...
3227
+ * },
3228
+ * complete() {
3229
+ * // ...
3230
+ * }
3231
+ * });
3232
+ * ```
3233
+ *
3234
+ * The return value of `actor.subscribe(observer)` is a subscription object
3235
+ * that has an `.unsubscribe()` method. You can call
3236
+ * `subscription.unsubscribe()` to unsubscribe the observer:
3237
+ *
3238
+ * @example
3239
+ *
3240
+ * ```ts
3241
+ * const subscription = actor.subscribe((snapshot) => {
3242
+ * // ...
3243
+ * });
3244
+ *
3245
+ * // Unsubscribe the observer
3246
+ * subscription.unsubscribe();
3247
+ * ```
3248
+ *
3249
+ * When the actor is stopped, all of its observers will automatically be
3250
+ * unsubscribed.
3251
+ *
3252
+ * @param observer - Either a plain function that receives the latest
3253
+ * snapshot, or an observer object whose `.next(snapshot)` method receives
3254
+ * the latest snapshot
3255
+ */
3256
+
3257
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
3258
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
3259
+ if (this._processingStatus !== ProcessingStatus.Stopped) {
3260
+ this.observers.add(observer);
3261
+ } else {
3262
+ switch (this._snapshot.status) {
3263
+ case 'done':
3264
+ try {
3265
+ observer.complete?.();
3266
+ } catch (err) {
3267
+ reportUnhandledError(err);
3268
+ }
3269
+ break;
3270
+ case 'error':
3271
+ {
3272
+ const err = this._snapshot.error;
3273
+ if (!observer.error) {
3274
+ reportUnhandledError(err);
3275
+ } else {
3276
+ try {
3277
+ observer.error(err);
3278
+ } catch (err) {
3279
+ reportUnhandledError(err);
3280
+ }
3281
+ }
3282
+ break;
3283
+ }
3284
+ }
3285
+ }
3286
+ return {
3287
+ unsubscribe: () => {
3288
+ this.observers.delete(observer);
3289
+ }
3290
+ };
3291
+ }
3292
+ on(type, handler) {
3293
+ let listeners = this.eventListeners.get(type);
3294
+ if (!listeners) {
3295
+ listeners = new Set();
3296
+ this.eventListeners.set(type, listeners);
3297
+ }
3298
+ listeners.add(handler);
3299
+ return {
3300
+ unsubscribe: () => {
3301
+ listeners.delete(handler);
3302
+ }
3303
+ };
3304
+ }
3305
+ select(selector, equalityFn = Object.is) {
3306
+ return {
3307
+ subscribe: (observerOrFn, errorListener, completeListener) => {
3308
+ const observer = toObserver(observerOrFn, errorListener, completeListener);
3309
+ let selected = selector(this.getSnapshot());
3310
+ return this.subscribe({
3311
+ next: snapshot => {
3312
+ const next = selector(snapshot);
3313
+ if (!equalityFn(selected, next)) {
3314
+ selected = next;
3315
+ observer.next?.(next);
3316
+ }
3317
+ },
3318
+ error: observer.error,
3319
+ complete: observer.complete
3320
+ });
3321
+ },
3322
+ get: () => selector(this.getSnapshot())
3323
+ };
3324
+ }
3325
+
3326
+ /** Starts the Actor from the initial state */
3327
+ start() {
3328
+ if (this._processingStatus === ProcessingStatus.Running) {
3329
+ // Do not restart the service if it is already started
3330
+ return this;
3331
+ }
3332
+ if (this._syncSnapshot) {
3333
+ this.subscribe({
3334
+ next: snapshot => {
3335
+ if (snapshot.status === 'active') {
3336
+ this.system._relay(this, this._parent, {
3337
+ type: `xstate.snapshot.${this.id}`,
3338
+ snapshot
3339
+ });
3340
+ }
3341
+ },
3342
+ error: () => {}
3343
+ });
3344
+ }
3345
+ this.system._register(this.sessionId, this);
3346
+ if (this.registryKey) {
3347
+ this.system._set(this.registryKey, this);
3348
+ }
3349
+ this._processingStatus = ProcessingStatus.Running;
3350
+
3351
+ // TODO: this isn't correct when rehydrating
3352
+ const initEvent = createInitEvent(this.options.input);
3353
+ // remember source of init as parent for unified transition event
3354
+ this._lastSourceRef = this._parent;
3355
+ const status = this._snapshot.status;
3356
+ switch (status) {
3357
+ case 'done':
3358
+ // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
3359
+ // we still need to complete observers, flush deferreds etc
3360
+ if (!this._flushInitialEffects()) {
3361
+ return this;
3362
+ }
3363
+ this.update(this._snapshot, initEvent);
3364
+ // TODO: rethink cleanup of observers, mailbox, etc
3365
+ return this;
3366
+ case 'error':
3367
+ this._error(this._snapshot.error);
3368
+ return this;
3369
+ }
3370
+ if (!this._parent) {
3371
+ this.system.start();
3372
+ }
3373
+ if (this.logic.start) {
3374
+ try {
3375
+ this.logic.start(this._snapshot, this._actorScope);
3376
+ } catch (err) {
3377
+ this._setErrorSnapshot(err);
3378
+ this._error(err);
3379
+ return this;
3380
+ }
3381
+ }
3382
+ if (!this._flushInitialEffects()) {
3383
+ return this;
3384
+ }
3385
+
3386
+ // TODO: this notifies all subscribers but usually this is redundant
3387
+ // there is no real change happening here
3388
+ // we need to rethink if this needs to be refactored
3389
+ this.update(this._snapshot, initEvent);
3390
+ if (this._pendingEffects) {
3391
+ const strategy = this.options.timers ?? this.system._timerStrategy ?? 'resume';
3392
+ for (const effect of this._pendingEffects) {
3393
+ // Re-execute the pending effect with its remaining delay. Only
3394
+ // self-targeted raises exist today; other effect types are ignored.
3395
+ if (effect.type === '@xstate.raise') {
3396
+ this.system.scheduler.schedule(this, this, effect.event, resolveRestoredTimerDelay(strategy, effect), effect.id);
3397
+ }
3398
+ }
3399
+ this._pendingEffects = undefined;
3400
+ }
3401
+ this.mailbox.start();
3402
+ return this;
3403
+ }
3404
+ _process(event) {
3405
+ let nextState;
3406
+ let caughtError;
3407
+ try {
3408
+ nextState = this.logic.transition(this._snapshot, event, this._actorScope);
3409
+ } catch (err) {
3410
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
3411
+ caughtError = {
3412
+ err
3413
+ };
3414
+ }
3415
+ if (caughtError) {
3416
+ const {
3417
+ err
3418
+ } = caughtError;
3419
+ this._setErrorSnapshot(err);
3420
+ this._error(err);
3421
+ return;
3422
+ }
3423
+ try {
3424
+ const [snapshot, effects] = nextState;
3425
+ const logicEffects = executeExecutableEffects(effects, this._actorScope);
3426
+ this.update(snapshot, event);
3427
+ executeLogicEffects(logicEffects, this._actorScope);
3428
+ } catch (err) {
3429
+ this._setErrorSnapshot(err);
3430
+ this._error(err);
3431
+ return;
3432
+ }
3433
+ if (event.type === XSTATE_STOP) {
3434
+ this._stopProcedure();
3435
+ this._complete();
3436
+ }
3437
+ }
3438
+
3439
+ /** @internal */
3440
+ _stop() {
3441
+ if (this._processingStatus === ProcessingStatus.Stopped) {
3442
+ return this;
3443
+ }
3444
+ this.mailbox.clear();
3445
+ if (this._processingStatus === ProcessingStatus.NotStarted) {
3446
+ this._processingStatus = ProcessingStatus.Stopped;
3447
+ return this;
3448
+ }
3449
+ this.mailbox.enqueue({
3450
+ type: XSTATE_STOP
3451
+ });
3452
+ this.system._unregister(this);
3453
+ return this;
3454
+ }
3455
+
3456
+ /** Stops the Actor and unsubscribe all listeners. */
3457
+ stop() {
3458
+ if (this._parent) {
3459
+ throw new Error('A non-root actor cannot be stopped directly.');
3460
+ }
3461
+ return this._stop();
3462
+ }
3463
+ _complete() {
3464
+ for (const observer of this.observers) {
3465
+ try {
3466
+ observer.complete?.();
3467
+ } catch (err) {
3468
+ reportUnhandledError(err);
3469
+ }
3470
+ }
3471
+ this.observers.clear();
3472
+ this.eventListeners.clear();
3473
+ }
3474
+ _error(err) {
3475
+ this._stopProcedure();
3476
+ if (!this.observers.size) {
3477
+ if (!this._parent) {
3478
+ reportUnhandledError(err);
3479
+ }
3480
+ this.eventListeners.clear();
3481
+ } else {
3482
+ let reportError = false;
3483
+ for (const observer of this.observers) {
3484
+ const errorListener = observer.error;
3485
+ reportError ||= !errorListener;
3486
+ try {
3487
+ errorListener?.(err);
3488
+ } catch (err2) {
3489
+ reportUnhandledError(err2);
3490
+ }
3491
+ }
3492
+ this.observers.clear();
3493
+ this.eventListeners.clear();
3494
+ if (reportError) {
3495
+ reportUnhandledError(err);
3496
+ }
3497
+ }
3498
+ if (this._parent) {
3499
+ this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
3500
+ }
3501
+ }
3502
+ // TODO: atm children don't belong entirely to the actor so
3503
+ // in a way - it's not even super aware of them
3504
+ // so we can't stop them from here but we really should!
3505
+ // right now, they are being stopped within the machine's transition
3506
+ // but that could throw and leave us with "orphaned" active actors
3507
+ _stopProcedure() {
3508
+ if (this._processingStatus !== ProcessingStatus.Running) {
3509
+ // Actor already stopped; do nothing
3510
+ return;
3511
+ }
3512
+
3513
+ // Cancel all delayed events
3514
+ this.system.scheduler.cancelAll(this);
3515
+
3516
+ // TODO: mailbox.reset
3517
+ this.mailbox.clear();
3518
+ // TODO: after `stop` we must prepare ourselves for receiving events again
3519
+ // events sent *after* stop signal must be queued
3520
+ // it seems like this should be the common behavior for all of our consumers
3521
+ // so perhaps this should be unified somehow for all of them
3522
+ this.mailbox = new Mailbox(this._boundProcess);
3523
+ this._processingStatus = ProcessingStatus.Stopped;
3524
+ this.system._unregister(this);
3525
+ }
3526
+
3527
+ /** @internal */
3528
+ _send(event) {
3529
+ if (this._processingStatus === ProcessingStatus.Stopped) {
3530
+ // do nothing
3531
+ {
3532
+ // TODO: circular serialization issues
3533
+ // const eventString = ''; //JSON.stringify(event);
3534
+
3535
+ 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.`);
3536
+ }
3537
+ return;
3538
+ }
3539
+ this.mailbox.enqueue(event);
3540
+ }
3541
+
3542
+ /**
3543
+ * Sends an event to the running Actor to trigger a transition.
3544
+ *
3545
+ * @param event The event to send
3546
+ */
3547
+ send(event) {
3548
+ if (typeof event === 'string') {
3549
+ throw new Error(`Only event objects may be sent to actors; use .send({ type: "${event}" }) instead`);
3550
+ }
3551
+ this.system._relay(undefined, this, event);
3552
+ }
3553
+ toJSON() {
3554
+ return {
3555
+ xstate$$type: $$ACTOR_TYPE,
3556
+ id: this.id
3557
+ };
3558
+ }
3559
+
3560
+ /**
3561
+ * Obtain the internal state of the actor, which can be persisted.
3562
+ *
3563
+ * @remarks
3564
+ * The internal state can be persisted from any actor, not only machines.
3565
+ *
3566
+ * Note that the persisted state is not the same as the snapshot from
3567
+ * {@link Actor.getSnapshot}. Persisted state represents the internal state of
3568
+ * the actor, while snapshots represent the actor's last emitted value.
3569
+ *
3570
+ * Can be restored with {@link ActorOptions.state}
3571
+ * @see https://stately.ai/docs/persistence
3572
+ */
3573
+
3574
+ getPersistedSnapshot(options) {
3575
+ const persisted = this.logic.getPersistedSnapshot(this._snapshot, options);
3576
+
3577
+ // Capture this actor's pending self-targeted effects (delayed
3578
+ // events/transitions) as serialized action descriptors plus their
3579
+ // runtime progress, so they can be restored on `start()`.
3580
+ const scheduledEvents = this.system._snapshot._scheduledEvents;
3581
+ let pendingEffects;
3582
+ const now = Date.now();
3583
+ for (const key in scheduledEvents) {
3584
+ const scheduled = scheduledEvents[key];
3585
+ if (scheduled.source === this && scheduled.target === this) {
3586
+ (pendingEffects ??= []).push({
3587
+ type: '@xstate.raise',
3588
+ event: scheduled.event,
3589
+ id: scheduled.id,
3590
+ delay: scheduled.delay,
3591
+ startedAt: scheduled.startedAt,
3592
+ elapsed: Math.max(0, now - scheduled.startedAt)
3593
+ });
3594
+ }
3595
+ }
3596
+
3597
+ // If this actor was restored but not yet started, its pending effects
3598
+ // are not in the scheduler yet — carry them through as-is.
3599
+ pendingEffects ??= this._pendingEffects;
3600
+ return pendingEffects ? {
3601
+ ...persisted,
3602
+ _pendingEffects: pendingEffects
3603
+ } : persisted;
3604
+ }
3605
+ [symbolObservable]() {
3606
+ return this;
3607
+ }
3608
+
3609
+ /**
3610
+ * Read an actor’s snapshot synchronously.
3611
+ *
3612
+ * @remarks
3613
+ * The snapshot represent an actor's last emitted value.
3614
+ *
3615
+ * When an actor receives an event, its internal state may change. An actor
3616
+ * may emit a snapshot when a state transition occurs.
3617
+ *
3618
+ * Note that some actors, such as callback actors generated with
3619
+ * `createCallbackLogic`, will not emit snapshots.
3620
+ * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
3621
+ * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
3622
+ */
3623
+ getSnapshot() {
3624
+ if (!this._snapshot) {
3625
+ throw new Error(`Snapshot can't be read while the actor initializes itself`);
3626
+ }
3627
+ return this._snapshot;
3628
+ }
3629
+ }
3630
+ function resolveRestoredTimerDelay(strategy, effect) {
3631
+ if (typeof strategy === 'function') {
3632
+ return strategy(effect);
3633
+ }
3634
+ switch (strategy) {
3635
+ case 'restart':
3636
+ return effect.delay;
3637
+ case 'absolute':
3638
+ return Math.max(0, effect.startedAt + effect.delay - Date.now());
3639
+ case 'resume':
3640
+ default:
3641
+ return Math.max(0, effect.delay - effect.elapsed);
3642
+ }
3643
+ }
3644
+ /**
3645
+ * Creates a new actor instance for the given actor logic with the provided
3646
+ * options, if any.
3647
+ *
3648
+ * @remarks
3649
+ * When you create an actor from actor logic via `createActor(logic)`, you
3650
+ * implicitly create an actor system where the created actor is the root actor.
3651
+ * Any actors spawned from this root actor and its descendants are part of that
3652
+ * actor system.
3653
+ * @example
3654
+ *
3655
+ * ```ts
3656
+ * import { createActor } from 'xstate';
3657
+ * import { someActorLogic } from './someActorLogic.ts';
3658
+ *
3659
+ * // Creating the actor, which implicitly creates an actor system with itself as the root actor
3660
+ * const actor = createActor(someActorLogic);
3661
+ *
3662
+ * actor.subscribe((snapshot) => {
3663
+ * console.log(snapshot);
3664
+ * });
3665
+ *
3666
+ * // Actors must be started by calling `actor.start()`, which will also start the actor system.
3667
+ * actor.start();
3668
+ *
3669
+ * // Actors can receive events
3670
+ * actor.send({ type: 'someEvent' });
3671
+ *
3672
+ * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
3673
+ * actor.stop();
3674
+ * ```
3675
+ *
3676
+ * @param logic - The actor logic to create an actor from. For a state machine
3677
+ * actor logic creator, see {@link createMachine}. Other actor logic creators
3678
+ * include {@link createCallbackLogic}, {@link createEventObservableLogic},
3679
+ * {@link createObservableLogic}, {@link createLogic}, and
3680
+ * {@link createAsyncLogic}.
3681
+ * @param options - Actor options
3682
+ */
3683
+ function createActor(logic, options) {
3684
+ return new Actor(logic, options);
3685
+ }
3686
+
3687
+ const instanceStates = /* #__PURE__ */new WeakMap();
3688
+
3689
+ /**
3690
+ * Represents an actor created by `createCallbackLogic`.
3691
+ *
3692
+ * The type of `self` within the actor's logic.
3693
+ *
3694
+ * @example
3695
+ *
3696
+ * ```ts
3697
+ * import { createCallbackLogic, createActor } from 'xstate';
3698
+ *
3699
+ * // The events the actor receives.
3700
+ * type Event = { type: 'someEvent' };
3701
+ * // The actor's input.
3702
+ * type Input = { name: string };
3703
+ *
3704
+ * // Actor logic that logs whenever it receives an event of type `someEvent`.
3705
+ * const logic = createCallbackLogic<Event, Input>(
3706
+ * ({ self, input, receive }) => {
3707
+ * self;
3708
+ * // ^? CallbackActorRef<Event, Input>
3709
+ *
3710
+ * receive((event) => {
3711
+ * if (event.type === 'someEvent') {
3712
+ * console.log(`${input.name}: received "someEvent" event`);
3713
+ * // logs 'myActor: received "someEvent" event'
3714
+ * }
3715
+ * });
3716
+ * }
3717
+ * );
3718
+ *
3719
+ * const actor = createActor(logic, { input: { name: 'myActor' } });
3720
+ * // ^? CallbackActorRef<Event, Input>
3721
+ * ```
3722
+ *
3723
+ * @see {@link createCallbackLogic}
3724
+ */
3725
+
3726
+ /**
3727
+ * An actor logic creator which returns callback logic as defined by a callback
3728
+ * function.
3729
+ *
3730
+ * @remarks
3731
+ * Useful for subscription-based or other free-form logic that can send events
3732
+ * back to the parent actor.
3733
+ *
3734
+ * Actors created from callback logic (“callback actors”) can:
3735
+ *
3736
+ * - Receive events via the `receive` function
3737
+ * - Send events to the parent actor via the `sendBack` function
3738
+ *
3739
+ * Callback actors are a bit different from other actors in that they:
3740
+ *
3741
+ * - Do not work with `onDone`
3742
+ * - Do not produce a snapshot using `.getSnapshot()`
3743
+ * - Do not emit values when used with `.subscribe()`
3744
+ * - Can not be stopped with `.stop()`
3745
+ *
3746
+ * @example
3747
+ *
3748
+ * ```typescript
3749
+ * const callbackLogic = createCallbackLogic(({ sendBack, receive }) => {
3750
+ * let lockStatus = 'unlocked';
3751
+ *
3752
+ * const handler = (event) => {
3753
+ * if (lockStatus === 'locked') {
3754
+ * return;
3755
+ * }
3756
+ * sendBack(event);
3757
+ * };
3758
+ *
3759
+ * receive((event) => {
3760
+ * if (event.type === 'lock') {
3761
+ * lockStatus = 'locked';
3762
+ * } else if (event.type === 'unlock') {
3763
+ * lockStatus = 'unlocked';
3764
+ * }
3765
+ * });
3766
+ *
3767
+ * document.body.addEventListener('click', handler);
3768
+ *
3769
+ * return () => {
3770
+ * document.body.removeEventListener('click', handler);
3771
+ * };
3772
+ * });
3773
+ * ```
3774
+ *
3775
+ * @param callback - The callback function used to describe the callback logic
3776
+ * The callback function is passed an object with the following properties:
3777
+ *
3778
+ * - `receive` - A function that can send events back to the parent actor; the
3779
+ * listener is then called whenever events are received by the callback
3780
+ * actor
3781
+ * - `sendBack` - A function that can send events back to the parent actor
3782
+ * - `input` - Data that was provided to the callback actor
3783
+ * - `self` - The parent actor of the callback actor
3784
+ * - `system` - The actor system to which the callback actor belongs The callback
3785
+ * function can (optionally) return a cleanup function, which is called
3786
+ * when the actor is stopped.
3787
+ *
3788
+ * @returns Callback logic
3789
+ * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument
3790
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
3791
+ */
3792
+
3793
+ function createCallbackLogic(callbackOrConfig) {
3794
+ const callback = typeof callbackOrConfig === 'function' ? callbackOrConfig : callbackOrConfig.run;
3795
+ const schemas = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.schemas;
3796
+ return createLogic({
3797
+ schemas,
3798
+ context: undefined,
3799
+ run: (args, enq) => {
3800
+ const {
3801
+ event,
3802
+ input,
3803
+ self,
3804
+ system
3805
+ } = args;
3806
+ const emit = args.emit;
3807
+ const callbackState = instanceStates.get(self);
3808
+ callbackState?.receivers?.forEach(receiver => receiver(event));
3809
+ enq.effect('callback', () => {
3810
+ const callbackState = {
3811
+ receivers: undefined,
3812
+ dispose: undefined
3813
+ };
3814
+ instanceStates.set(self, callbackState);
3815
+ callbackState.dispose = callback({
3816
+ input,
3817
+ system,
3818
+ self: self,
3819
+ sendBack: event => {
3820
+ if (self.getSnapshot().status === 'stopped') {
3821
+ return;
3822
+ }
3823
+ const parent = self._parent;
3824
+ if (parent) {
3825
+ system._relay(self, parent, event);
3826
+ }
3827
+ },
3828
+ receive: listener => {
3829
+ callbackState.receivers ??= new Set();
3830
+ callbackState.receivers.add(listener);
3831
+ },
3832
+ emit: emit
3833
+ });
3834
+ return () => {
3835
+ instanceStates.delete(self);
3836
+ callbackState.receivers?.clear();
3837
+ callbackState.dispose?.();
3838
+ };
3839
+ });
3840
+ }
3841
+ });
3842
+ }
3843
+
3844
+ const XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';
3845
+ const XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';
3846
+ const XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';
3847
+
3848
+ /**
3849
+ * Represents an actor created by `createObservableLogic` or
3850
+ * `createEventObservableLogic`.
3851
+ *
3852
+ * The type of `self` within the actor's logic.
3853
+ *
3854
+ * @example
3855
+ *
3856
+ * ```ts
3857
+ * import { createObservableLogic, createActor } from 'xstate';
3858
+ * import { interval } from 'rxjs';
3859
+ *
3860
+ * // The type of the value observed by the actor's logic.
3861
+ * type Context = number;
3862
+ * // The actor's input.
3863
+ * type Input = { period?: number };
3864
+ *
3865
+ * // Actor logic that observes a number incremented every `input.period`
3866
+ * // milliseconds (default: 1_000).
3867
+ * const logic = createObservableLogic<Context, Input>(
3868
+ * ({ input, self }) => {
3869
+ * self;
3870
+ * // ^? ObservableActor<Event, Input>
3871
+ *
3872
+ * return interval(input.period ?? 1_000);
3873
+ * }
3874
+ * );
3875
+ *
3876
+ * const actor = createActor(logic, { input: { period: 2_000 } });
3877
+ * // ^? ObservableActor<Event, Input>
3878
+ * ```
3879
+ *
3880
+ * @see {@link createObservableLogic}
3881
+ * @see {@link createEventObservableLogic}
3882
+ */
3883
+
3884
+ /**
3885
+ * Observable actor logic is described by an observable stream of values. Actors
3886
+ * created from observable logic (“observable actors”) can:
3887
+ *
3888
+ * - Emit snapshots of the observable’s emitted value
3889
+ *
3890
+ * The observable’s emitted value is used as its observable actor’s `context`.
3891
+ *
3892
+ * Sending events to observable actors will have no effect.
3893
+ *
3894
+ * @example
3895
+ *
3896
+ * ```ts
3897
+ * import { createObservableLogic, createActor } from 'xstate';
3898
+ * import { interval } from 'rxjs';
3899
+ *
3900
+ * const logic = createObservableLogic((obj) => interval(1000));
3901
+ *
3902
+ * const actor = createActor(logic);
3903
+ *
3904
+ * actor.subscribe((snapshot) => {
3905
+ * console.log(snapshot.context);
3906
+ * });
3907
+ *
3908
+ * actor.start();
3909
+ * // At every second:
3910
+ * // Logs 0
3911
+ * // Logs 1
3912
+ * // Logs 2
3913
+ * // ...
3914
+ * ```
3915
+ *
3916
+ * @param observableCreator A function that creates an observable. It receives
3917
+ * one argument, an object with the following properties:
3918
+ *
3919
+ * - `input` - Data that was provided to the observable actor
3920
+ * - `self` - The parent actor
3921
+ * - `system` - The actor system to which the observable actor belongs
3922
+ *
3923
+ * It should return a {@link Subscribable}, which is compatible with an RxJS
3924
+ * Observable, although RxJS is not required to create them.
3925
+ * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.
3926
+ * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.
3927
+ */
3928
+
3929
+ function createObservableLogic(observableCreatorOrConfig) {
3930
+ const observableCreator = typeof observableCreatorOrConfig === 'function' ? observableCreatorOrConfig : observableCreatorOrConfig.run;
3931
+ const schemas = typeof observableCreatorOrConfig === 'function' ? undefined : observableCreatorOrConfig.schemas;
3932
+ return createLogic({
3933
+ schemas,
3934
+ context: undefined,
3935
+ run: (args, enq) => {
3936
+ const {
3937
+ event,
3938
+ input,
3939
+ self,
3940
+ system
3941
+ } = args;
3942
+ const emit = args.emit;
3943
+ switch (event.type) {
3944
+ case XSTATE_OBSERVABLE_NEXT:
3945
+ {
3946
+ return {
3947
+ context: event.data
3948
+ };
3949
+ }
3950
+ case XSTATE_OBSERVABLE_ERROR:
3951
+ return {
3952
+ status: 'error',
3953
+ error: event.data,
3954
+ input: undefined,
3955
+ effects: {
3956
+ observable: {
3957
+ status: 'error',
3958
+ error: event.data
3959
+ }
3960
+ }
3961
+ };
3962
+ case XSTATE_OBSERVABLE_COMPLETE:
3963
+ return {
3964
+ status: 'done',
3965
+ input: undefined,
3966
+ effects: {
3967
+ observable: {
3968
+ status: 'done'
3969
+ }
3970
+ }
3971
+ };
3972
+ }
3973
+ enq.effect('observable', () => {
3974
+ const actorSelf = self;
3975
+ const subscription = observableCreator({
3976
+ input,
3977
+ system,
3978
+ self: self,
3979
+ emit: emit
3980
+ }).subscribe({
3981
+ next: value => {
3982
+ system._relay(actorSelf, actorSelf, {
3983
+ type: XSTATE_OBSERVABLE_NEXT,
3984
+ data: value
3985
+ });
3986
+ },
3987
+ error: err => {
3988
+ system._relay(actorSelf, actorSelf, {
3989
+ type: XSTATE_OBSERVABLE_ERROR,
3990
+ data: err
3991
+ });
3992
+ },
3993
+ complete: () => {
3994
+ system._relay(actorSelf, actorSelf, {
3995
+ type: XSTATE_OBSERVABLE_COMPLETE
3996
+ });
3997
+ }
3998
+ });
3999
+ return () => subscription.unsubscribe();
4000
+ });
4001
+ }
4002
+ });
4003
+ }
4004
+
4005
+ /**
4006
+ * Creates event observable logic that listens to an observable that delivers
4007
+ * event objects.
4008
+ *
4009
+ * Event observable actor logic is described by an observable stream of
4010
+ * {@link https://stately.ai/docs/transitions#event-objects | event objects}.
4011
+ * Actors created from event observable logic (“event observable actors”) can:
4012
+ *
4013
+ * - Implicitly send events to its parent actor
4014
+ * - Emit snapshots of its emitted event objects
4015
+ *
4016
+ * Sending events to event observable actors will have no effect.
4017
+ *
4018
+ * @example
4019
+ *
4020
+ * ```ts
4021
+ * import {
4022
+ * createEventObservableLogic,
4023
+ * Subscribable,
4024
+ * EventObject,
4025
+ * createMachine,
4026
+ * createActor
4027
+ * } from 'xstate';
4028
+ * import { fromEvent } from 'rxjs';
4029
+ *
4030
+ * const mouseClickLogic = createEventObservableLogic(
4031
+ * () => fromEvent(document.body, 'click') as Subscribable<EventObject>
4032
+ * );
4033
+ *
4034
+ * const canvasMachine = createMachine({
4035
+ * invoke: {
4036
+ * // Will send mouse `click` events to the canvas actor
4037
+ * src: mouseClickLogic
4038
+ * }
4039
+ * });
4040
+ *
4041
+ * const canvasActor = createActor(canvasMachine);
4042
+ * canvasActor.start();
4043
+ * ```
4044
+ *
4045
+ * @param lazyObservable A function that creates an observable that delivers
4046
+ * event objects. It receives one argument, an object with the following
4047
+ * properties:
4048
+ *
4049
+ * - `input` - Data that was provided to the event observable actor
4050
+ * - `self` - The parent actor
4051
+ * - `system` - The actor system to which the event observable actor belongs.
4052
+ *
4053
+ * It should return a {@link Subscribable}, which is compatible with an RxJS
4054
+ * Observable, although RxJS is not required to create them.
4055
+ */
4056
+
4057
+ function createEventObservableLogic(lazyObservableOrConfig) {
4058
+ const lazyObservable = typeof lazyObservableOrConfig === 'function' ? lazyObservableOrConfig : lazyObservableOrConfig.run;
4059
+
4060
+ // TODO: event types
4061
+ const logic = {
4062
+ config: lazyObservable,
4063
+ transition: (state, event) => {
4064
+ if (state.status !== 'active') {
4065
+ return [state, []];
4066
+ }
4067
+ switch (event.type) {
4068
+ case XSTATE_OBSERVABLE_ERROR:
4069
+ return [{
4070
+ ...state,
4071
+ status: 'error',
4072
+ error: event.data,
4073
+ input: undefined,
4074
+ _subscription: undefined
4075
+ }, []];
4076
+ case XSTATE_OBSERVABLE_COMPLETE:
4077
+ return [{
4078
+ ...state,
4079
+ status: 'done',
4080
+ input: undefined,
4081
+ _subscription: undefined
4082
+ }, []];
4083
+ case XSTATE_STOP:
4084
+ state._subscription.unsubscribe();
4085
+ return [{
4086
+ ...state,
4087
+ status: 'stopped',
4088
+ input: undefined,
4089
+ _subscription: undefined
4090
+ }, []];
4091
+ default:
4092
+ return [state, []];
4093
+ }
4094
+ },
4095
+ initialTransition: (input, _) => [{
4096
+ status: 'active',
4097
+ output: undefined,
4098
+ error: undefined,
4099
+ context: undefined,
4100
+ input,
4101
+ _subscription: undefined
4102
+ }, []],
4103
+ getInitialSnapshot: (actorScope, input) => logic.initialTransition(input, actorScope)[0],
4104
+ start: (state, {
4105
+ self,
4106
+ system,
4107
+ emit
4108
+ }) => {
4109
+ if (state.status === 'done') {
4110
+ // Do not restart a completed observable
4111
+ return;
4112
+ }
4113
+ state._subscription = lazyObservable({
4114
+ input: state.input,
4115
+ system,
4116
+ self,
4117
+ emit
4118
+ }).subscribe({
4119
+ next: value => {
4120
+ if (self._parent) {
4121
+ system._relay(self, self._parent, value);
4122
+ }
4123
+ },
4124
+ error: err => {
4125
+ system._relay(self, self, {
4126
+ type: XSTATE_OBSERVABLE_ERROR,
4127
+ data: err
4128
+ });
4129
+ },
4130
+ complete: () => {
4131
+ system._relay(self, self, {
4132
+ type: XSTATE_OBSERVABLE_COMPLETE
4133
+ });
4134
+ }
4135
+ });
4136
+ },
4137
+ getPersistedSnapshot: ({
4138
+ _subscription,
4139
+ ...snapshot
4140
+ }) => snapshot,
4141
+ restoreSnapshot: snapshot => ({
4142
+ ...snapshot,
4143
+ _subscription: undefined
4144
+ })
4145
+ };
4146
+ return logic;
4147
+ }
4148
+
4149
+ const XSTATE_ASYNC_RESOLVE = 'xstate.async.resolve';
4150
+ const XSTATE_ASYNC_REJECT = 'xstate.async.reject';
4151
+ class TimeoutError extends Error {
4152
+ constructor(timeout) {
4153
+ super(`Async logic timed out after ${timeout}.`);
4154
+ this.name = 'TimeoutError';
4155
+ }
4156
+ }
4157
+
4158
+ /**
4159
+ * Represents an actor created by `createAsyncLogic`.
4160
+ *
4161
+ * The type of `self` within the actor's logic.
4162
+ *
4163
+ * @example
4164
+ *
4165
+ * ```ts
4166
+ * import { createAsyncLogic, createActor } from 'xstate';
4167
+ *
4168
+ * // The actor's resolved output
4169
+ * type Output = string;
4170
+ * // The actor's input.
4171
+ * type Input = { message: string };
4172
+ *
4173
+ * // Actor logic that fetches the url of an image of a cat saying `input.message`.
4174
+ * const logic = createAsyncLogic<Output, Input>({
4175
+ * run: async ({ input, self }, enq) => {
4176
+ * self;
4177
+ * // ^? AsyncActor<Output, Input>
4178
+ * enq.emit({ type: 'request.start' });
4179
+ *
4180
+ * const data = await fetch(
4181
+ * `https://cataas.com/cat/says/${input.message}`
4182
+ * );
4183
+ * const url = await data.json();
4184
+ * return url;
4185
+ * }
4186
+ * });
4187
+ *
4188
+ * const actor = createActor(logic, { input: { message: 'hello world' } });
4189
+ * // ^? AsyncActor<Output, Input>
4190
+ * ```
4191
+ *
4192
+ * @see {@link createAsyncLogic}
4193
+ */
4194
+
4195
+ /**
4196
+ * An actor logic creator which returns async logic as defined by an async
4197
+ * process that resolves or rejects after some time.
4198
+ *
4199
+ * Actors created from async actor logic can:
4200
+ *
4201
+ * - Output the resolved value of the async process
4202
+ * - Error with the rejected value of the async process
4203
+ * - Abort when stopped or timed out
4204
+ *
4205
+ * Sending events to async actors will have no effect.
4206
+ *
4207
+ * @example
4208
+ *
4209
+ * ```ts
4210
+ * const asyncLogic = createAsyncLogic({
4211
+ * id: 'fetch-user',
4212
+ * timeout: '30s',
4213
+ * run: async ({ signal }, enq) => {
4214
+ * enq.emit({ type: 'request.start' });
4215
+ * const result = await fetch('https://example.com/...', {
4216
+ * signal
4217
+ * }).then((data) => data.json());
4218
+ *
4219
+ * return result;
4220
+ * }
4221
+ * });
4222
+ *
4223
+ * const asyncActor = createActor(asyncLogic);
4224
+ * asyncActor.subscribe((snapshot) => {
4225
+ * console.log(snapshot);
4226
+ * });
4227
+ * asyncActor.start();
4228
+ * // => {
4229
+ * // output: undefined,
4230
+ * // status: 'active'
4231
+ * // ...
4232
+ * // }
4233
+ *
4234
+ * // After promise resolves
4235
+ * // => {
4236
+ * // output: { ... },
4237
+ * // status: 'done',
4238
+ * // ...
4239
+ * // }
4240
+ * ```
4241
+ *
4242
+ * @param asyncLogic A config object with a `run` function which returns a
4243
+ * Promise, and accepts an object with the following properties:
4244
+ *
4245
+ * - `input` - Data that was provided to the async actor
4246
+ * - `self` - The async actor ref
4247
+ * - `system` - The actor system to which the async actor belongs
4248
+ * - `signal` - An abort signal for cancellation
4249
+ *
4250
+ * `run` also receives an `enq` object with the following properties:
4251
+ *
4252
+ * - `emit` - Emits an event that can be observed with `actor.on(...)`
4253
+ *
4254
+ * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed
4255
+ */
4256
+
4257
+ function createAsyncLogic(asyncLogic) {
4258
+ const config = asyncLogic;
4259
+ function waitForEffect(self, key) {
4260
+ return new Promise((resolve, reject) => {
4261
+ const subscription = self.subscribe(snapshot => {
4262
+ const effect = snapshot.effects?.[key];
4263
+ if (effect?.status === 'done') {
4264
+ subscription.unsubscribe();
4265
+ resolve(effect.output);
4266
+ } else if (effect?.status === 'error') {
4267
+ subscription.unsubscribe();
4268
+ reject(effect.error);
4269
+ }
4270
+ });
4271
+ });
4272
+ }
4273
+ return createLogic({
4274
+ id: config.id,
4275
+ schemas: config.schemas,
4276
+ context: undefined,
4277
+ run: ({
4278
+ event,
4279
+ input,
4280
+ self,
4281
+ system
4282
+ }, enq) => {
4283
+ switch (event.type) {
4284
+ case XSTATE_ASYNC_RESOLVE:
4285
+ {
4286
+ const resolvedValue = event.data ?? event.output;
4287
+ return {
4288
+ status: 'done',
4289
+ output: resolvedValue,
4290
+ input: undefined,
4291
+ effects: {
4292
+ async: {
4293
+ status: 'done',
4294
+ output: resolvedValue
4295
+ }
4296
+ }
4297
+ };
4298
+ }
4299
+ case XSTATE_ASYNC_REJECT:
4300
+ {
4301
+ const error = event.data ?? event.error;
4302
+ return {
4303
+ status: 'error',
4304
+ error,
4305
+ input: undefined,
4306
+ effects: {
4307
+ async: {
4308
+ status: 'error',
4309
+ error
4310
+ }
4311
+ }
4312
+ };
4313
+ }
4314
+ }
4315
+ if (event.type !== XSTATE_INIT) {
4316
+ return;
4317
+ }
4318
+ enq.effect(() => {
4319
+ const actorSelf = self;
4320
+ const controller = new AbortController();
4321
+ const timeout = config.timeout;
4322
+ const timeoutMs = parseDelayToMilliseconds(timeout);
4323
+ const timeoutId = timeoutMs === undefined ? undefined : system._clock.setTimeout(() => {
4324
+ if (self.getSnapshot().status !== 'active') {
4325
+ return;
4326
+ }
4327
+ controller.abort();
4328
+ system._relay(actorSelf, actorSelf, {
4329
+ type: XSTATE_ASYNC_REJECT,
4330
+ data: new TimeoutError(timeout)
4331
+ });
4332
+ }, timeoutMs);
4333
+ const clearTimeout = () => {
4334
+ if (timeoutId !== undefined) {
4335
+ system._clock.clearTimeout(timeoutId);
4336
+ }
4337
+ };
4338
+ const resolvedPromise = Promise.resolve(config.run({
4339
+ input,
4340
+ system,
4341
+ self: self,
4342
+ signal: controller.signal
4343
+ }, {
4344
+ emit: enq.emit,
4345
+ step: async (key, exec) => {
4346
+ const effect = self.getSnapshot().effects?.[key];
4347
+ if (effect?.status === 'done') {
4348
+ return effect.output;
4349
+ }
4350
+ if (effect?.status === 'error') {
4351
+ throw effect.error;
4352
+ }
4353
+ if (effect?.status === 'active') {
4354
+ return waitForEffect(self, key);
4355
+ }
4356
+ system._relay(actorSelf, actorSelf, {
4357
+ type: XSTATE_LOGIC_EFFECT_START,
4358
+ key
4359
+ });
4360
+ try {
4361
+ const output = await exec();
4362
+ system._relay(actorSelf, actorSelf, {
4363
+ type: XSTATE_LOGIC_EFFECT_RESOLVE,
4364
+ key,
4365
+ output
4366
+ });
4367
+ return output;
4368
+ } catch (error) {
4369
+ system._relay(actorSelf, actorSelf, {
4370
+ type: XSTATE_LOGIC_EFFECT_REJECT,
4371
+ key,
4372
+ error
4373
+ });
4374
+ throw error;
4375
+ }
4376
+ }
4377
+ }));
4378
+ resolvedPromise.then(response => {
4379
+ clearTimeout();
4380
+ if (self.getSnapshot().status !== 'active') {
4381
+ return;
4382
+ }
4383
+ system._relay(actorSelf, actorSelf, {
4384
+ type: XSTATE_ASYNC_RESOLVE,
4385
+ data: response
4386
+ });
4387
+ }, errorData => {
4388
+ clearTimeout();
4389
+ if (self.getSnapshot().status !== 'active') {
4390
+ return;
4391
+ }
4392
+ system._relay(actorSelf, actorSelf, {
4393
+ type: XSTATE_ASYNC_REJECT,
4394
+ data: errorData
4395
+ });
4396
+ });
4397
+ return () => {
4398
+ controller.abort();
4399
+ clearTimeout();
4400
+ };
4401
+ });
4402
+ return {
4403
+ effects: {
4404
+ async: {
4405
+ status: 'active'
4406
+ }
4407
+ }
4408
+ };
4409
+ }
4410
+ });
4411
+ }
4412
+
4413
+ const emptyLogic = /* #__PURE__ */createLogic({
4414
+ context: undefined,
4415
+ run: () => undefined
4416
+ });
4417
+ function createEmptyActor() {
4418
+ return createActor(emptyLogic);
4419
+ }
4420
+
4421
+ export { $$ACTOR_TYPE as $, Actor as A, subscriptionLogic as B, resolveReferencedActor as C, mapValues as D, createInvokeId as E, getDelayedTransitions as F, evaluateCandidate as G, formatTransition as H, toTransitionConfigArray as I, createInvokeTimeoutEvent as J, getCandidates as K, formatRouteTransitions as L, resolveStateValue as M, NULL_EVENT as N, getAllStateNodes as O, ProcessingStatus as P, createMachineSnapshot as Q, isInFinalState as R, STATE_DELIMITER as S, TimeoutError as T, transitionNode as U, resolveActionsWithContext as V, toStatePath as W, isStateId as X, getStateNodeByPath as Y, getPersistedSnapshot as Z, XSTATE_INIT as _, macrostep as a, createInitEvent as b, createActor as c, initialMicrostep as d, isMachineSnapshot as e, getStateNodes as f, getProperAncestors as g, getAllOwnEventDescriptors as h, isAtomicStateNode as i, matchesState as j, checkStateIn as k, pathToStateValue as l, matchesEventDescriptor as m, toObserver as n, isBuiltInExecutableAction as o, parseDelayToMilliseconds as p, createEmptyActor as q, createCallbackLogic as r, createObservableLogic as s, toArray as t, createEventObservableLogic as u, createLogic as v, createAsyncLogic as w, createListenerLogic as x, listenerLogic as y, createSubscriptionLogic as z };