xstate 6.0.0-alpha.7 → 6.0.0-alpha.71

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