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