xstate 5.32.0 → 6.0.0-alpha.1

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