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